Open History to see the last commit
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;
58}
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" };
92}
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 };
116}
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;
136}
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;
152}
153
154export function resolveThreadListV2Status(
155 thread: Pick<
156 EnvironmentThreadShell,
157 | "hasPendingApprovals"
158 | "hasPendingUserInput"
159 | "pendingSubagentRequest"
160 | "runtime"
161 | "blockedOnThreadWait"
162 >,
163): ThreadListV2Status {
164 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
165 return "approval";
166 }
167 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
168 return "input";
169 }
170 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
171 return "waiting";
172 }
173 if (
174 thread.runtime !== null &&
175 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
176 ) {
177 return "working";
178 }
179 if (thread.runtime?.status === "idle") {
180 return "waiting";
181 }
182 if (thread.runtime?.status === "failed") {
183 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
184 }
185 return "ready";
186}
187
188function parseTimestampMs(isoDate: string): number {
189 const parsed = Date.parse(isoDate);
190 return Number.isNaN(parsed) ? 0 : parsed;
191}
192
193export function sortThreadsForListV2<
194 T extends {
195 readonly id: string;
196 readonly createdAt: string;
197 readonly unsettledAt?: string | null | undefined;
198 readonly activeOrderKey?: string | null | undefined;
199 readonly environmentId?: string | undefined;
200 },
201>(threads: readonly T[]): T[] {
202 return sortActiveThreadsByOrderKey(threads);
203}
204
205export function getThreadListV2OrderedSection(input: {
206 readonly threads: readonly EnvironmentThreadShell[];
207 readonly section: "pinned" | "active";
208 readonly pendingOrder?: PendingThreadOrder | null;
209 readonly now: string;
210 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
211 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
212 readonly queuedThreadKeys?: ReadonlySet<string>;
213}): EnvironmentThreadShell[] {
214 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
215 const threads = input.threads.filter((thread) => {
216 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
217 return false;
218 if (
219 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
220 thread.settledOverride === "settled" &&
221 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) !== true
222 ) {
223 return false;
224 }
225 if (
226 (input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true) &&
227 effectiveSnoozed(thread, { now: input.now })
228 ) {
229 return false;
230 }
231 return (thread.pinnedAt != null) === (input.section === "pinned");
232 });
233 const ordered =
234 input.section === "pinned"
235 ? sortPinnedThreadsByOrderKey(threads)
236 : sortActiveThreadsByOrderKey(threads);
237 const pending =
238 input.pendingOrder?.section === input.section
239 ? reconcilePendingThreadOrder(input.pendingOrder, ordered)
240 : null;
241 return applyPendingThreadOrder(ordered, input.section, pending);
242}
243
244export interface ThreadListV2Item {
245 readonly thread: EnvironmentThreadShell;
246 readonly variant: "card" | "slim";
247 readonly snoozed: boolean;
248 readonly pinned: boolean;
249 readonly isLast: boolean;
250}
251
252export interface ThreadListV2Layout {
253 readonly items: ThreadListV2Item[];
254 readonly hiddenSettledCount: number;
255 readonly workingCount: number;
256 readonly workingShelfHeaderIndex: number | null;
257 readonly snoozedCount: number;
258 readonly snoozedShelfHeaderIndex: number | null;
259 readonly settledCount: number;
260 readonly settledShelfHeaderIndex: number | null;
261 /**
262 * Callers arm a timeout at this boundary so the list re-partitions the moment
263 * a snooze expires instead of on the next minute tick.
264 */
265 readonly nextSnoozeWakeAt: string | null;
266}
267
268export interface ThreadListV2ThreadListItem {
269 readonly type: "v2-thread";
270 readonly key: string;
271 readonly item: ThreadListV2Item;
272 readonly snoozeWakeLabelText: string | undefined;
273 readonly timeLabel: string;
274 readonly snoozePresetMinute: string | undefined;
275 readonly showTrailingDivider: boolean;
276 /**
277 * Carried on the item so an outbox write (which never touches the thread
278 * shell) reaches the row through recycled-list equality instead of leaving a
279 * stale icon.
280 */
281 readonly hasQueuedMessages: boolean;
282 readonly canMoveUp: boolean;
283 readonly canMoveDown: boolean;
284}
285
286export interface ThreadListV2PendingListItem {
287 readonly type: "v2-pending";
288 readonly key: string;
289 readonly pendingTask: PendingNewTask;
290 readonly showPendingDivider: boolean;
291 readonly showTrailingDivider: boolean;
292}
293
294export interface ThreadListV2WorkingShelfListItem {
295 readonly type: "v2-working-shelf";
296 readonly key: "v2-working-shelf";
297 readonly count: number;
298 readonly expanded: boolean;
299 readonly disabled: boolean;
300}
301
302export interface ThreadListV2SnoozedShelfListItem {
303 readonly type: "v2-snoozed-shelf";
304 readonly key: "v2-snoozed-shelf";
305 readonly count: number;
306 readonly expanded: boolean;
307 /**
308 * Carried on the item because a recycled cell ignores the render closure —
309 * without it the header would stay visibly disabled (or enabled too early)
310 * after the preference load lands.
311 */
312 readonly disabled: boolean;
313}
314
315export interface ThreadListV2SettledShelfListItem {
316 readonly type: "v2-settled-shelf";
317 readonly key: "v2-settled-shelf";
318 readonly count: number;
319 readonly expanded: boolean;
320 readonly disabled: boolean;
321}
322
323export type ThreadListV2ListItem =
324 | ThreadListV2ThreadListItem
325 | ThreadListV2PendingListItem
326 | ThreadListV2WorkingShelfListItem
327 | ThreadListV2SnoozedShelfListItem
328 | ThreadListV2SettledShelfListItem;
329
330export function isThreadListV2ListItem(value: {
331 readonly type: string;
332}): value is ThreadListV2ListItem {
333 return (
334 value.type === "v2-thread" ||
335 value.type === "v2-pending" ||
336 value.type === "v2-working-shelf" ||
337 value.type === "v2-snoozed-shelf" ||
338 value.type === "v2-settled-shelf"
339 );
340}
341
342/**
343 * Item objects are rebuilt on every minute tick and every partition run;
344 * without this the lists would consider every mounted row changed and re-render
345 * all of them (each carrying a swipeable + a PR subscription).
346 */
347export function threadListV2ListItemsAreEqual(
348 previous: ThreadListV2ListItem,
349 item: ThreadListV2ListItem,
350): boolean {
351 switch (item.type) {
352 case "v2-thread":
353 return (
354 previous.type === "v2-thread" &&
355 previous.key === item.key &&
356 previous.item.thread === item.item.thread &&
357 previous.item.variant === item.item.variant &&
358 previous.item.snoozed === item.item.snoozed &&
359 previous.item.pinned === item.item.pinned &&
360 previous.snoozeWakeLabelText === item.snoozeWakeLabelText &&
361 previous.timeLabel === item.timeLabel &&
362 previous.snoozePresetMinute === item.snoozePresetMinute &&
363 previous.showTrailingDivider === item.showTrailingDivider &&
364 previous.hasQueuedMessages === item.hasQueuedMessages &&
365 previous.canMoveUp === item.canMoveUp &&
366 previous.canMoveDown === item.canMoveDown
367 );
368 case "v2-pending":
369 return (
370 previous.type === "v2-pending" &&
371 previous.key === item.key &&
372 previous.pendingTask === item.pendingTask &&
373 previous.showPendingDivider === item.showPendingDivider &&
374 previous.showTrailingDivider === item.showTrailingDivider
375 );
376 case "v2-working-shelf":
377 return (
378 previous.type === "v2-working-shelf" &&
379 previous.count === item.count &&
380 previous.expanded === item.expanded &&
381 previous.disabled === item.disabled
382 );
383 case "v2-snoozed-shelf":
384 return (
385 previous.type === "v2-snoozed-shelf" &&
386 previous.count === item.count &&
387 previous.expanded === item.expanded &&
388 previous.disabled === item.disabled
389 );
390 case "v2-settled-shelf":
391 return (
392 previous.type === "v2-settled-shelf" &&
393 previous.count === item.count &&
394 previous.expanded === item.expanded &&
395 previous.disabled === item.disabled
396 );
397 }
398}
399
400function resolveThreadListV2ItemTimeLabel(
401 item: ThreadListV2Item,
402 showSnoozeWakeLabel: boolean,
403): string {
404 const { thread, variant, snoozed } = item;
405 if (showSnoozeWakeLabel) return "";
406 if (
407 variant === "card" &&
408 (resolveThreadListV2Status(thread) !== "ready" || threadHasUnseenCompletion(thread))
409 )
410 return "";
411 const settledTimestamp =
412 variant === "slim" && !snoozed ? resolveSettledThreadTimestamp(thread) : null;
413 return relativeTime(
414 settledTimestamp ?? thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
415 );
416}
417
418export function buildThreadListV2ListItems(input: {
419 readonly items: ReadonlyArray<ThreadListV2Item>;
420 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
421 readonly workingCount?: number;
422 readonly workingShelfExpanded?: boolean;
423 readonly workingShelfHeaderIndex?: number | null;
424 readonly snoozedCount?: number;
425 readonly snoozedShelfExpanded?: boolean;
426 readonly snoozedShelfHeaderIndex?: number | null;
427 readonly settledCount?: number;
428 readonly settledShelfExpanded?: boolean;
429 readonly settledShelfHeaderIndex?: number | null;
430 readonly snoozeLabelNow?: string;
431 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
432 readonly queuedThreadKeys?: ReadonlySet<string>;
433 readonly moveAvailability?: ReadonlyMap<string, ThreadMoveAvailability>;
434 readonly shelfPreferencesLoading?: boolean;
435}): ThreadListV2ListItem[] {
436 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
437 const threadItems = input.items.map((item): ThreadListV2ListItem => {
438 const snoozeWakeLabelText =
439 item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
440 ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
441 : undefined;
442 // The minute clock belongs on the item, not the list's extraData, so the
443 // recycler's equality can confine the per-minute re-render to rows whose
444 // snooze menu actually shows preset times.
445 const snoozePresetMinute =
446 !item.snoozed &&
447 input.snoozeLabelNow !== undefined &&
448 (input.snoozeEnvironmentIds?.has(item.thread.environmentId) ?? true) &&
449 canSnooze(item.thread, { now: input.snoozeLabelNow })
450 ? input.snoozeLabelNow
451 : undefined;
452 const move =
453 item.variant === "card"
454 ? input.moveAvailability?.get(`${item.thread.environmentId}:${item.thread.id}`)
455 : undefined;
456 return {
457 type: "v2-thread",
458 key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
459 item,
460 snoozeWakeLabelText,
461 timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined),
462 snoozePresetMinute,
463 showTrailingDivider: false,
464 hasQueuedMessages:
465 queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true,
466 canMoveUp: move?.canMoveUp === true,
467 canMoveDown: move?.canMoveDown === true,
468 };
469 });
470 const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({
471 type: "v2-pending",
472 key: `v2-${pendingTask.key}`,
473 pendingTask,
474 showPendingDivider: index === 0,
475 showTrailingDivider: false,
476 }));
477 const workingCount = input.workingCount ?? 0;
478 const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null;
479 const snoozedCount = input.snoozedCount ?? 0;
480 const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
481 const settledCount = input.settledCount ?? 0;
482 const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
483 const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
484 const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd;
485 const activeEnd = workingShelfHeaderIndex ?? workingEnd;
486 const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, activeEnd)];
487 const shelfDisabled = input.shelfPreferencesLoading === true;
488 if (workingShelfHeaderIndex !== null && workingCount > 0) {
489 result.push({
490 type: "v2-working-shelf",
491 key: "v2-working-shelf",
492 count: workingCount,
493 expanded: input.workingShelfExpanded === true,
494 disabled: shelfDisabled,
495 });
496 result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd));
497 }
498 if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
499 result.push({
500 type: "v2-snoozed-shelf",
501 key: "v2-snoozed-shelf",
502 count: snoozedCount,
503 expanded: input.snoozedShelfExpanded === true,
504 disabled: shelfDisabled,
505 });
506 result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
507 }
508 if (settledShelfHeaderIndex !== null && settledCount > 0) {
509 result.push({
510 type: "v2-settled-shelf",
511 key: "v2-settled-shelf",
512 count: settledCount,
513 expanded: input.settledShelfExpanded !== false,
514 disabled: shelfDisabled,
515 });
516 result.push(...threadItems.slice(settledShelfHeaderIndex));
517 }
518 return result.map((entry, index) => {
519 if (entry.type !== "v2-thread" && entry.type !== "v2-pending") return entry;
520 const next = result[index + 1];
521 const showTrailingDivider =
522 next?.type === "v2-thread" || (next?.type === "v2-pending" && !next.showPendingDivider);
523 return showTrailingDivider === entry.showTrailingDivider
524 ? entry
525 : { ...entry, showTrailingDivider };
526 });
527}
528
529// Shells are immutable and the settled sort reads only their own fields, so an
530// element-identical input has an identical output.
531let lastSettledInput: ReadonlyArray<EnvironmentThreadShell> = [];
532let lastSettledOutput: ReadonlyArray<EnvironmentThreadShell> = [];
533
534function sortSettledThreadsReusingLast(
535 settled: ReadonlyArray<EnvironmentThreadShell>,
536): ReadonlyArray<EnvironmentThreadShell> {
537 if (settled.length === lastSettledInput.length) {
538 let same = true;
539 for (let index = 0; index < settled.length; index += 1) {
540 if (settled[index] !== lastSettledInput[index]) {
541 same = false;
542 break;
543 }
544 }
545 if (same) return lastSettledOutput;
546 }
547 lastSettledInput = settled;
548 lastSettledOutput = sortSettledThreads(settled);
549 return lastSettledOutput;
550}
551
552export function buildThreadListV2Items(input: {
553 readonly pendingOrder?: PendingThreadOrder | null;
554 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
555 readonly environmentId: EnvironmentId | null;
556 readonly projectRefs?: ReadonlyArray<{
557 readonly environmentId: EnvironmentId;
558 readonly projectId: ProjectId;
559 }> | null;
560 readonly searchQuery: string;
561 readonly matchedThreadKeys?: ReadonlySet<string>;
562 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
563 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
564 readonly settledLimit?: number;
565 readonly now: string;
566 readonly workingShelfEnabled?: boolean;
567 readonly workingShelfExpanded?: boolean;
568 readonly inboxReturnAt?: (thread: EnvironmentThreadShell) => number | undefined;
569 readonly snoozedShelfExpanded?: boolean;
570 readonly settledShelfExpanded?: boolean;
571 readonly selectedThreadKey?: string | null;
572 readonly queuedThreadKeys?: ReadonlySet<string>;
573}): ThreadListV2Layout {
574 const now = input.now;
575 const pending =
576 input.pendingOrder == null
577 ? null
578 : reconcilePendingThreadOrder(
579 input.pendingOrder,
580 getThreadListV2OrderedSection({
581 ...input,
582 section: input.pendingOrder.section,
583 pendingOrder: null,
584 }),
585 );
586 const query = input.searchQuery.trim().toLocaleLowerCase();
587 const projectKeys = input.projectRefs
588 ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
589 : null;
590
591 const workingShelfEnabled = input.workingShelfEnabled === true;
592 const pinned: EnvironmentThreadShell[] = [];
593 const active: EnvironmentThreadShell[] = [];
594 const working: EnvironmentThreadShell[] = [];
595 const settled: EnvironmentThreadShell[] = [];
596 const snoozed: EnvironmentThreadShell[] = [];
597 let nextSnoozeWakeAt: string | null = null;
598 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
599 for (const thread of input.threads) {
600 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent") continue;
601 if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
602 if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
603 continue;
604 }
605 if (
606 query.length > 0 &&
607 !thread.title.toLocaleLowerCase().includes(query) &&
608 !threadPullRequestSearchTerms(thread).some((term) =>
609 term.toLocaleLowerCase().includes(query),
610 ) &&
611 input.matchedThreadKeys?.has(
612 threadSearchMatchKey({
613 environmentId: thread.environmentId,
614 threadId: thread.id,
615 }),
616 ) !== true
617 ) {
618 continue;
619 }
620 const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
621 const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
622 if (supportsSnooze && effectiveSnoozed(thread, { now })) {
623 snoozed.push(thread);
624 if (
625 thread.snoozedUntil != null &&
626 (nextSnoozeWakeAt === null ||
627 parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
628 ) {
629 nextSnoozeWakeAt = thread.snoozedUntil;
630 }
631 continue;
632 }
633 const hasQueuedMessages =
634 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
635 if (supportsSettlement && thread.settledOverride === "settled" && !hasQueuedMessages) {
636 settled.push(thread);
637 } else if (thread.pinnedAt != null) {
638 pinned.push(thread);
639 } else if (workingShelfEnabled && isThreadWorking(thread)) {
640 working.push(thread);
641 } else {
642 active.push(thread);
643 }
644 }
645
646 const orderedActive = workingShelfEnabled
647 ? sortInboxThreadsByReturn(active, input.inboxReturnAt)
648 : applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
649 const orderedWorking = sortWorkingThreadsBySend(working);
650 const orderedSnoozed = [...snoozed].sort(
651 (left, right) =>
652 parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
653 );
654 const selectedThreadKey = input.selectedThreadKey ?? null;
655 const visibleWorking =
656 input.workingShelfExpanded === true
657 ? orderedWorking
658 : orderedWorking.filter(
659 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
660 );
661 const visibleSnoozed =
662 input.snoozedShelfExpanded === true
663 ? orderedSnoozed
664 : orderedSnoozed.filter(
665 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
666 );
667 const orderedSettled = sortSettledThreadsReusingLast(settled);
668 const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
669 const limitedSettled =
670 orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
671 const selectedSettled =
672 selectedThreadKey === null
673 ? undefined
674 : orderedSettled
675 .slice(limitedSettled.length)
676 .find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
677 const pagedSettled =
678 selectedSettled === undefined ? limitedSettled : [...limitedSettled, selectedSettled];
679 const visibleSettled =
680 input.settledShelfExpanded !== false
681 ? pagedSettled
682 : pagedSettled.filter(
683 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
684 );
685
686 const items: ThreadListV2Item[] = [];
687 for (const thread of applyPendingThreadOrder(
688 sortPinnedThreadsByOrderKey(pinned),
689 "pinned",
690 pending,
691 )) {
692 items.push({
693 thread,
694 variant: "card",
695 snoozed: false,
696 pinned: true,
697 isLast: false,
698 });
699 }
700 for (const thread of orderedActive) {
701 items.push({
702 thread,
703 variant: "card",
704 snoozed: false,
705 pinned: false,
706 isLast: false,
707 });
708 }
709 const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null;
710 for (const thread of visibleWorking) {
711 items.push({
712 thread,
713 variant: "card",
714 snoozed: false,
715 pinned: false,
716 isLast: false,
717 });
718 }
719 const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
720 for (const thread of visibleSnoozed) {
721 items.push({
722 thread,
723 variant: "slim",
724 snoozed: true,
725 pinned: false,
726 isLast: false,
727 });
728 }
729 const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
730 for (const thread of visibleSettled) {
731 items.push({
732 thread,
733 variant: "slim",
734 snoozed: false,
735 pinned: false,
736 isLast: false,
737 });
738 }
739 const last = items.at(-1);
740 if (last) {
741 items[items.length - 1] = { ...last, isLast: true };
742 }
743 return {
744 items,
745 hiddenSettledCount: orderedSettled.length - pagedSettled.length,
746 workingCount: orderedWorking.length,
747 workingShelfHeaderIndex,
748 snoozedCount: orderedSnoozed.length,
749 snoozedShelfHeaderIndex,
750 settledCount: orderedSettled.length,
751 settledShelfHeaderIndex,
752 nextSnoozeWakeAt,
753 };
754}