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

threadListV2.ts

747 lines25.9 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 { resolveThreadProviderStack } from "@t3tools/client-runtime/state/models";
13import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
14import {
15 createInboxReturnTracker,
16 isThreadWorking,
17 sortInboxThreadsByReturn,
18 sortWorkingThreadsBySend,
19} from "@t3tools/client-runtime/state/thread-inbox";
20import {
21 sortActiveThreadsByOrderKey,
22 resolveSettledThreadTimestamp,
23 sortPinnedThreadsByOrderKey,
24 sortSettledThreads,
25} from "@t3tools/client-runtime/state/thread-sort";
26import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
27​
28import type { ThreadListProvider } from "../../state/thread-list-environments";
29import type { ThreadMoveAvailability } from "./threadOrder";
30​
31import { relativeTime } from "../../lib/time";
32import type { PendingNewTask } from "../../state/use-pending-new-tasks";
33​
34import {
35 applyPendingThreadOrder,
36 reconcilePendingThreadOrder,
37 type PendingThreadOrder,
38} from "./threadOrder";
39​
40export { snoozeWakeLabel };
41​
42export const threadListInboxReturns = createInboxReturnTracker();
43​
44export function resolveThreadListV2ProviderDrivers(
45 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
46 providers: ReadonlyArray<ThreadListProvider> | undefined,
47): ReadonlyArray<string> {
48 if (providers === undefined) return [];
49 const stack = resolveThreadProviderStack(thread);
50 const drivers = stack.flatMap((instanceId) => {
51 const driver = providers.find((provider) => provider.instanceId === instanceId)?.driver;
52 return driver === undefined ? [] : [driver];
53 });
54 const currentDriver = providers.find(
55 (provider) => provider.instanceId === stack[stack.length - 1],
56 )?.driver;
57 return currentDriver === undefined ? [] : drivers;
59​
60export type ThreadListV2Status =
61 | "approval"
62 | "input"
63 | "working"
64 | "waiting"
65 | "failed"
66 | "limited"
67 | "ready";
68export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
69​
70export function resolveThreadListV2SnoozeMenuSelection(input: {
71 readonly event: string;
72 readonly displayedPresets: ReadonlyArray<SnoozePreset>;
73 readonly now: Date;
74}):
75 | { readonly _tag: "selected"; readonly preset: SnoozePreset }
76 | { readonly _tag: "expired" }
77 | { readonly _tag: "not-snooze" } {
78 if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
79​
80 const currentPreset = resolveSnoozePresets(input.now).find(
81 (candidate) => input.event === `snooze:${candidate.id}`,
82 );
83 if (currentPreset) return { _tag: "selected", preset: currentPreset };
84​
85 const displayedPreset = input.displayedPresets.find(
86 (candidate) => input.event === `snooze:${candidate.id}`,
87 );
88 if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
89 return { _tag: "selected", preset: displayedPreset };
90 }
91 return { _tag: "expired" };
93​
94export function resolveThreadListV2SwipeActions(input: {
95 readonly variant: "card" | "slim";
96 readonly settlementSupported: boolean;
97 readonly snoozeSupported: boolean;
98 readonly snoozable: boolean;
99 readonly snoozed?: boolean;
100}): {
101 readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
102 readonly secondary: "snooze" | null;
103} {
104 if (input.snoozed === true) {
105 return { primary: "unsnooze", secondary: null };
106 }
107 const primary = input.settlementSupported
108 ? input.variant === "slim"
109 ? "unsettle"
110 : "settle"
111 : "archive";
112 return {
113 primary,
114 secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
115 };
117​
118export function resolveThreadListV2SnoozeGateExpiryMs(
119 thread: Pick<
120 EnvironmentThreadShell,
121 | "hasPendingApprovals"
122 | "hasPendingUserInput"
123 | "pendingSubagentRequest"
124 | "latestRun"
125 | "latestUserMessageAt"
126 | "runtime"
127 >,
128 options: { readonly now: string },
129): number | null {
130 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
131 if (thread.pendingSubagentRequest != null) return null;
132 if (!hasQueuedTurnStart(thread, options)) return null;
133 const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
134 if (Number.isNaN(messageAtMs)) return null;
135 return messageAtMs + QUEUED_TURN_START_GRACE_MS;
137​
138export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
139export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
140​
141export function threadHasUnseenCompletion(
142 thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
143): boolean {
144 const completedAt = thread.latestRun?.completedAt;
145 if (!completedAt) return false;
146 const completedAtMs = Date.parse(completedAt);
147 if (Number.isNaN(completedAtMs)) return false;
148 if (!thread.lastVisitedAt) return false;
149 const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
150 if (Number.isNaN(lastVisitedAtMs)) return true;
151 return completedAtMs > lastVisitedAtMs;
153​
154export function resolveThreadListV2Status(
155 thread: Pick<
156 EnvironmentThreadShell,
157 "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime"
158 >,
159): ThreadListV2Status {
160 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
161 return "approval";
162 }
163 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
164 return "input";
165 }
166 if (
167 thread.runtime !== null &&
168 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
169 ) {
170 return "working";
171 }
172 if (thread.runtime?.status === "idle") {
173 return "waiting";
174 }
175 if (thread.runtime?.status === "failed") {
176 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
177 }
178 return "ready";
180​
181function parseTimestampMs(isoDate: string): number {
182 const parsed = Date.parse(isoDate);
183 return Number.isNaN(parsed) ? 0 : parsed;
185​
186export function sortThreadsForListV2<
187 T extends {
188 readonly id: string;
189 readonly createdAt: string;
190 readonly unsettledAt?: string | null | undefined;
191 readonly activeOrderKey?: string | null | undefined;
192 readonly environmentId?: string | undefined;
193 },
194>(threads: readonly T[]): T[] {
195 return sortActiveThreadsByOrderKey(threads);
197​
198export function getThreadListV2OrderedSection(input: {
199 readonly threads: readonly EnvironmentThreadShell[];
200 readonly section: "pinned" | "active";
201 readonly pendingOrder?: PendingThreadOrder | null;
202 readonly now: string;
203 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
204 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
205 readonly queuedThreadKeys?: ReadonlySet<string>;
206}): EnvironmentThreadShell[] {
207 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
208 const threads = input.threads.filter((thread) => {
209 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
210 return false;
211 if (
212 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
213 thread.settledOverride === "settled" &&
214 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) !== true
215 ) {
216 return false;
217 }
218 if (
219 (input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true) &&
220 effectiveSnoozed(thread, { now: input.now })
221 ) {
222 return false;
223 }
224 return (thread.pinnedAt != null) === (input.section === "pinned");
225 });
226 const ordered =
227 input.section === "pinned"
228 ? sortPinnedThreadsByOrderKey(threads)
229 : sortActiveThreadsByOrderKey(threads);
230 const pending =
231 input.pendingOrder?.section === input.section
232 ? reconcilePendingThreadOrder(input.pendingOrder, ordered)
233 : null;
234 return applyPendingThreadOrder(ordered, input.section, pending);
236​
237export interface ThreadListV2Item {
238 readonly thread: EnvironmentThreadShell;
239 readonly variant: "card" | "slim";
240 readonly snoozed: boolean;
241 readonly pinned: boolean;
242 readonly isLast: boolean;
244​
245export interface ThreadListV2Layout {
246 readonly items: ThreadListV2Item[];
247 readonly hiddenSettledCount: number;
248 readonly workingCount: number;
249 readonly workingShelfHeaderIndex: number | null;
250 readonly snoozedCount: number;
251 readonly snoozedShelfHeaderIndex: number | null;
252 readonly settledCount: number;
253 readonly settledShelfHeaderIndex: number | null;
254 /**
255 * Callers arm a timeout at this boundary so the list re-partitions the moment
256 * a snooze expires instead of on the next minute tick.
257 */
258 readonly nextSnoozeWakeAt: string | null;
260​
261export interface ThreadListV2ThreadListItem {
262 readonly type: "v2-thread";
263 readonly key: string;
264 readonly item: ThreadListV2Item;
265 readonly snoozeWakeLabelText: string | undefined;
266 readonly timeLabel: string;
267 readonly snoozePresetMinute: string | undefined;
268 readonly showTrailingDivider: boolean;
269 /**
270 * Carried on the item so an outbox write (which never touches the thread
271 * shell) reaches the row through recycled-list equality instead of leaving a
272 * stale icon.
273 */
274 readonly hasQueuedMessages: boolean;
275 readonly canMoveUp: boolean;
276 readonly canMoveDown: boolean;
278​
279export interface ThreadListV2PendingListItem {
280 readonly type: "v2-pending";
281 readonly key: string;
282 readonly pendingTask: PendingNewTask;
283 readonly showPendingDivider: boolean;
284 readonly showTrailingDivider: boolean;
286​
287export interface ThreadListV2WorkingShelfListItem {
288 readonly type: "v2-working-shelf";
289 readonly key: "v2-working-shelf";
290 readonly count: number;
291 readonly expanded: boolean;
292 readonly disabled: boolean;
294​
295export interface ThreadListV2SnoozedShelfListItem {
296 readonly type: "v2-snoozed-shelf";
297 readonly key: "v2-snoozed-shelf";
298 readonly count: number;
299 readonly expanded: boolean;
300 /**
301 * Carried on the item because a recycled cell ignores the render closure —
302 * without it the header would stay visibly disabled (or enabled too early)
303 * after the preference load lands.
304 */
305 readonly disabled: boolean;
307​
308export interface ThreadListV2SettledShelfListItem {
309 readonly type: "v2-settled-shelf";
310 readonly key: "v2-settled-shelf";
311 readonly count: number;
312 readonly expanded: boolean;
313 readonly disabled: boolean;
315​
316export type ThreadListV2ListItem =
317 | ThreadListV2ThreadListItem
318 | ThreadListV2PendingListItem
319 | ThreadListV2WorkingShelfListItem
320 | ThreadListV2SnoozedShelfListItem
321 | ThreadListV2SettledShelfListItem;
322​
323export function isThreadListV2ListItem(value: {
324 readonly type: string;
325}): value is ThreadListV2ListItem {
326 return (
327 value.type === "v2-thread" ||
328 value.type === "v2-pending" ||
329 value.type === "v2-working-shelf" ||
330 value.type === "v2-snoozed-shelf" ||
331 value.type === "v2-settled-shelf"
332 );
334​
335/**
336 * Item objects are rebuilt on every minute tick and every partition run;
337 * without this the lists would consider every mounted row changed and re-render
338 * all of them (each carrying a swipeable + a PR subscription).
339 */
340export function threadListV2ListItemsAreEqual(
341 previous: ThreadListV2ListItem,
342 item: ThreadListV2ListItem,
343): boolean {
344 switch (item.type) {
345 case "v2-thread":
346 return (
347 previous.type === "v2-thread" &&
348 previous.key === item.key &&
349 previous.item.thread === item.item.thread &&
350 previous.item.variant === item.item.variant &&
351 previous.item.snoozed === item.item.snoozed &&
352 previous.item.pinned === item.item.pinned &&
353 previous.snoozeWakeLabelText === item.snoozeWakeLabelText &&
354 previous.timeLabel === item.timeLabel &&
355 previous.snoozePresetMinute === item.snoozePresetMinute &&
356 previous.showTrailingDivider === item.showTrailingDivider &&
357 previous.hasQueuedMessages === item.hasQueuedMessages &&
358 previous.canMoveUp === item.canMoveUp &&
359 previous.canMoveDown === item.canMoveDown
360 );
361 case "v2-pending":
362 return (
363 previous.type === "v2-pending" &&
364 previous.key === item.key &&
365 previous.pendingTask === item.pendingTask &&
366 previous.showPendingDivider === item.showPendingDivider &&
367 previous.showTrailingDivider === item.showTrailingDivider
368 );
369 case "v2-working-shelf":
370 return (
371 previous.type === "v2-working-shelf" &&
372 previous.count === item.count &&
373 previous.expanded === item.expanded &&
374 previous.disabled === item.disabled
375 );
376 case "v2-snoozed-shelf":
377 return (
378 previous.type === "v2-snoozed-shelf" &&
379 previous.count === item.count &&
380 previous.expanded === item.expanded &&
381 previous.disabled === item.disabled
382 );
383 case "v2-settled-shelf":
384 return (
385 previous.type === "v2-settled-shelf" &&
386 previous.count === item.count &&
387 previous.expanded === item.expanded &&
388 previous.disabled === item.disabled
389 );
390 }
392​
393function resolveThreadListV2ItemTimeLabel(
394 item: ThreadListV2Item,
395 showSnoozeWakeLabel: boolean,
396): string {
397 const { thread, variant, snoozed } = item;
398 if (showSnoozeWakeLabel) return "";
399 if (
400 variant === "card" &&
401 (resolveThreadListV2Status(thread) !== "ready" || threadHasUnseenCompletion(thread))
402 )
403 return "";
404 const settledTimestamp =
405 variant === "slim" && !snoozed ? resolveSettledThreadTimestamp(thread) : null;
406 return relativeTime(
407 settledTimestamp ?? thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
408 );
410​
411export function buildThreadListV2ListItems(input: {
412 readonly items: ReadonlyArray<ThreadListV2Item>;
413 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
414 readonly workingCount?: number;
415 readonly workingShelfExpanded?: boolean;
416 readonly workingShelfHeaderIndex?: number | null;
417 readonly snoozedCount?: number;
418 readonly snoozedShelfExpanded?: boolean;
419 readonly snoozedShelfHeaderIndex?: number | null;
420 readonly settledCount?: number;
421 readonly settledShelfExpanded?: boolean;
422 readonly settledShelfHeaderIndex?: number | null;
423 readonly snoozeLabelNow?: string;
424 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
425 readonly queuedThreadKeys?: ReadonlySet<string>;
426 readonly moveAvailability?: ReadonlyMap<string, ThreadMoveAvailability>;
427 readonly shelfPreferencesLoading?: boolean;
428}): ThreadListV2ListItem[] {
429 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
430 const threadItems = input.items.map((item): ThreadListV2ListItem => {
431 const snoozeWakeLabelText =
432 item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
433 ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
434 : undefined;
435 // The minute clock belongs on the item, not the list's extraData, so the
436 // recycler's equality can confine the per-minute re-render to rows whose
437 // snooze menu actually shows preset times.
438 const snoozePresetMinute =
439 !item.snoozed &&
440 input.snoozeLabelNow !== undefined &&
441 (input.snoozeEnvironmentIds?.has(item.thread.environmentId) ?? true) &&
442 canSnooze(item.thread, { now: input.snoozeLabelNow })
443 ? input.snoozeLabelNow
444 : undefined;
445 const move =
446 item.variant === "card"
447 ? input.moveAvailability?.get(`${item.thread.environmentId}:${item.thread.id}`)
448 : undefined;
449 return {
450 type: "v2-thread",
451 key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
452 item,
453 snoozeWakeLabelText,
454 timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined),
455 snoozePresetMinute,
456 showTrailingDivider: false,
457 hasQueuedMessages:
458 queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true,
459 canMoveUp: move?.canMoveUp === true,
460 canMoveDown: move?.canMoveDown === true,
461 };
462 });
463 const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({
464 type: "v2-pending",
465 key: `v2-${pendingTask.key}`,
466 pendingTask,
467 showPendingDivider: index === 0,
468 showTrailingDivider: false,
469 }));
470 const workingCount = input.workingCount ?? 0;
471 const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null;
472 const snoozedCount = input.snoozedCount ?? 0;
473 const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
474 const settledCount = input.settledCount ?? 0;
475 const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
476 const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
477 const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd;
478 const activeEnd = workingShelfHeaderIndex ?? workingEnd;
479 const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
480 const shelfDisabled = input.shelfPreferencesLoading === true;
481 if (workingShelfHeaderIndex !== null && workingCount > 0) {
482 result.push({
483 type: "v2-working-shelf",
484 key: "v2-working-shelf",
485 count: workingCount,
486 expanded: input.workingShelfExpanded === true,
487 disabled: shelfDisabled,
488 });
489 result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd));
490 }
491 if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
492 result.push({
493 type: "v2-snoozed-shelf",
494 key: "v2-snoozed-shelf",
495 count: snoozedCount,
496 expanded: input.snoozedShelfExpanded === true,
497 disabled: shelfDisabled,
498 });
499 result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
500 }
501 if (settledShelfHeaderIndex !== null && settledCount > 0) {
502 result.push({
503 type: "v2-settled-shelf",
504 key: "v2-settled-shelf",
505 count: settledCount,
506 expanded: input.settledShelfExpanded !== false,
507 disabled: shelfDisabled,
508 });
509 result.push(...threadItems.slice(settledShelfHeaderIndex));
510 }
511 return result.map((entry, index) => {
512 if (entry.type !== "v2-thread" && entry.type !== "v2-pending") return entry;
513 const next = result[index + 1];
514 const showTrailingDivider =
515 next?.type === "v2-thread" || (next?.type === "v2-pending" && !next.showPendingDivider);
516 return showTrailingDivider === entry.showTrailingDivider
517 ? entry
518 : { ...entry, showTrailingDivider };
519 });
521​
522// Shells are immutable and the settled sort reads only their own fields, so an
523// element-identical input has an identical output.
524let lastSettledInput: ReadonlyArray<EnvironmentThreadShell> = [];
525let lastSettledOutput: ReadonlyArray<EnvironmentThreadShell> = [];
526​
527function sortSettledThreadsReusingLast(
528 settled: ReadonlyArray<EnvironmentThreadShell>,
529): ReadonlyArray<EnvironmentThreadShell> {
530 if (settled.length === lastSettledInput.length) {
531 let same = true;
532 for (let index = 0; index < settled.length; index += 1) {
533 if (settled[index] !== lastSettledInput[index]) {
534 same = false;
535 break;
536 }
537 }
538 if (same) return lastSettledOutput;
539 }
540 lastSettledInput = settled;
541 lastSettledOutput = sortSettledThreads(settled);
542 return lastSettledOutput;
544​
545export function buildThreadListV2Items(input: {
546 readonly pendingOrder?: PendingThreadOrder | null;
547 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
548 readonly environmentId: EnvironmentId | null;
549 readonly projectRefs?: ReadonlyArray<{
550 readonly environmentId: EnvironmentId;
551 readonly projectId: ProjectId;
552 }> | null;
553 readonly searchQuery: string;
554 readonly matchedThreadKeys?: ReadonlySet<string>;
555 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
556 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
557 readonly settledLimit?: number;
558 readonly now: string;
559 readonly workingShelfEnabled?: boolean;
560 readonly workingShelfExpanded?: boolean;
561 readonly inboxReturnAt?: (thread: EnvironmentThreadShell) => number | undefined;
562 readonly snoozedShelfExpanded?: boolean;
563 readonly settledShelfExpanded?: boolean;
564 readonly selectedThreadKey?: string | null;
565 readonly queuedThreadKeys?: ReadonlySet<string>;
566}): ThreadListV2Layout {
567 const now = input.now;
568 const pending =
569 input.pendingOrder == null
570 ? null
571 : reconcilePendingThreadOrder(
572 input.pendingOrder,
573 getThreadListV2OrderedSection({
574 ...input,
575 section: input.pendingOrder.section,
576 pendingOrder: null,
577 }),
578 );
579 const query = input.searchQuery.trim().toLocaleLowerCase();
580 const projectKeys = input.projectRefs
581 ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
582 : null;
583​
584 const workingShelfEnabled = input.workingShelfEnabled === true;
585 const pinned: EnvironmentThreadShell[] = [];
586 const active: EnvironmentThreadShell[] = [];
587 const working: EnvironmentThreadShell[] = [];
588 const settled: EnvironmentThreadShell[] = [];
589 const snoozed: EnvironmentThreadShell[] = [];
590 let nextSnoozeWakeAt: string | null = null;
591 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
592 for (const thread of input.threads) {
593 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent") continue;
594 if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
595 if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
596 continue;
597 }
598 if (
599 query.length > 0 &&
600 !thread.title.toLocaleLowerCase().includes(query) &&
601 !threadPullRequestSearchTerms(thread).some((term) =>
602 term.toLocaleLowerCase().includes(query),
603 ) &&
604 input.matchedThreadKeys?.has(
605 threadSearchMatchKey({
606 environmentId: thread.environmentId,
607 threadId: thread.id,
608 }),
609 ) !== true
610 ) {
611 continue;
612 }
613 const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
614 const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
615 if (supportsSnooze && effectiveSnoozed(thread, { now })) {
616 snoozed.push(thread);
617 if (
618 thread.snoozedUntil != null &&
619 (nextSnoozeWakeAt === null ||
620 parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
621 ) {
622 nextSnoozeWakeAt = thread.snoozedUntil;
623 }
624 continue;
625 }
626 const hasQueuedMessages =
627 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
628 if (supportsSettlement && thread.settledOverride === "settled" && !hasQueuedMessages) {
629 settled.push(thread);
630 } else if (thread.pinnedAt != null) {
631 pinned.push(thread);
632 } else if (workingShelfEnabled && isThreadWorking(thread)) {
633 working.push(thread);
634 } else {
635 active.push(thread);
636 }
637 }
638​
639 const orderedActive = workingShelfEnabled
640 ? sortInboxThreadsByReturn(active, input.inboxReturnAt)
641 : applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
642 const orderedWorking = sortWorkingThreadsBySend(working);
643 const orderedSnoozed = [...snoozed].sort(
644 (left, right) =>
645 parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
646 );
647 const selectedThreadKey = input.selectedThreadKey ?? null;
648 const visibleWorking =
649 input.workingShelfExpanded === true
650 ? orderedWorking
651 : orderedWorking.filter(
652 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
653 );
654 const visibleSnoozed =
655 input.snoozedShelfExpanded === true
656 ? orderedSnoozed
657 : orderedSnoozed.filter(
658 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
659 );
660 const orderedSettled = sortSettledThreadsReusingLast(settled);
661 const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
662 const limitedSettled =
663 orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
664 const selectedSettled =
665 selectedThreadKey === null
666 ? undefined
667 : orderedSettled
668 .slice(limitedSettled.length)
669 .find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
670 const pagedSettled =
671 selectedSettled === undefined ? limitedSettled : [...limitedSettled, selectedSettled];
672 const visibleSettled =
673 input.settledShelfExpanded !== false
674 ? pagedSettled
675 : pagedSettled.filter(
676 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
677 );
678​
679 const items: ThreadListV2Item[] = [];
680 for (const thread of applyPendingThreadOrder(
681 sortPinnedThreadsByOrderKey(pinned),
682 "pinned",
683 pending,
684 )) {
685 items.push({
686 thread,
687 variant: "card",
688 snoozed: false,
689 pinned: true,
690 isLast: false,
691 });
692 }
693 for (const thread of orderedActive) {
694 items.push({
695 thread,
696 variant: "card",
697 snoozed: false,
698 pinned: false,
699 isLast: false,
700 });
701 }
702 const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null;
703 for (const thread of visibleWorking) {
704 items.push({
705 thread,
706 variant: "card",
707 snoozed: false,
708 pinned: false,
709 isLast: false,
710 });
711 }
712 const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
713 for (const thread of visibleSnoozed) {
714 items.push({
715 thread,
716 variant: "slim",
717 snoozed: true,
718 pinned: false,
719 isLast: false,
720 });
721 }
722 const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
723 for (const thread of visibleSettled) {
724 items.push({
725 thread,
726 variant: "slim",
727 snoozed: false,
728 pinned: false,
729 isLast: false,
730 });
731 }
732 const last = items.at(-1);
733 if (last) {
734 items[items.length - 1] = { ...last, isLast: true };
735 }
736 return {
737 items,
738 hiddenSettledCount: orderedSettled.length - pagedSettled.length,
739 workingCount: orderedWorking.length,
740 workingShelfHeaderIndex,
741 snoozedCount: orderedSnoozed.length,
742 snoozedShelfHeaderIndex,
743 settledCount: orderedSettled.length,
744 settledShelfHeaderIndex,
745 nextSnoozeWakeAt,
746 };