Open History to see the last commit
1import { planPinnedMove } from "@t3tools/client-runtime/state/thread-sort";
2import {
3 createPendingThreadOrder,
4 createThreadMovePlanner,
5 threadOrderAfterMove,
6 threadDropLifecycle,
7 reconcilePendingThreadOrder,
8 type PendingThreadOrder,
9} from "./threadOrder";
10import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
11import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
12import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
13import {
14 CommandId,
15 EnvironmentId,
16 MessageId,
17 ProjectId,
18 ProviderInstanceId,
19 ThreadId,
20 TurnId,
21} from "@t3tools/contracts";
22import { describe, expect, it } from "vite-plus/test";
23
24import type { PendingNewTask } from "../../state/use-pending-new-tasks";
25import { threadJumpTarget } from "../keyboard/threadKeyboardShortcuts";
26import {
27 buildThreadListV2Items,
28 buildThreadListV2ListItems,
29 getThreadListV2OrderedSection,
30 resolveThreadListV2Enabled,
31 resolveThreadListV2SnoozeMenuSelection,
32 resolveThreadListV2SnoozeGateExpiryMs,
33 resolveThreadListV2Status,
34 resolveThreadListV2SwipeActions,
35 sortThreadsForListV2,
36} from "./threadListV2";
37
38const environmentId = EnvironmentId.make("environment-1");
39
40function makeThread(
41 input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
42): EnvironmentThreadShell {
43 return {
44 environmentId,
45 projectId: ProjectId.make("project-1"),
46 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
47 runtimeMode: "full-access",
48 interactionMode: "default",
49 branch: null,
50 worktreePath: null,
51 pullRequests: [],
52 latestTurn: null,
53 createdAt: "2026-06-01T00:00:00.000Z",
54 updatedAt: "2026-06-01T00:00:00.000Z",
55 archivedAt: null,
56 settledOverride: null,
57 settledAt: null,
58 session: null,
59 latestUserMessageAt: null,
60 hasPendingApprovals: false,
61 hasPendingUserInput: false,
62 hasActionableProposedPlan: false,
63 ...input,
64 };
65}
66
67const NOW = "2026-06-02T00:00:00.000Z";
68const linkedPullRequest = {
69 projectId: ProjectId.make("project-1"),
70 repository: "pingdotgg/t3code",
71 number: 42,
72 url: "https://github.com/pingdotgg/t3code/pull/42",
73};
74
75describe("resolveThreadListV2SnoozeMenuSelection", () => {
76 it("accepts a displayed evening preset while its wake time is still future", () => {
77 const menuOpenedAt = new Date(2026, 4, 8, 16, 59, 30);
78 const selectedAt = new Date(2026, 4, 8, 17, 0, 30);
79 const displayedPresets = resolveSnoozePresets(menuOpenedAt);
80
81 const selection = resolveThreadListV2SnoozeMenuSelection({
82 event: "snooze:evening",
83 displayedPresets,
84 now: selectedAt,
85 });
86
87 expect(selection).toEqual({
88 _tag: "selected",
89 preset: displayedPresets.find((preset) => preset.id === "evening"),
90 });
91 });
92
93 it("expires a displayed preset once its wake time has passed", () => {
94 const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 16, 59, 30));
95
96 expect(
97 resolveThreadListV2SnoozeMenuSelection({
98 event: "snooze:evening",
99 displayedPresets,
100 now: new Date(2026, 4, 8, 18, 0, 1),
101 }),
102 ).toEqual({ _tag: "expired" });
103 });
104
105 it("recomputes presets that remain available instead of using old timestamps", () => {
106 const displayedPresets = resolveSnoozePresets(new Date(2026, 4, 8, 10));
107 const selectedAt = new Date(2026, 4, 8, 10, 30);
108 const selection = resolveThreadListV2SnoozeMenuSelection({
109 event: "snooze:hour",
110 displayedPresets,
111 now: selectedAt,
112 });
113
114 expect(selection._tag).toBe("selected");
115 if (selection._tag === "selected") {
116 expect(selection.preset.snoozedUntil).toBe(
117 new Date(selectedAt.getTime() + 60 * 60 * 1_000).toISOString(),
118 );
119 }
120 });
121});
122
123describe("resolveThreadListV2Enabled", () => {
124 it("defaults on when the device has never chosen", () => {
125 expect(
126 resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: true }),
127 ).toBe(true);
128 });
129
130 it("honors an explicit legacy opt-in", () => {
131 expect(resolveThreadListV2Enabled({ legacyPreference: true, preferencesLoaded: true })).toBe(
132 false,
133 );
134 expect(resolveThreadListV2Enabled({ legacyPreference: false, preferencesLoaded: true })).toBe(
135 true,
136 );
137 });
138
139 it("holds the default while preferences are still loading so the list does not remount", () => {
140 expect(
141 resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: false }),
142 ).toBe(true);
143 });
144});
145
146describe("resolveThreadListV2Status", () => {
147 it("prioritizes approval over a running session", () => {
148 const thread = makeThread({
149 id: ThreadId.make("t"),
150 title: "t",
151 hasPendingApprovals: true,
152 session: {
153 threadId: ThreadId.make("t"),
154 status: "running",
155 providerName: "Codex",
156 providerInstanceId: ProviderInstanceId.make("codex"),
157 runtimeMode: "full-access",
158 activeTurnId: null,
159 lastError: null,
160 updatedAt: NOW,
161 },
162 });
163 expect(resolveThreadListV2Status(thread)).toBe("approval");
164 });
165
166 it("resolves ready for quiescent threads", () => {
167 expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
168 "ready",
169 );
170 });
171});
172
173describe("queued messages keep a settled thread active", () => {
174 const threads = [
175 makeThread({ id: ThreadId.make("active"), title: "Active" }),
176 makeThread({ id: ThreadId.make("settled"), title: "Settled", settledOverride: "settled" }),
177 makeThread({
178 id: ThreadId.make("settled-queued"),
179 title: "Settled with outbox",
180 settledOverride: "settled",
181 }),
182 ];
183 const queuedThreadKeys = new Set([`${environmentId}:settled-queued`]);
184
185 it("lists the thread in the active block instead of the settled shelf", () => {
186 const layout = buildThreadListV2Items({
187 threads,
188 environmentId: null,
189 searchQuery: "",
190 now: NOW,
191 queuedThreadKeys,
192 });
193 expect(layout.items.map((item) => [item.thread.id, item.variant] as const)).toEqual([
194 ["active", "card"],
195 ["settled-queued", "card"],
196 ["settled", "slim"],
197 ]);
198 expect(layout.settledCount).toBe(1);
199 });
200
201 it("includes it in the reorderable active section", () => {
202 expect(
203 getThreadListV2OrderedSection({ threads, section: "active", now: NOW, queuedThreadKeys }).map(
204 (thread) => thread.id,
205 ),
206 ).toEqual(["active", "settled-queued"]);
207 expect(
208 getThreadListV2OrderedSection({ threads, section: "active", now: NOW }).map(
209 (thread) => thread.id,
210 ),
211 ).toEqual(["active"]);
212 });
213});
214
215describe("resolveThreadListV2SwipeActions", () => {
216 it("offers settle and snooze for an active snoozable thread", () => {
217 expect(
218 resolveThreadListV2SwipeActions({
219 variant: "card",
220 settlementSupported: true,
221 snoozeSupported: true,
222 snoozable: true,
223 }),
224 ).toEqual({ primary: "settle", secondary: "snooze" });
225 });
226
227 it("offers un-settle and snooze for settled history", () => {
228 expect(
229 resolveThreadListV2SwipeActions({
230 variant: "slim",
231 settlementSupported: true,
232 snoozeSupported: true,
233 snoozable: true,
234 }),
235 ).toEqual({ primary: "unsettle", secondary: "snooze" });
236 });
237
238 it("omits snooze when the server or thread does not allow it", () => {
239 expect(
240 resolveThreadListV2SwipeActions({
241 variant: "card",
242 settlementSupported: true,
243 snoozeSupported: false,
244 snoozable: true,
245 }),
246 ).toEqual({ primary: "settle", secondary: null });
247 expect(
248 resolveThreadListV2SwipeActions({
249 variant: "card",
250 settlementSupported: true,
251 snoozeSupported: true,
252 snoozable: false,
253 }),
254 ).toEqual({ primary: "settle", secondary: null });
255 });
256
257 it("falls back to archive only for a pre-lifecycle server", () => {
258 expect(
259 resolveThreadListV2SwipeActions({
260 variant: "card",
261 settlementSupported: false,
262 snoozeSupported: false,
263 snoozable: true,
264 }),
265 ).toEqual({ primary: "archive", secondary: null });
266 });
267
268 it("offers wake and no snooze on a snoozed row", () => {
269 expect(
270 resolveThreadListV2SwipeActions({
271 variant: "slim",
272 settlementSupported: true,
273 snoozeSupported: true,
274 snoozable: true,
275 snoozed: true,
276 }),
277 ).toEqual({ primary: "unsnooze", secondary: null });
278 });
279});
280
281describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
282 it("reports when an unadopted turn's grace window lapses", () => {
283 const thread = makeThread({
284 id: ThreadId.make("t"),
285 title: "t",
286 latestUserMessageAt: "2026-06-02T00:00:30.000Z",
287 });
288 expect(resolveThreadListV2SnoozeGateExpiryMs(thread, { now: "2026-06-02T00:01:00.000Z" })).toBe(
289 Date.parse("2026-06-02T00:02:30.000Z"),
290 );
291 });
292
293 it("returns null once the thread is snoozable or when only data can unblock it", () => {
294 expect(
295 resolveThreadListV2SnoozeGateExpiryMs(
296 makeThread({ id: ThreadId.make("ready"), title: "Ready" }),
297 { now: NOW },
298 ),
299 ).toBe(null);
300 expect(
301 resolveThreadListV2SnoozeGateExpiryMs(
302 makeThread({
303 id: ThreadId.make("blocked"),
304 title: "Blocked",
305 hasPendingApprovals: true,
306 latestUserMessageAt: NOW,
307 }),
308 { now: NOW },
309 ),
310 ).toBe(null);
311 });
312});
313
314describe("sortThreadsForListV2", () => {
315 it("honors a saved active order and leaves new threads above it", () => {
316 const sorted = sortThreadsForListV2([
317 { id: "newer-arranged", createdAt: "2026-06-01T12:00:00.000Z", activeOrderKey: "t" },
318 { id: "older-arranged", createdAt: "2026-06-01T08:00:00.000Z", activeOrderKey: "f" },
319 { id: "new", createdAt: "2026-06-01T13:00:00.000Z" },
320 ]);
321 expect(sorted.map((thread) => thread.id)).toEqual(["new", "older-arranged", "newer-arranged"]);
322 });
323
324 it("orders by creation time, newest first, ignoring activity", () => {
325 const sorted = sortThreadsForListV2([
326 { id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
327 { id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
328 { id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
329 ]);
330 expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
331 });
332
333 it("surfaces an un-settled thread at the top via its re-entry stamp", () => {
334 const sorted = sortThreadsForListV2([
335 {
336 id: "old-unsettled",
337 createdAt: "2026-06-01T08:00:00.000Z",
338 unsettledAt: "2026-06-01T13:00:00.000Z",
339 },
340 { id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
341 { id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
342 ]);
343 expect(sorted.map((thread) => thread.id)).toEqual(["old-unsettled", "newest", "middle"]);
344 });
345});
346
347describe("getThreadListV2OrderedSection", () => {
348 it("uses each saved order and excludes settled, snoozed, and archived rows", () => {
349 const threads = [
350 makeThread({ id: ThreadId.make("active-later"), title: "Later", activeOrderKey: "t" }),
351 makeThread({ id: ThreadId.make("active-first"), title: "First", activeOrderKey: "f" }),
352 makeThread({ id: ThreadId.make("active-new"), title: "New" }),
353 makeThread({
354 id: ThreadId.make("pinned-later"),
355 title: "Pinned later",
356 pinnedAt: NOW,
357 pinOrderKey: "t",
358 activeOrderKey: "f",
359 }),
360 makeThread({
361 id: ThreadId.make("pinned-first"),
362 title: "Pinned first",
363 pinnedAt: NOW,
364 pinOrderKey: "f",
365 activeOrderKey: "t",
366 }),
367 makeThread({ id: ThreadId.make("settled"), title: "Settled", settledOverride: "settled" }),
368 makeThread({ id: ThreadId.make("archived"), title: "Archived", archivedAt: NOW }),
369 makeThread({
370 id: ThreadId.make("snoozed"),
371 title: "Snoozed",
372 snoozedUntil: "2026-06-03T10:00:00.000Z",
373 snoozedAt: NOW,
374 }),
375 makeThread({
376 id: ThreadId.make("pinned-snoozed"),
377 title: "Pinned snoozed",
378 pinnedAt: NOW,
379 snoozedUntil: "2026-06-03T10:00:00.000Z",
380 snoozedAt: NOW,
381 }),
382 ];
383 expect(
384 getThreadListV2OrderedSection({ threads, section: "active", now: NOW }).map(
385 (thread) => thread.id,
386 ),
387 ).toEqual(["active-new", "active-first", "active-later"]);
388 expect(
389 getThreadListV2OrderedSection({ threads, section: "pinned", now: NOW }).map(
390 (thread) => thread.id,
391 ),
392 ).toEqual(["pinned-first", "pinned-later"]);
393 });
394});
395
396describe("buildThreadListV2Items", () => {
397 it("places a persisted settled thread in the settled shelf", () => {
398 const thread = makeThread({
399 id: ThreadId.make("linked-merged"),
400 title: "Linked merged pull request",
401 linkedPullRequest,
402 settledOverride: "settled",
403 settledAt: NOW,
404 });
405 const layout = buildThreadListV2Items({
406 threads: [thread],
407 environmentId: null,
408 searchQuery: "",
409 now: NOW,
410 });
411
412 expect(layout.settledCount).toBe(1);
413 expect(layout.items[0]?.variant).toBe("slim");
414 });
415
416 it("hides snoozed threads and counts them — visibility parity with web", () => {
417 const layout = buildThreadListV2Items({
418 threads: [
419 makeThread({ id: ThreadId.make("active"), title: "Active" }),
420 makeThread({
421 id: ThreadId.make("snoozed"),
422 title: "Snoozed",
423 snoozedUntil: "2026-06-03T09:00:00.000Z",
424 snoozedAt: "2026-06-01T12:00:00.000Z",
425 }),
426 makeThread({
427 id: ThreadId.make("woken"),
428 title: "Woken",
429 // Wake time already passed: back in the active list.
430 snoozedUntil: "2026-06-01T18:00:00.000Z",
431 snoozedAt: "2026-06-01T12:00:00.000Z",
432 }),
433 ],
434 environmentId: null,
435 searchQuery: "",
436 now: NOW,
437 });
438
439 // Same createdAt → static sort tiebreaks by id; the point is the woken
440 // thread is BACK in the card block and the snoozed one is gone.
441 expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
442 expect(layout.snoozedCount).toBe(1);
443 });
444
445 it("places settled pinned threads in the settled shelf", () => {
446 const layout = buildThreadListV2Items({
447 threads: [
448 makeThread({ id: ThreadId.make("active"), title: "Active" }),
449 makeThread({
450 id: ThreadId.make("pinned-settled"),
451 title: "Pinned while settled",
452 pinnedAt: "2026-06-01T12:00:00.000Z",
453 settledOverride: "settled",
454 settledAt: "2026-06-01T12:00:00.000Z",
455 }),
456 ],
457 environmentId: null,
458 searchQuery: "",
459 now: NOW,
460 });
461
462 expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "pinned-settled"]);
463 expect(layout.items.map((item) => item.pinned)).toEqual([false, false]);
464 expect(layout.settledCount).toBe(1);
465 });
466
467 it("keeps active pinned threads in the pinned block", () => {
468 const pinned = makeThread({
469 id: ThreadId.make("pinned"),
470 title: "Pinned thread",
471 pinnedAt: "2026-06-01T12:00:00.000Z",
472 });
473 const layout = buildThreadListV2Items({
474 threads: [pinned],
475 environmentId: null,
476 searchQuery: "",
477 now: NOW,
478 });
479
480 expect(layout.items[0]).toMatchObject({
481 thread: { id: "pinned" },
482 variant: "card",
483 pinned: true,
484 });
485 expect(layout.settledCount).toBe(0);
486 });
487
488 it("snooze hides a pinned thread and wake restores it to the pinned block", () => {
489 const snoozedInput = {
490 threads: [
491 makeThread({ id: ThreadId.make("active"), title: "Active" }),
492 makeThread({
493 id: ThreadId.make("pinned-snoozed"),
494 title: "Pinned and snoozed",
495 pinnedAt: "2026-06-01T12:00:00.000Z",
496 snoozedUntil: "2026-06-03T09:00:00.000Z",
497 snoozedAt: "2026-06-01T11:00:00.000Z",
498 }),
499 ],
500 environmentId: null,
501 searchQuery: "",
502 };
503
504 // Before the wake time: the snooze wins; the pin holds underneath.
505 const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
506 expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
507 expect(whileSnoozed.snoozedCount).toBe(1);
508
509 // After the wake time: the thread returns pinned, back on top.
510 const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });
511 expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
512 expect(afterWake.items[0]?.pinned).toBe(true);
513 expect(afterWake.snoozedCount).toBe(0);
514 });
515
516 it("classifies snooze with the second-precise clock and reports the next wake", () => {
517 const layout = buildThreadListV2Items({
518 threads: [
519 makeThread({
520 id: ThreadId.make("just-woke"),
521 title: "Just woke",
522 // Woke 30s ago: hidden under the minute-floored clock, visible
523 // under the precise one.
524 snoozedUntil: "2026-06-02T00:00:30.000Z",
525 snoozedAt: "2026-06-01T12:00:00.000Z",
526 }),
527 makeThread({
528 id: ThreadId.make("still-snoozed"),
529 title: "Still snoozed",
530 snoozedUntil: "2026-06-02T09:00:00.000Z",
531 snoozedAt: "2026-06-01T12:00:00.000Z",
532 }),
533 ],
534 environmentId: null,
535 searchQuery: "",
536 now: "2026-06-02T00:01:07.500Z",
537 });
538
539 expect(layout.items.map((item) => item.thread.id)).toEqual(["just-woke"]);
540 expect(layout.snoozedCount).toBe(1);
541 expect(layout.nextSnoozeWakeAt).toBe("2026-06-02T09:00:00.000Z");
542 });
543
544 it("builds snoozed rows between active and settled when the shelf is expanded", () => {
545 const layout = buildThreadListV2Items({
546 threads: [
547 makeThread({ id: ThreadId.make("active"), title: "Active" }),
548 makeThread({
549 id: ThreadId.make("settled"),
550 title: "Settled",
551 settledOverride: "settled",
552 settledAt: NOW,
553 }),
554 makeThread({
555 id: ThreadId.make("later"),
556 title: "Wakes later",
557 snoozedUntil: "2026-06-03T09:00:00.000Z",
558 snoozedAt: "2026-06-01T12:00:00.000Z",
559 }),
560 makeThread({
561 id: ThreadId.make("sooner"),
562 title: "Wakes sooner",
563 snoozedUntil: "2026-06-02T09:00:00.000Z",
564 snoozedAt: "2026-06-01T12:00:00.000Z",
565 }),
566 ],
567 environmentId: null,
568 searchQuery: "",
569 now: NOW,
570 snoozedShelfExpanded: true,
571 });
572
573 expect(layout.items.map((item) => item.thread.id)).toEqual([
574 "active",
575 "sooner",
576 "later",
577 "settled",
578 ]);
579 expect(layout.items.map((item) => item.snoozed)).toEqual([false, true, true, false]);
580 expect(layout.snoozedShelfHeaderIndex).toBe(1);
581 expect(layout.snoozedCount).toBe(2);
582 });
583
584 it("collapses to a header-only shelf", () => {
585 const layout = buildThreadListV2Items({
586 threads: [
587 makeThread({
588 id: ThreadId.make("snoozed"),
589 title: "Snoozed",
590 snoozedUntil: "2026-06-03T09:00:00.000Z",
591 snoozedAt: "2026-06-01T12:00:00.000Z",
592 }),
593 ],
594 environmentId: null,
595 searchQuery: "",
596 now: NOW,
597 });
598
599 expect(layout.items).toEqual([]);
600 expect(layout.snoozedCount).toBe(1);
601 expect(layout.snoozedShelfHeaderIndex).toBe(0);
602 });
603
604 it("keeps the selected thread on a collapsed shelf", () => {
605 const layout = buildThreadListV2Items({
606 threads: [
607 makeThread({
608 id: ThreadId.make("open"),
609 title: "Open",
610 snoozedUntil: "2026-06-03T09:00:00.000Z",
611 snoozedAt: "2026-06-01T12:00:00.000Z",
612 }),
613 makeThread({
614 id: ThreadId.make("other"),
615 title: "Other",
616 snoozedUntil: "2026-06-03T10:00:00.000Z",
617 snoozedAt: "2026-06-01T12:00:00.000Z",
618 }),
619 ],
620 environmentId: null,
621 searchQuery: "",
622 now: NOW,
623 selectedThreadKey: `${environmentId}:open`,
624 });
625
626 expect(layout.items.map((item) => item.thread.id)).toEqual(["open"]);
627 expect(layout.items[0]?.snoozed).toBe(true);
628 expect(layout.snoozedCount).toBe(2);
629 });
630
631 it("keeps snoozed threads visible on environments without the snooze capability", () => {
632 const layout = buildThreadListV2Items({
633 threads: [
634 makeThread({
635 id: ThreadId.make("snoozed"),
636 title: "Snoozed",
637 snoozedUntil: "2026-06-03T09:00:00.000Z",
638 snoozedAt: "2026-06-01T12:00:00.000Z",
639 }),
640 ],
641 environmentId: null,
642 searchQuery: "",
643 snoozeEnvironmentIds: new Set(),
644 now: NOW,
645 });
646
647 expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
648 expect(layout.snoozedCount).toBe(0);
649 });
650
651 it("partitions settled threads into a slim shelf", () => {
652 const layout = buildThreadListV2Items({
653 threads: [
654 makeThread({ id: ThreadId.make("active"), title: "Active" }),
655 makeThread({
656 id: ThreadId.make("settled"),
657 title: "Settled",
658 settledOverride: "settled",
659 settledAt: NOW,
660 }),
661 makeThread({
662 id: ThreadId.make("settled-2"),
663 title: "Settled 2",
664 settledOverride: "settled",
665 settledAt: NOW,
666 }),
667 ],
668 environmentId: null,
669 searchQuery: "",
670 now: NOW,
671 });
672
673 expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
674 ["active", "card"],
675 ["settled", "slim"],
676 ["settled-2", "slim"],
677 ]);
678 expect(layout.items.map((item) => item.isLast)).toEqual([false, false, true]);
679 expect(layout.settledCount).toBe(2);
680 expect(layout.settledShelfHeaderIndex).toBe(1);
681 });
682
683 it("collapses settled threads to a counted shelf header", () => {
684 const layout = buildThreadListV2Items({
685 threads: [
686 makeThread({ id: ThreadId.make("active"), title: "Active" }),
687 makeThread({
688 id: ThreadId.make("settled"),
689 title: "Settled",
690 settledOverride: "settled",
691 settledAt: NOW,
692 }),
693 ],
694 environmentId: null,
695 searchQuery: "",
696 now: NOW,
697 settledShelfExpanded: false,
698 });
699
700 expect(layout.items.map((item) => item.thread.id)).toEqual(["active"]);
701 expect(layout.settledCount).toBe(1);
702 expect(layout.settledShelfHeaderIndex).toBe(1);
703 });
704
705 it("keeps the selected settled thread visible when its shelf is collapsed", () => {
706 const layout = buildThreadListV2Items({
707 threads: [
708 makeThread({
709 id: ThreadId.make("selected"),
710 title: "Selected",
711 settledOverride: "settled",
712 settledAt: NOW,
713 }),
714 makeThread({
715 id: ThreadId.make("other"),
716 title: "Other",
717 settledOverride: "settled",
718 settledAt: NOW,
719 }),
720 ],
721 environmentId: null,
722 searchQuery: "",
723 now: NOW,
724 settledShelfExpanded: false,
725 selectedThreadKey: `${environmentId}:selected`,
726 });
727
728 expect(layout.items.map((item) => item.thread.id)).toEqual(["selected"]);
729 expect(layout.settledCount).toBe(2);
730 expect(layout.settledShelfHeaderIndex).toBe(0);
731 });
732
733 it("keeps cards in creation order while settled sorts by recency", () => {
734 const { items } = buildThreadListV2Items({
735 threads: [
736 makeThread({
737 id: ThreadId.make("older-created"),
738 title: "Older",
739 createdAt: "2026-06-01T08:00:00.000Z",
740 updatedAt: NOW, // recent activity must NOT promote it
741 }),
742 makeThread({
743 id: ThreadId.make("newer-created"),
744 title: "Newer",
745 createdAt: "2026-06-01T12:00:00.000Z",
746 }),
747 ],
748 environmentId: null,
749 searchQuery: "",
750 now: NOW,
751 });
752
753 expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
754 });
755
756 it("sorts settled threads by their persisted settlement timestamp", () => {
757 const { items } = buildThreadListV2Items({
758 threads: [
759 makeThread({
760 id: ThreadId.make("settled-newer"),
761 title: "Settled newer",
762 settledOverride: "settled",
763 settledAt: "2026-06-01T12:00:00.000Z",
764 latestUserMessageAt: "2026-06-01T08:00:00.000Z",
765 }),
766 makeThread({
767 id: ThreadId.make("settled-older"),
768 title: "Settled older",
769 settledOverride: "settled",
770 settledAt: "2026-06-01T10:00:00.000Z",
771 latestUserMessageAt: "2026-06-01T09:00:00.000Z",
772 }),
773 ],
774 environmentId: null,
775 searchQuery: "",
776 now: NOW,
777 });
778
779 expect(items.map((item) => item.thread.id)).toEqual(["settled-newer", "settled-older"]);
780 });
781
782 it("keeps settled threads in the tail and filters by search query", () => {
783 const { items } = buildThreadListV2Items({
784 threads: [
785 makeThread({ id: ThreadId.make("match"), title: "Fix login bug" }),
786 makeThread({ id: ThreadId.make("miss"), title: "Greeting" }),
787 makeThread({
788 id: ThreadId.make("settled"),
789 title: "Fix login again",
790 settledOverride: "settled",
791 settledAt: NOW,
792 }),
793 ],
794 environmentId: null,
795 searchQuery: "login",
796 now: NOW,
797 });
798
799 expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
800 ["match", "card"],
801 ["settled", "slim"],
802 ]);
803 });
804
805 it("includes a thread matched by message content", () => {
806 const thread = makeThread({
807 id: ThreadId.make("content-match"),
808 title: "Unrelated title",
809 });
810 const { items } = buildThreadListV2Items({
811 threads: [thread],
812 environmentId: null,
813 searchQuery: "relay reconnect",
814 matchedThreadKeys: new Set([
815 threadSearchMatchKey({
816 environmentId,
817 threadId: thread.id,
818 }),
819 ]),
820 now: NOW,
821 });
822
823 expect(items.map((item) => item.thread.id)).toEqual(["content-match"]);
824 });
825
826 it("scopes the flat list to one project", () => {
827 const otherProjectId = ProjectId.make("project-2");
828 const { items } = buildThreadListV2Items({
829 threads: [
830 makeThread({ id: ThreadId.make("included"), title: "Included" }),
831 makeThread({
832 id: ThreadId.make("excluded"),
833 projectId: otherProjectId,
834 title: "Excluded",
835 }),
836 ],
837 environmentId: null,
838 projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
839 searchQuery: "",
840 now: NOW,
841 });
842
843 expect(items.map((item) => item.thread.id)).toEqual(["included"]);
844 });
845
846 it("scopes the flat list to every environment member of a logical project", () => {
847 const remoteEnvironmentId = EnvironmentId.make("environment-remote");
848 const { items } = buildThreadListV2Items({
849 threads: [
850 makeThread({ id: ThreadId.make("local"), title: "Local" }),
851 makeThread({
852 environmentId: remoteEnvironmentId,
853 id: ThreadId.make("remote"),
854 title: "Remote",
855 }),
856 ],
857 environmentId: null,
858 projectRefs: [
859 { environmentId, projectId: ProjectId.make("project-1") },
860 { environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
861 ],
862 searchQuery: "",
863 now: NOW,
864 });
865
866 expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
867 });
868});
869
870describe("buildThreadListV2Items settled paging", () => {
871 it("caps the settled tail at settledLimit and reports the hidden count", () => {
872 const threads = [
873 makeThread({ id: ThreadId.make("active"), title: "Active" }),
874 ...Array.from({ length: 4 }, (_, index) =>
875 makeThread({
876 id: ThreadId.make(`settled-${index}`),
877 title: `Settled ${index}`,
878 settledOverride: "settled",
879 settledAt: `2026-06-01T0${index}:10:00.000Z`,
880 latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
881 // A turn adopted the message (same requestedAt): without it the
882 // thread reads as a queued turn start, which never settles.
883 latestTurn: {
884 turnId: TurnId.make(`turn-${index}`),
885 state: "completed",
886 requestedAt: `2026-06-01T0${index}:00:00.000Z`,
887 startedAt: `2026-06-01T0${index}:00:00.000Z`,
888 completedAt: `2026-06-01T0${index}:10:00.000Z`,
889 assistantMessageId: null,
890 },
891 }),
892 ),
893 ];
894
895 const layout = buildThreadListV2Items({
896 threads,
897 environmentId: null,
898 searchQuery: "",
899 settledLimit: 2,
900 now: NOW,
901 });
902
903 expect(layout.hiddenSettledCount).toBe(2);
904 expect(layout.items.filter((item) => item.variant === "slim")).toHaveLength(2);
905 // Most recent settled first — the hidden ones are the oldest.
906 expect(layout.items.map((item) => item.thread.id)).toEqual([
907 "active",
908 "settled-3",
909 "settled-2",
910 ]);
911 });
912});
913
914function makePendingTask(id: string): PendingNewTask {
915 const creation = {
916 projectId: ProjectId.make("project-1"),
917 workspaceMode: "worktree" as const,
918 branch: null,
919 worktreePath: null,
920 };
921 return {
922 kind: "pending",
923 key: `pending-task:${id}`,
924 environmentId,
925 projectId: creation.projectId,
926 projectTitle: undefined,
927 projectCwd: undefined,
928 branch: null,
929 title: id,
930 createdAt: NOW,
931 message: {
932 environmentId,
933 threadId: ThreadId.make(`thread-${id}`),
934 messageId: MessageId.make(id),
935 commandId: CommandId.make(`command-${id}`),
936 text: id,
937 attachments: [],
938 createdAt: NOW,
939 creation,
940 },
941 creation,
942 };
943}
944
945describe("buildThreadListV2ListItems", () => {
946 const layout = buildThreadListV2Items({
947 threads: [
948 makeThread({ id: ThreadId.make("active"), title: "active" }),
949 makeThread({
950 id: ThreadId.make("settled"),
951 title: "settled",
952 settledOverride: "settled",
953 settledAt: NOW,
954 }),
955 ],
956 environmentId: null,
957 searchQuery: "",
958 now: NOW,
959 });
960
961 it("splices queued tasks between the active block and the settled tail", () => {
962 const items = buildThreadListV2ListItems({
963 items: layout.items,
964 pendingTasks: [makePendingTask("queued-1"), makePendingTask("queued-2")],
965 settledCount: layout.settledCount,
966 settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
967 });
968
969 expect(
970 items.map((item) =>
971 item.type === "v2-pending"
972 ? item.pendingTask.title
973 : item.type === "v2-thread"
974 ? item.item.thread.id
975 : item.type === "v2-snoozed-shelf"
976 ? "snoozed-shelf"
977 : "settled-shelf",
978 ),
979 ).toEqual(["active", "queued-1", "queued-2", "settled-shelf", "settled"]);
980 // Only the leading queued row labels the section, exactly like Settled.
981 expect(
982 items.filter((item) => item.type === "v2-pending" && item.showPendingDivider),
983 ).toHaveLength(1);
984 });
985
986 it("ends the list with queued tasks when nothing has settled yet", () => {
987 const activeOnly = buildThreadListV2Items({
988 threads: [makeThread({ id: ThreadId.make("active"), title: "active" })],
989 environmentId: null,
990 searchQuery: "",
991 now: NOW,
992 });
993 const items = buildThreadListV2ListItems({
994 items: activeOnly.items,
995 pendingTasks: [makePendingTask("queued-1")],
996 });
997
998 expect(items.map((item) => item.type)).toEqual(["v2-thread", "v2-pending"]);
999 });
1000
1001 it("keeps the settled shelf between active and settled rows when nothing is queued", () => {
1002 const items = buildThreadListV2ListItems({
1003 items: layout.items,
1004 pendingTasks: [],
1005 settledCount: layout.settledCount,
1006 settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
1007 });
1008
1009 expect(items.map((item) => item.key)).toEqual([
1010 `v2-thread:${environmentId}:active`,
1011 "v2-settled-shelf",
1012 `v2-thread:${environmentId}:settled`,
1013 ]);
1014 });
1015
1016 it("places queued tasks before a collapsed snoozed shelf", () => {
1017 const snoozedLayout = buildThreadListV2Items({
1018 threads: [
1019 makeThread({ id: ThreadId.make("active"), title: "active" }),
1020 makeThread({
1021 id: ThreadId.make("snoozed"),
1022 title: "snoozed",
1023 snoozedUntil: "2026-06-03T09:00:00.000Z",
1024 snoozedAt: "2026-06-01T12:00:00.000Z",
1025 }),
1026 makeThread({
1027 id: ThreadId.make("settled"),
1028 title: "settled",
1029 settledOverride: "settled",
1030 settledAt: NOW,
1031 }),
1032 ],
1033 environmentId: null,
1034 searchQuery: "",
1035 now: NOW,
1036 });
1037 const items = buildThreadListV2ListItems({
1038 items: snoozedLayout.items,
1039 pendingTasks: [makePendingTask("queued")],
1040 snoozedCount: snoozedLayout.snoozedCount,
1041 snoozedShelfExpanded: false,
1042 snoozedShelfHeaderIndex: snoozedLayout.snoozedShelfHeaderIndex,
1043 settledCount: snoozedLayout.settledCount,
1044 settledShelfHeaderIndex: snoozedLayout.settledShelfHeaderIndex,
1045 });
1046
1047 expect(items.map((item) => item.type)).toEqual([
1048 "v2-thread",
1049 "v2-pending",
1050 "v2-snoozed-shelf",
1051 "v2-settled-shelf",
1052 "v2-thread",
1053 ]);
1054 expect(threadJumpTarget(items, "thread.jump.1")?.id).toBe("active");
1055 expect(threadJumpTarget(items, "thread.jump.2")?.id).toBe("settled");
1056 expect(threadJumpTarget(items, "thread.jump.3")).toBeNull();
1057 });
1058});
1059
1060describe("pending mobile thread moves", () => {
1061 function fixture(section: "active" | "pinned" = "active") {
1062 const rows = ["a", "b", "c"].map((id, index) =>
1063 makeThread({
1064 id: ThreadId.make(id),
1065 title: id === "a" ? "hidden" : "match",
1066 createdAt: `2026-06-01T0${3 - index}:00:00.000Z`,
1067 pinnedAt: section === "pinned" ? `2026-06-01T0${3 - index}:00:00.000Z` : null,
1068 }),
1069 );
1070 const ordered = getThreadListV2OrderedSection({ threads: rows, section, now: NOW });
1071 const orderedIds = ordered.map((row) => `${row.environmentId}:${row.id}`);
1072 const movedId = orderedIds[2]!;
1073 const assignments = planPinnedMove({
1074 orderedIds,
1075 keysById: new Map(orderedIds.map((id) => [id, null])),
1076 movedId,
1077 direction: "up",
1078 })!;
1079 const pending = createPendingThreadOrder({
1080 section,
1081 ordered,
1082 movedId,
1083 direction: "up",
1084 assignments,
1085 });
1086 const update = (current: EnvironmentThreadShell[], assignment: (typeof assignments)[number]) =>
1087 current.map((row) =>
1088 `${row.environmentId}:${row.id}` === assignment.id
1089 ? {
1090 ...row,
1091 [section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: assignment.orderKey,
1092 }
1093 : row,
1094 );
1095 return { rows, assignments, pending, update };
1096 }
1097
1098 function layout(
1099 rows: EnvironmentThreadShell[],
1100 pendingOrder: PendingThreadOrder | null,
1101 searchQuery = "",
1102 ) {
1103 return buildThreadListV2Items({
1104 threads: rows,
1105 pendingOrder,
1106 environmentId: null,
1107 searchQuery,
1108 now: NOW,
1109 }).items.map((item) => item.thread.id);
1110 }
1111
1112 it.each(["active", "pinned"] as const)(
1113 "holds %s order through every intermediate key upsert",
1114 (section) => {
1115 const { rows, assignments, pending, update } = fixture(section);
1116 let current = rows;
1117 let hold: PendingThreadOrder | null = pending;
1118 const desired = pending.orderedIds.map((id) => id.split(":")[1]);
1119 expect(layout(current, hold)).toEqual(desired);
1120 for (const assignment of assignments) {
1121 current = update(current, assignment);
1122 hold = reconcilePendingThreadOrder(
1123 hold!,
1124 getThreadListV2OrderedSection({ threads: current, section, now: NOW }),
1125 );
1126 expect(hold).not.toBeNull();
1127 expect(layout(current, hold)).toEqual(desired);
1128 }
1129 expect(reconcilePendingThreadOrder({ ...hold!, commandsComplete: true }, current)).toBeNull();
1130 expect(layout(current, null)).toEqual(desired);
1131 },
1132 );
1133
1134 it("keeps the action guard pending when receipts precede canonical shells", () => {
1135 const { rows, assignments, pending, update } = fixture();
1136 let hold: PendingThreadOrder | null = { ...pending, commandsComplete: true };
1137 let current = rows;
1138 expect(reconcilePendingThreadOrder(hold, current)).toBe(hold);
1139 for (const [index, assignment] of assignments.entries()) {
1140 current = update(current, assignment);
1141 hold = reconcilePendingThreadOrder(hold!, current);
1142 expect(hold === null).toBe(index === assignments.length - 1);
1143 expect(layout(current, hold)).toEqual(["a", "c", "b"]);
1144 }
1145 });
1146
1147 it("keeps search results in the full pending section order", () => {
1148 const { rows, assignments, pending, update } = fixture();
1149 const current = update(update(rows, assignments[0]!), assignments[1]!);
1150 expect(layout(current, pending, "match")).toEqual(["c", "b"]);
1151 });
1152
1153 it("releases for real section membership and foreign key changes", () => {
1154 const { rows, pending } = fixture();
1155 expect(reconcilePendingThreadOrder(pending, rows.slice(1))).toBeNull();
1156 const newRow = makeThread({ id: ThreadId.make("new"), title: "new" });
1157 expect(reconcilePendingThreadOrder(pending, [...rows, newRow])).toBeNull();
1158 expect(
1159 reconcilePendingThreadOrder(
1160 pending,
1161 rows.map((row, index) => (index === 0 ? { ...row, activeOrderKey: "zz" } : row)),
1162 ),
1163 ).toBeNull();
1164 const settled = rows.map((row, index) =>
1165 index === 0 ? { ...row, settledOverride: "settled" as const } : row,
1166 );
1167 expect(layout(settled, pending)).toEqual(layout(settled, null));
1168 });
1169
1170 it("does not hide a concurrent return to a previously confirmed key", () => {
1171 const { rows, assignments, pending, update } = fixture();
1172 const confirmed = reconcilePendingThreadOrder(pending, update(rows, assignments[0]!))!;
1173 expect(reconcilePendingThreadOrder(confirmed, rows)).toBeNull();
1174 });
1175
1176 it("preserves the hold for activity but releases for a reopened sort anchor", () => {
1177 const { rows, pending } = fixture();
1178 expect(
1179 reconcilePendingThreadOrder(
1180 pending,
1181 rows.map((row) => ({ ...row, updatedAt: NOW })),
1182 ),
1183 ).toBe(pending);
1184 expect(
1185 reconcilePendingThreadOrder(
1186 pending,
1187 rows.map((row, index) => (index === 0 ? { ...row, unsettledAt: NOW } : row)),
1188 ),
1189 ).toBeNull();
1190 });
1191});
1192
1193describe("mobile move availability", () => {
1194 const oldEnvironment = EnvironmentId.make("older-server");
1195 function rows(section: "active" | "pinned", keys: readonly (string | null)[]) {
1196 return keys.map((key, index) =>
1197 makeThread({
1198 id: ThreadId.make(`move-${index}`),
1199 title: `Move ${index}`,
1200 environmentId: index === 1 ? oldEnvironment : environmentId,
1201 activeOrderKey: section === "active" ? key : null,
1202 pinOrderKey: section === "pinned" ? key : null,
1203 pinnedAt: section === "pinned" ? NOW : null,
1204 }),
1205 );
1206 }
1207
1208 it.each(["active", "pinned"] as const)(
1209 "keeps unsupported keyed %s neighbors as usable anchors",
1210 (section) => {
1211 const ordered = rows(section, ["bb", "dd", "ff"]);
1212 const plan = createThreadMovePlanner({
1213 ordered,
1214 section,
1215 reorderableEnvironmentIds: new Set([environmentId]),
1216 });
1217 const assignments = plan(`${environmentId}:move-0`, "down");
1218 expect(assignments).toHaveLength(1);
1219 expect(assignments![0]!.id).toBe(`${environmentId}:move-0`);
1220 expect(assignments![0]!.orderKey > "dd").toBe(true);
1221 expect(assignments![0]!.orderKey < "ff").toBe(true);
1222 expect(plan(`${oldEnvironment}:move-1`, "up")).toBeNull();
1223 expect(plan(`${environmentId}:move-0`, "up")).toBeNull();
1224 },
1225 );
1226
1227 it.each(["active", "pinned"] as const)(
1228 "disables %s moves requiring unsupported keyless materialization",
1229 (section) => {
1230 const ordered = rows(section, [null, null, null]);
1231 const plan = createThreadMovePlanner({
1232 ordered,
1233 section,
1234 reorderableEnvironmentIds: new Set([environmentId]),
1235 });
1236 expect(plan(`${environmentId}:move-0`, "down")).toBeNull();
1237 expect(plan(`${environmentId}:move-2`, "up")).toBeNull();
1238 const supported = createThreadMovePlanner({
1239 ordered,
1240 section,
1241 reorderableEnvironmentIds: new Set([environmentId, oldEnvironment]),
1242 });
1243 expect(supported(`${environmentId}:move-0`, "down")).toHaveLength(3);
1244 },
1245 );
1246
1247 it.each(["active", "pinned"] as const)(
1248 "reserves snoozed %s keys when moving visible rows",
1249 (section) => {
1250 const ordered = rows(section, ["bb", "dd", "ff"]);
1251 const input = { ordered, section, reorderableEnvironmentIds: new Set([environmentId]) };
1252 const collision = createThreadMovePlanner(input)(`${environmentId}:move-0`, "down")![0]!
1253 .orderKey;
1254 const hidden = {
1255 ...ordered[0]!,
1256 id: ThreadId.make("snoozed"),
1257 snoozedAt: NOW,
1258 snoozedUntil: "2099-01-01T00:00:00.000Z",
1259 pinOrderKey: section === "pinned" ? collision : null,
1260 activeOrderKey: section === "active" ? collision : null,
1261 };
1262 const assignments = createThreadMovePlanner({ ...input, allThreads: [...ordered, hidden] })(
1263 `${environmentId}:move-0`,
1264 "down",
1265 );
1266 expect(assignments).toHaveLength(1);
1267 expect(assignments![0]!.orderKey).not.toBe(collision);
1268 expect(assignments![0]!.orderKey > "dd" && assignments![0]!.orderKey < "ff").toBe(true);
1269 },
1270 );
1271
1272 it("allows an independent keyed move despite an unsupported keyless row elsewhere", () => {
1273 const ordered = rows("active", [null, null, "bb", "dd", "ff"]);
1274 const plan = createThreadMovePlanner({
1275 ordered,
1276 section: "active",
1277 reorderableEnvironmentIds: new Set([environmentId]),
1278 });
1279 const assignments = plan(`${environmentId}:move-4`, "up");
1280 expect(assignments).toHaveLength(1);
1281 expect(assignments![0]!.id).toBe(`${environmentId}:move-4`);
1282 expect(assignments![0]!.orderKey > "bb").toBe(true);
1283 expect(assignments![0]!.orderKey < "dd").toBe(true);
1284 });
1285});
1286
1287describe("thread drag destinations", () => {
1288 it("moves across multiple rows while keeping hidden anchors in place", () => {
1289 expect(
1290 threadOrderAfterMove(["a", "hidden", "b", "c"], "c", {
1291 targetId: "a",
1292 placement: "before",
1293 }),
1294 ).toEqual(["c", "a", "hidden", "b"]);
1295 expect(
1296 threadOrderAfterMove(["a", "hidden", "b", "c"], "a", {
1297 targetId: "b",
1298 placement: "after",
1299 }),
1300 ).toEqual(["hidden", "b", "a", "c"]);
1301 });
1302
1303 it("rejects missing, self, and unchanged destinations", () => {
1304 for (const targetId of ["missing", "a", "b"]) {
1305 expect(
1306 threadOrderAfterMove(["a", "b", "c"], "a", {
1307 targetId,
1308 placement: "before",
1309 }),
1310 ).toBeNull();
1311 }
1312 expect(threadOrderAfterMove(["a", "b"], "missing", "down")).toBeNull();
1313 });
1314
1315 it.each(["active", "pinned"] as const)(
1316 "persists a dropped %s row and holds its order until confirmed",
1317 (section) => {
1318 const ordered = ["a", "b", "c", "d"].map((id) =>
1319 makeThread({
1320 id: ThreadId.make(id),
1321 title: id,
1322 pinnedAt: section === "pinned" ? NOW : null,
1323 }),
1324 );
1325 const ids = ordered.map((row) => `${row.environmentId}:${row.id}`);
1326 const direction = { targetId: ids[0]!, placement: "before" as const };
1327 const assignments = createThreadMovePlanner({
1328 ordered,
1329 section,
1330 reorderableEnvironmentIds: new Set([environmentId]),
1331 })(ids[3]!, direction)!;
1332 const pending = createPendingThreadOrder({
1333 section,
1334 ordered,
1335 movedId: ids[3]!,
1336 direction,
1337 assignments,
1338 });
1339 expect(pending.orderedIds).toEqual([ids[3], ids[0], ids[1], ids[2]]);
1340 const confirmed = ordered.map((row) => ({
1341 ...row,
1342 [section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: assignments.find(
1343 (a) => a.id === `${row.environmentId}:${row.id}`,
1344 )!.orderKey,
1345 }));
1346 expect(
1347 getThreadListV2OrderedSection({ threads: confirmed, section, now: NOW }).map(
1348 (row) => `${row.environmentId}:${row.id}`,
1349 ),
1350 ).toEqual(pending.orderedIds);
1351 expect(
1352 reconcilePendingThreadOrder({ ...pending, commandsComplete: true }, confirmed),
1353 ).toBeNull();
1354 },
1355 );
1356
1357 it("refuses a drop that would need to rewrite an old server's keyless row", () => {
1358 const old = EnvironmentId.make("old-server");
1359 const ordered = [environmentId, old, environmentId].map((env, index) =>
1360 makeThread({
1361 id: ThreadId.make(String(index)),
1362 title: String(index),
1363 environmentId: env,
1364 }),
1365 );
1366 expect(
1367 createThreadMovePlanner({
1368 ordered,
1369 section: "active",
1370 reorderableEnvironmentIds: new Set([environmentId]),
1371 })(`${environmentId}:2`, { targetId: `${environmentId}:0`, placement: "before" }),
1372 ).toBeNull();
1373 });
1374});
1375
1376it("allows a long drop past an old server even when both adjacent moves fail", () => {
1377 const old = EnvironmentId.make("old-server");
1378 const ordered = [
1379 makeThread({ id: ThreadId.make("a"), title: "a" }),
1380 makeThread({ id: ThreadId.make("b"), title: "b", environmentId: old }),
1381 makeThread({ id: ThreadId.make("c"), title: "c", activeOrderKey: "h" }),
1382 makeThread({ id: ThreadId.make("d"), title: "d", activeOrderKey: "p" }),
1383 ];
1384 const planner = createThreadMovePlanner({
1385 ordered,
1386 section: "active",
1387 reorderableEnvironmentIds: new Set([environmentId]),
1388 });
1389 const movedId = `${environmentId}:a`;
1390 expect(planner(movedId, "up")).toBeNull();
1391 expect(planner(movedId, "down")).toBeNull();
1392 const assignments = planner(movedId, { targetId: `${environmentId}:d`, placement: "after" });
1393 expect(assignments).toHaveLength(1);
1394 expect(assignments![0]!.id).toBe(movedId);
1395 expect(assignments![0]!.orderKey > "p").toBe(true);
1396});
1397
1398describe("cross-section thread drops", () => {
1399 it.each(["pinned", "active"] as const)("inserts into an empty %s section", (section) => {
1400 const thread = makeThread({ id: ThreadId.make("source"), title: "source" });
1401 const id = `${thread.environmentId}:${thread.id}`;
1402 const destination = { section, targetId: null, placement: "before" as const };
1403 expect(threadOrderAfterMove([], id, destination)).toEqual([id]);
1404 const plan = createThreadMovePlanner({
1405 ordered: [],
1406 allThreads: [thread],
1407 section,
1408 reorderableEnvironmentIds: new Set([environmentId]),
1409 })(id, destination);
1410 expect(plan).toHaveLength(1);
1411 expect(plan![0]!.id).toBe(id);
1412 });
1413 it("places an incoming row between existing anchors without rewriting them", () => {
1414 const a = makeThread({ id: ThreadId.make("a"), title: "a", pinOrderKey: "h" });
1415 const b = makeThread({ id: ThreadId.make("b"), title: "b", pinOrderKey: "z" });
1416 const source = makeThread({ id: ThreadId.make("source"), title: "source" });
1417 const id = `${environmentId}:source`;
1418 const destination = {
1419 section: "pinned" as const,
1420 targetId: `${environmentId}:b`,
1421 placement: "before" as const,
1422 };
1423 const plan = createThreadMovePlanner({
1424 ordered: [a, b],
1425 allThreads: [a, b, source],
1426 section: "pinned",
1427 reorderableEnvironmentIds: new Set([environmentId]),
1428 })(id, destination);
1429 expect(plan).toHaveLength(1);
1430 expect(plan![0]!.orderKey > "h" && plan![0]!.orderKey < "z").toBe(true);
1431 expect(
1432 threadOrderAfterMove([`${environmentId}:a`, `${environmentId}:b`], id, destination),
1433 ).toEqual([`${environmentId}:a`, id, `${environmentId}:b`]);
1434 });
1435 it("rejects removed targets and unsupported incoming sources", () => {
1436 expect(
1437 threadOrderAfterMove(["a"], "source", {
1438 section: "active",
1439 targetId: "gone",
1440 placement: "before",
1441 }),
1442 ).toBeNull();
1443 const source = makeThread({ id: ThreadId.make("source"), title: "source" });
1444 expect(
1445 createThreadMovePlanner({
1446 ordered: [],
1447 allThreads: [source],
1448 section: "active",
1449 reorderableEnvironmentIds: new Set(),
1450 })(`${environmentId}:source`, { section: "active", targetId: null, placement: "before" }),
1451 ).toBeNull();
1452 });
1453 it("clears pinning, settlement and snooze when returning a parked thread to Active", () => {
1454 const thread = makeThread({
1455 id: ThreadId.make("parked"),
1456 title: "parked",
1457 pinnedAt: NOW,
1458 settledOverride: "settled",
1459 snoozedAt: NOW,
1460 snoozedUntil: "2099-01-01T00:00:00.000Z",
1461 });
1462 expect(threadDropLifecycle(thread, "active", NOW)).toEqual({
1463 pin: false,
1464 unpin: true,
1465 unsettle: true,
1466 unsnooze: true,
1467 });
1468 expect(threadDropLifecycle(thread, "pinned", NOW)).toEqual({
1469 pin: true,
1470 unpin: false,
1471 unsettle: false,
1472 unsnooze: false,
1473 });
1474 });
1475 it("does not send lifecycle commands for an ordinary Active reorder", () => {
1476 expect(
1477 threadDropLifecycle(
1478 makeThread({ id: ThreadId.make("active"), title: "active" }),
1479 "active",
1480 NOW,
1481 ),
1482 ).toEqual({ pin: false, unpin: false, unsettle: false, unsnooze: false });
1483 });
1484});