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

threadListV2.ts

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