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

threadListV2.ts

681 lines26.6 KB

1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import {
3 canSnooze,
4 effectiveSnoozed,
5 hasQueuedTurnStart,
6 QUEUED_TURN_START_GRACE_MS,
7 resolveSnoozePresets,
8 snoozeWakeLabel,
9} from "@t3tools/client-runtime/state/thread-settled";
10import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
13import {
14 sortActiveThreadsByOrderKey,
15 resolveSettledThreadTimestamp,
16 sortPinnedThreadsByOrderKey,
17 sortSettledThreads,
18} from "@t3tools/client-runtime/state/thread-sort";
19import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
20​
21import type { ThreadMoveAvailability } from "./threadOrder";
22​
23import { relativeTime } from "../../lib/time";
24import type { PendingNewTask } from "../../state/use-pending-new-tasks";
25​
26import {
27 applyPendingThreadOrder,
28 reconcilePendingThreadOrder,
29 type PendingThreadOrder,
30} from "./threadOrder";
31​
32export { snoozeWakeLabel };
33​
34/**
35 * Thread List v2 model, ported from the web sidebar v2
36 * (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
37 *
38 * Four visual states, three colors: color is reserved for "act now"
39 * (approval), "in motion" (working), and "broken" (failed). Ready is the
40 * unlabeled resting state.
41 */
42export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
43export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
44​
45export function resolveThreadListV2SnoozeMenuSelection(input: {
46 readonly event: string;
47 readonly displayedPresets: ReadonlyArray<SnoozePreset>;
48 readonly now: Date;
49}):
50 | { readonly _tag: "selected"; readonly preset: SnoozePreset }
51 | { readonly _tag: "expired" }
52 | { readonly _tag: "not-snooze" } {
53 if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
54​
55 const currentPreset = resolveSnoozePresets(input.now).find(
56 (candidate) => input.event === `snooze:${candidate.id}`,
57 );
58 if (currentPreset) return { _tag: "selected", preset: currentPreset };
59​
60 const displayedPreset = input.displayedPresets.find(
61 (candidate) => input.event === `snooze:${candidate.id}`,
62 );
63 if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
64 return { _tag: "selected", preset: displayedPreset };
65 }
66 return { _tag: "expired" };
68​
69export function resolveThreadListV2SwipeActions(input: {
70 readonly variant: "card" | "slim";
71 readonly settlementSupported: boolean;
72 readonly snoozeSupported: boolean;
73 readonly snoozable: boolean;
74 /** Row is on the snoozed shelf. */
75 readonly snoozed?: boolean;
76}): {
77 readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
78 readonly secondary: "snooze" | null;
79} {
80 if (input.snoozed === true) {
81 return { primary: "unsnooze", secondary: null };
82 }
83 const primary = input.settlementSupported
84 ? input.variant === "slim"
85 ? "unsettle"
86 : "settle"
87 : "archive";
88 return {
89 primary,
90 secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
91 };
93​
94/**
95 * The point at which a queued-turn snooze guard expires on its own. Rows arm
96 * a one-shot timer for this boundary so Snooze appears without waiting for an
97 * unrelated render. User-blocked threads return null because only fresh
98 * server data can make them snoozable.
99 */
100export function resolveThreadListV2SnoozeGateExpiryMs(
101 thread: Pick<
102 EnvironmentThreadShell,
103 "hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
104 >,
105 options: { readonly now: string },
106): number | null {
107 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
108 if (!hasQueuedTurnStart(thread, options)) return null;
109 const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
110 if (Number.isNaN(messageAtMs)) return null;
111 return messageAtMs + QUEUED_TURN_START_GRACE_MS;
113​
114// Settled-tail paging: recent history is the common lookup; the deep tail
115// stays behind an explicit Show more. Shared by the compact Home list and
116// the iPad sidebar so both page identically.
117export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
118export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
119​
120export function resolveThreadListV2Status(
121 thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
122): ThreadListV2Status {
123 if (thread.hasPendingApprovals) {
124 return "approval";
125 }
126 if (thread.hasPendingUserInput) {
127 return "input";
128 }
129 if (thread.session?.status === "running" || thread.session?.status === "starting") {
130 return "working";
131 }
132 if (thread.session?.status === "error") {
133 return "failed";
134 }
135 return "ready";
137​
138/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
139 poison the whole ordering, so it sinks to the epoch instead. */
140function parseTimestampMs(isoDate: string): number {
141 const parsed = Date.parse(isoDate);
142 return Number.isNaN(parsed) ? 0 : parsed;
144​
145/** The active order shared by web and native: new/reopened rows, then the
146 saved arrangement. Activity does not move a thread. */
147export function sortThreadsForListV2<
148 T extends {
149 readonly id: string;
150 readonly createdAt: string;
151 readonly unsettledAt?: string | null | undefined;
152 readonly activeOrderKey?: string | null | undefined;
153 readonly environmentId?: string | undefined;
154 },
155>(threads: readonly T[]): T[] {
156 return sortActiveThreadsByOrderKey(threads);
158​
159/** Canonical card section for Move up/down, independent of search or scope. */
160export function getThreadListV2OrderedSection(input: {
161 readonly threads: readonly EnvironmentThreadShell[];
162 readonly section: "pinned" | "active";
163 readonly pendingOrder?: PendingThreadOrder | null;
164 readonly now: string;
165 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
166 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
167 readonly queuedThreadKeys?: ReadonlySet<string>;
168}): EnvironmentThreadShell[] {
169 const threads = input.threads.filter((thread) => {
170 if (thread.archivedAt !== null) return false;
171 if (
172 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
173 thread.settledOverride === "settled" &&
174 input.queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) !== true
175 ) {
176 return false;
177 }
178 if (
179 (input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true) &&
180 effectiveSnoozed(thread, { now: input.now })
181 ) {
182 return false;
183 }
184 return (thread.pinnedAt != null) === (input.section === "pinned");
185 });
186 const ordered =
187 input.section === "pinned"
188 ? sortPinnedThreadsByOrderKey(threads)
189 : sortActiveThreadsByOrderKey(threads);
190 const pending =
191 input.pendingOrder?.section === input.section
192 ? reconcilePendingThreadOrder(input.pendingOrder, ordered)
193 : null;
194 return applyPendingThreadOrder(ordered, input.section, pending);
196​
197export interface ThreadListV2Item {
198 readonly thread: EnvironmentThreadShell;
199 readonly variant: "card" | "slim";
200 /** Snoozed-shelf row: shows the wake countdown and offers Wake. */
201 readonly snoozed: boolean;
202 /** Pinned-block row: renders the pin glyph and offers Unpin. */
203 readonly pinned: boolean;
204 readonly isLast: boolean;
206​
207export interface ThreadListV2Layout {
208 readonly items: ThreadListV2Item[];
209 /** Settled threads beyond the render limit (behind "Show more"). */
210 readonly hiddenSettledCount: number;
211 /** Snoozed threads matching the current filters. */
212 readonly snoozedCount: number;
213 /** Index in `items` where the Snoozed shelf header belongs. The header is
214 still rendered when the shelf is collapsed and no snoozed rows exist. */
215 readonly snoozedShelfHeaderIndex: number | null;
216 /** Total settled threads in scope, including rows hidden by collapse/paging. */
217 readonly settledCount: number;
218 /** Index in `items` where the Settled shelf header belongs. */
219 readonly settledShelfHeaderIndex: number | null;
220 /** Soonest wake time among snoozed threads, or null. Callers arm
221 a timeout at this boundary so the list re-partitions the moment a
222 snooze expires instead of on the next minute tick. */
223 readonly nextSnoozeWakeAt: string | null;
225​
226export interface ThreadListV2ThreadListItem {
227 readonly type: "v2-thread";
228 readonly key: string;
229 readonly item: ThreadListV2Item;
230 /** Precomputed so recycled-list equality can see a minute-tick change. */
231 readonly snoozeWakeLabelText: string | undefined;
232 /** Row timestamp precomputed against the parent clock so the recycler's
233 equality only sees a change on rows that actually draw a time. Blank
234 while the row renders a status label or the wake countdown instead. */
235 readonly timeLabel: string;
236 /** Minute clock feeding the row's native snooze menu, carried only on rows
237 whose menu holds snooze presets (capability-gated cards the user may
238 snooze). Keeping it out of the list's `extraData` means the minute tick
239 re-renders just these rows instead of every visible one. */
240 readonly snoozePresetMinute: string | undefined;
241 /** Inset hairline drawn under the row. Precomputed from the final order so
242 a neighbour change (e.g. the queued block appearing) updates the row
243 through recycled-list equality instead of leaving a stale divider. */
244 readonly showTrailingDivider: boolean;
245 /** A message for this thread is waiting in the outbox. Carried on the item
246 so an outbox write (which never touches the thread shell) reaches the
247 row through recycled-list equality instead of leaving a stale icon. */
248 readonly hasQueuedMessages: boolean;
249 /** Move up/down availability in the row's card section. Carried on the item
250 for the same reason: a reorder in flight (or its commit) changes menu
251 availability without changing any shell. */
252 readonly canMoveUp: boolean;
253 readonly canMoveDown: boolean;
255​
256export interface ThreadListV2PendingListItem {
257 readonly type: "v2-pending";
258 readonly key: string;
259 readonly pendingTask: PendingNewTask;
260 /** First queued row after the active block draws the PENDING divider. */
261 readonly showPendingDivider: boolean;
262 /** Same rule as the thread rows: a hairline unless the next row carries its
263 own section rule or none follows. */
264 readonly showTrailingDivider: boolean;
266​
267export interface ThreadListV2SnoozedShelfListItem {
268 readonly type: "v2-snoozed-shelf";
269 readonly key: "v2-snoozed-shelf";
270 readonly count: number;
271 readonly expanded: boolean;
272 /** Shelf preferences still loading: the toggle is disabled until they
273 arrive. Carried on the item because a recycled cell ignores the render
274 closure — without it the header would stay visibly disabled (or enabled
275 too early) after the preference load lands. */
276 readonly disabled: boolean;
278​
279export interface ThreadListV2SettledShelfListItem {
280 readonly type: "v2-settled-shelf";
281 readonly key: "v2-settled-shelf";
282 readonly count: number;
283 readonly expanded: boolean;
284 /** See the snoozed shelf header's field. */
285 readonly disabled: boolean;
287​
288export type ThreadListV2ListItem =
289 | ThreadListV2ThreadListItem
290 | ThreadListV2PendingListItem
291 | ThreadListV2SnoozedShelfListItem
292 | ThreadListV2SettledShelfListItem;
293​
294/** Narrows a wider list-item union (e.g. the sidebar's legacy + v2 mix) to
295 the v2 item kinds the shared equality understands. */
296export function isThreadListV2ListItem(value: {
297 readonly type: string;
298}): value is ThreadListV2ListItem {
299 return (
300 value.type === "v2-thread" ||
301 value.type === "v2-pending" ||
302 value.type === "v2-snoozed-shelf" ||
303 value.type === "v2-settled-shelf"
304 );
306​
307/** Recycled-list equality for the flat v2 list (Home + iPad sidebar).
308 Item objects are rebuilt on every minute tick and every partition run;
309 without this the lists would consider every mounted row changed and
310 re-render all of them (each carrying a swipeable + a PR subscription).
311 The clock-derived fields are per-row precomputed text, so a minute tick
312 only flips equality on rows whose visible text (or snooze menu) actually
313 moved. Thread references are stable across rebuilds. */
314export function threadListV2ListItemsAreEqual(
315 previous: ThreadListV2ListItem,
316 item: ThreadListV2ListItem,
317): boolean {
318 switch (item.type) {
319 case "v2-thread":
320 return (
321 previous.type === "v2-thread" &&
322 previous.key === item.key &&
323 previous.item.thread === item.item.thread &&
324 previous.item.variant === item.item.variant &&
325 previous.item.snoozed === item.item.snoozed &&
326 previous.item.pinned === item.item.pinned &&
327 previous.snoozeWakeLabelText === item.snoozeWakeLabelText &&
328 previous.timeLabel === item.timeLabel &&
329 previous.snoozePresetMinute === item.snoozePresetMinute &&
330 previous.showTrailingDivider === item.showTrailingDivider &&
331 previous.hasQueuedMessages === item.hasQueuedMessages &&
332 previous.canMoveUp === item.canMoveUp &&
333 previous.canMoveDown === item.canMoveDown
334 );
335 case "v2-pending":
336 return (
337 previous.type === "v2-pending" &&
338 previous.key === item.key &&
339 previous.pendingTask === item.pendingTask &&
340 previous.showPendingDivider === item.showPendingDivider &&
341 previous.showTrailingDivider === item.showTrailingDivider
342 );
343 case "v2-snoozed-shelf":
344 return (
345 previous.type === "v2-snoozed-shelf" &&
346 previous.count === item.count &&
347 previous.expanded === item.expanded &&
348 previous.disabled === item.disabled
349 );
350 case "v2-settled-shelf":
351 return (
352 previous.type === "v2-settled-shelf" &&
353 previous.count === item.count &&
354 previous.expanded === item.expanded &&
355 previous.disabled === item.disabled
356 );
357 }
359​
360/** The timestamp a row renders when it shows no status label: the settle
361 stamp on settled slim rows, otherwise the latest activity. Blank for
362 status-labelled cards and snoozed rows with a wake countdown — those
363 never draw a time, so their minute tick must not invalidate the cell. */
364function resolveThreadListV2ItemTimeLabel(
365 item: ThreadListV2Item,
366 showSnoozeWakeLabel: boolean,
367): string {
368 const { thread, variant, snoozed } = item;
369 if (showSnoozeWakeLabel) return "";
370 if (variant === "card" && resolveThreadListV2Status(thread) !== "ready") return "";
371 const settledTimestamp =
372 variant === "slim" && !snoozed ? resolveSettledThreadTimestamp(thread) : null;
373 return relativeTime(
374 settledTimestamp ?? thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
375 );
377​
378/**
379 * Builds the shared mobile order: active → pending → snoozed shelf → settled.
380 * Pending tasks are waiting rather than asking, and parked work remains
381 * reachable without competing with either the inbox or settled history.
382 */
383export function buildThreadListV2ListItems(input: {
384 readonly items: ReadonlyArray<ThreadListV2Item>;
385 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
386 readonly snoozedCount?: number;
387 readonly snoozedShelfExpanded?: boolean;
388 readonly snoozedShelfHeaderIndex?: number | null;
389 readonly settledCount?: number;
390 readonly settledShelfExpanded?: boolean;
391 readonly settledShelfHeaderIndex?: number | null;
392 readonly snoozeLabelNow?: string;
393 /** Environments whose server supports thread.snooze. Rows on other
394 environments never carry the minute clock that feeds the snooze menu.
395 Absent = no gating (tests). */
396 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
397 /** Thread keys (`environmentId:threadId`) with a message waiting in the
398 outbox; stamped onto the matching rows as `hasQueuedMessages`. */
399 readonly queuedThreadKeys?: ReadonlySet<string>;
400 /** Menu availability for Move up/down, keyed by `environmentId:threadId`
401 (only consulted for card rows — slim menus omit the moves). Produced by
402 `computeThreadMoveAvailability` in one pass per section; a recycled cell
403 ignores the render closure, so the stamps ride on the item. Absent =
404 never available (tests). */
405 readonly moveAvailability?: ReadonlyMap<string, ThreadMoveAvailability>;
406 /** True while the shelf expansion preferences are still loading; stamped
407 onto both shelf headers so the disabled state reaches recycled cells. */
408 readonly shelfPreferencesLoading?: boolean;
409}): ThreadListV2ListItem[] {
410 const threadItems = input.items.map((item): ThreadListV2ListItem => {
411 const snoozeWakeLabelText =
412 item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
413 ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
414 : undefined;
415 // The minute clock belongs on the item, not the list's extraData, so the
416 // recycler's equality can confine the per-minute re-render to rows whose
417 // snooze menu actually shows preset times. The swipe-revealed snooze menu
418 // exists on slim rows too (the variant only swaps the primary action),
419 // so the gate follows actual snooze availability, not the variant.
420 const snoozePresetMinute =
421 !item.snoozed &&
422 input.snoozeLabelNow !== undefined &&
423 (input.snoozeEnvironmentIds?.has(item.thread.environmentId) ?? true) &&
424 canSnooze(item.thread, { now: input.snoozeLabelNow })
425 ? input.snoozeLabelNow
426 : undefined;
427 const move =
428 item.variant === "card"
429 ? input.moveAvailability?.get(`${item.thread.environmentId}:${item.thread.id}`)
430 : undefined;
431 return {
432 type: "v2-thread",
433 key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
434 item,
435 snoozeWakeLabelText,
436 timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined),
437 snoozePresetMinute,
438 showTrailingDivider: false,
439 hasQueuedMessages:
440 input.queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true,
441 canMoveUp: move?.canMoveUp === true,
442 canMoveDown: move?.canMoveDown === true,
443 };
444 });
445 const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({
446 type: "v2-pending",
447 key: `v2-${pendingTask.key}`,
448 pendingTask,
449 showPendingDivider: index === 0,
450 showTrailingDivider: false,
451 }));
452 const snoozedCount = input.snoozedCount ?? 0;
453 const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
454 const settledCount = input.settledCount ?? 0;
455 const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
456 const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length;
457 const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
458 const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
459 const shelfDisabled = input.shelfPreferencesLoading === true;
460 if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
461 result.push({
462 type: "v2-snoozed-shelf",
463 key: "v2-snoozed-shelf",
464 count: snoozedCount,
465 expanded: input.snoozedShelfExpanded === true,
466 disabled: shelfDisabled,
467 });
468 result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
469 }
470 if (settledShelfHeaderIndex !== null && settledCount > 0) {
471 result.push({
472 type: "v2-settled-shelf",
473 key: "v2-settled-shelf",
474 count: settledCount,
475 expanded: input.settledShelfExpanded !== false,
476 disabled: shelfDisabled,
477 });
478 result.push(...threadItems.slice(settledShelfHeaderIndex));
479 }
480 // Hairlines depend on the final neighbour, so they are stamped after the
481 // splice: a recycled cell only re-renders when its divider actually flips.
482 return result.map((entry, index) => {
483 if (entry.type !== "v2-thread" && entry.type !== "v2-pending") return entry;
484 const next = result[index + 1];
485 const showTrailingDivider =
486 next?.type === "v2-thread" || (next?.type === "v2-pending" && !next.showPendingDivider);
487 return showTrailingDivider === entry.showTrailingDivider
488 ? entry
489 : { ...entry, showTrailingDivider };
490 });
492​
493/**
494 * Partitions visible threads into the active card block (saved order) and
495 * the settled recency tail, matching the web v2 list.
496 */
497export function buildThreadListV2Items(input: {
498 readonly pendingOrder?: PendingThreadOrder | null;
499 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
500 readonly environmentId: EnvironmentId | null;
501 readonly projectRefs?: ReadonlyArray<{
502 readonly environmentId: EnvironmentId;
503 readonly projectId: ProjectId;
504 }> | null;
505 readonly searchQuery: string;
506 readonly matchedThreadKeys?: ReadonlySet<string>;
507 /** Environments whose server supports thread.settle/unsettle. Threads on
508 other environments never classify as settled — the user could neither
509 un-settle nor pin them. Absent = no gating (tests). */
510 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
511 /** Environments whose server supports thread.snooze/unsnooze. Same
512 contract as settlementEnvironmentIds. */
513 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
514 /** Max settled rows to render; the rest are counted, not built. */
515 readonly settledLimit?: number;
516 /** Second-precise clock used for time-based classification. */
517 readonly now: string;
518 /** Expands the snoozed shelf into rows. Collapsed is the default. */
519 readonly snoozedShelfExpanded?: boolean;
520 /** Expands the settled shelf into rows. Expanded is the default. */
521 readonly settledShelfExpanded?: boolean;
522 /** The selected thread remains visible on an otherwise collapsed shelf so
523 a split-view detail can never lose its navigation row. */
524 readonly selectedThreadKey?: string | null;
525 /** Thread keys (`environmentId:threadId`) with a message waiting in the
526 outbox. Such a thread has work the user is waiting on, so it stays in
527 the active block even when the server has settled it. */
528 readonly queuedThreadKeys?: ReadonlySet<string>;
529}): ThreadListV2Layout {
530 const now = input.now;
531 const pending =
532 input.pendingOrder == null
533 ? null
534 : reconcilePendingThreadOrder(
535 input.pendingOrder,
536 getThreadListV2OrderedSection({
537 ...input,
538 section: input.pendingOrder.section,
539 pendingOrder: null,
540 }),
541 );
542 const query = input.searchQuery.trim().toLocaleLowerCase();
543 const projectKeys = input.projectRefs
544 ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
545 : null;
546​
547 const pinned: EnvironmentThreadShell[] = [];
548 const active: EnvironmentThreadShell[] = [];
549 const settled: EnvironmentThreadShell[] = [];
550 const snoozed: EnvironmentThreadShell[] = [];
551 let nextSnoozeWakeAt: string | null = null;
552 for (const thread of input.threads) {
553 // Callers pass live shells. The server stamps settledOverride for the tail.
554 if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
555 if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
556 continue;
557 }
558 if (
559 query.length > 0 &&
560 !thread.title.toLocaleLowerCase().includes(query) &&
561 !threadPullRequestSearchTerms(thread).some((term) =>
562 term.toLocaleLowerCase().includes(query),
563 ) &&
564 input.matchedThreadKeys?.has(
565 threadSearchMatchKey({
566 environmentId: thread.environmentId,
567 threadId: thread.id,
568 }),
569 ) !== true
570 ) {
571 continue;
572 }
573 const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
574 const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
575 // Snooze outranks settlement and pinning until the thread wakes.
576 if (supportsSnooze && effectiveSnoozed(thread, { now })) {
577 snoozed.push(thread);
578 if (
579 thread.snoozedUntil != null &&
580 (nextSnoozeWakeAt === null ||
581 parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
582 ) {
583 nextSnoozeWakeAt = thread.snoozedUntil;
584 }
585 continue;
586 }
587 const hasQueuedMessages =
588 input.queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
589 if (supportsSettlement && thread.settledOverride === "settled" && !hasQueuedMessages) {
590 settled.push(thread);
591 } else if (thread.pinnedAt != null) {
592 pinned.push(thread);
593 } else {
594 active.push(thread);
595 }
596 }
597​
598 const orderedActive = applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
599 const orderedSnoozed = [...snoozed].sort(
600 (left, right) =>
601 parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
602 );
603 const selectedThreadKey = input.selectedThreadKey ?? null;
604 const visibleSnoozed =
605 input.snoozedShelfExpanded === true
606 ? orderedSnoozed
607 : orderedSnoozed.filter(
608 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
609 );
610 const orderedSettled = sortSettledThreads(settled);
611 const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
612 const pagedSettled =
613 orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
614 const selectedSettled = orderedSettled
615 .slice(pagedSettled.length)
616 .find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
617 if (selectedSettled !== undefined) pagedSettled.push(selectedSettled);
618 const visibleSettled =
619 input.settledShelfExpanded !== false
620 ? pagedSettled
621 : pagedSettled.filter(
622 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
623 );
624​
625 const items: ThreadListV2Item[] = [];
626 for (const thread of applyPendingThreadOrder(
627 sortPinnedThreadsByOrderKey(pinned),
628 "pinned",
629 pending,
630 )) {
631 items.push({
632 thread,
633 variant: "card",
634 snoozed: false,
635 pinned: true,
636 isLast: false,
637 });
638 }
639 for (const thread of orderedActive) {
640 items.push({
641 thread,
642 variant: "card",
643 snoozed: false,
644 pinned: false,
645 isLast: false,
646 });
647 }
648 const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
649 for (const thread of visibleSnoozed) {
650 items.push({
651 thread,
652 variant: "slim",
653 snoozed: true,
654 pinned: false,
655 isLast: false,
656 });
657 }
658 const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
659 for (const thread of visibleSettled) {
660 items.push({
661 thread,
662 variant: "slim",
663 snoozed: false,
664 pinned: false,
665 isLast: false,
666 });
667 }
668 const last = items.at(-1);
669 if (last) {
670 items[items.length - 1] = { ...last, isLast: true };
671 }
672 return {
673 items,
674 hiddenSettledCount: orderedSettled.length - pagedSettled.length,
675 snoozedCount: orderedSnoozed.length,
676 snoozedShelfHeaderIndex,
677 settledCount: orderedSettled.length,
678 settledShelfHeaderIndex,
679 nextSnoozeWakeAt,
680 };