Open History to see the last commit
1import {
2 canSnooze,
3 effectiveSnoozed,
4 hasQueuedTurnStart,
5 pickSnoozePreset,
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 {
15 threadSearchMatchKey,
16 threadSearchSubject,
17} from "@t3tools/client-runtime/state/thread-search";
18import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
19import {
20 createInboxReturnTracker,
21 isThreadWorking,
22 sortInboxThreadsByReturn,
23 sortWorkingThreadsBySend,
24} from "@t3tools/client-runtime/state/thread-inbox";
25import {
26 sortActiveThreadsByOrderKey,
27 resolveSettledThreadTimestamp,
28 sortPinnedThreadsByOrderKey,
29 sortSettledThreads,
30} from "@t3tools/client-runtime/state/thread-sort";
31import { isListedThreadLineage, type EnvironmentId, type ProjectId } from "@t3tools/contracts";
32import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
33
34import type { ThreadListProvider } from "../../state/thread-list-environments";
35import type { ThreadMoveAvailability } from "./threadOrder";
36
37import { relativeTime } from "../../lib/time";
38import type { PendingNewTask } from "../../state/use-pending-new-tasks";
39
40import {
41 applyPendingThreadOrder,
42 reconcilePendingThreadOrder,
43 type PendingThreadOrder,
44} from "./threadOrder";
45
46export const threadListInboxReturns = createInboxReturnTracker();
47
48export function resolveThreadListV2ProviderDrivers(
49 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
50 providers: ReadonlyArray<ThreadListProvider> | undefined,
51): ReadonlyArray<string> {
52 if (providers === undefined) return [];
53 const stack = resolveThreadProviderStack(thread);
54 const drivers = stack.flatMap((instanceId) => {
55 const driver = providers.find((provider) => provider.instanceId === instanceId)?.driver;
56 return driver === undefined ? [] : [driver];
57 });
58 const currentDriver = providers.find(
59 (provider) => provider.instanceId === stack[stack.length - 1],
60 )?.driver;
61 return currentDriver === undefined ? [] : drivers;
62}
63
64export type ThreadListV2Status =
65 | "approval"
66 | "input"
67 | "request"
68 | "working"
69 | "waiting"
70 | "failed"
71 | "limited"
72 | "ready";
73export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
74
75/**
76 * Presets for a row's snooze menu, read at the list's minute instead of the
77 * clock: the compiler keys a row's memo on its inputs, so a clock read inside
78 * it would keep the times from the row's first render.
79 */
80export function resolveThreadListV2SnoozePresets(input: {
81 readonly secondary: "snooze" | null;
82 readonly now: string;
83 readonly presets: ReadonlyArray<SnoozePresetSetting> | undefined;
84}): ReadonlyArray<SnoozePreset> {
85 return input.secondary === "snooze"
86 ? resolveSnoozePresets(new Date(input.now), presetOptions(input.presets))
87 : [];
88}
89
90function presetOptions(presets: ReadonlyArray<SnoozePresetSetting> | undefined) {
91 return presets ? { presets } : {};
92}
93
94export function resolveThreadListV2SnoozeMenuSelection(input: {
95 readonly event: string;
96 readonly displayedPresets: ReadonlyArray<SnoozePreset>;
97 readonly now: Date;
98 readonly presets: ReadonlyArray<SnoozePresetSetting> | undefined;
99}):
100 | { readonly _tag: "selected"; readonly preset: SnoozePreset }
101 | { readonly _tag: "expired" }
102 | { readonly _tag: "not-snooze" } {
103 if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
104 const preset = pickSnoozePreset({
105 shown: input.displayedPresets,
106 id: input.event.slice("snooze:".length),
107 now: input.now,
108 ...presetOptions(input.presets),
109 });
110 return preset ? { _tag: "selected", preset } : { _tag: "expired" };
111}
112
113export function resolveThreadListV2SwipeActions(input: {
114 readonly variant: "card" | "slim";
115 readonly settlementSupported: boolean;
116 readonly snoozeSupported: boolean;
117 readonly snoozable: boolean;
118 readonly snoozed?: boolean;
119}): {
120 readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
121 readonly secondary: "snooze" | null;
122} {
123 if (input.snoozed === true) {
124 return { primary: "unsnooze", secondary: null };
125 }
126 const primary = input.settlementSupported
127 ? input.variant === "slim"
128 ? "unsettle"
129 : "settle"
130 : "archive";
131 return {
132 primary,
133 secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
134 };
135}
136
137export function resolveThreadListV2SnoozeGateExpiryMs(
138 thread: Pick<
139 EnvironmentThreadShell,
140 | "hasPendingApprovals"
141 | "hasPendingUserInput"
142 | "pendingSubagentRequest"
143 | "latestRun"
144 | "latestUserMessageAt"
145 | "runtime"
146 >,
147 options: { readonly now: string },
148): number | null {
149 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
150 if (thread.pendingSubagentRequest != null) return null;
151 if (!hasQueuedTurnStart(thread, options)) return null;
152 const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
153 if (Number.isNaN(messageAtMs)) return null;
154 return messageAtMs + QUEUED_TURN_START_GRACE_MS;
155}
156
157/** The earliest `snoozedUntil` strictly after `nowMs`, in epoch ms. */
158export function nextSnoozeWakeAfter(
159 threads: ReadonlyArray<{ readonly snoozedUntil?: string | null }>,
160 nowMs: number,
161): number | null {
162 let next: number | null = null;
163 for (const thread of threads) {
164 if (thread.snoozedUntil == null) continue;
165 const wakeAtMs = Date.parse(thread.snoozedUntil);
166 if (wakeAtMs > nowMs && (next === null || wakeAtMs < next)) next = wakeAtMs;
167 }
168 return next;
169}
170
171export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
172export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
173
174export function threadHasUnseenCompletion(
175 thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
176): boolean {
177 const completedAt = thread.latestRun?.completedAt;
178 if (!completedAt) return false;
179 const completedAtMs = Date.parse(completedAt);
180 if (Number.isNaN(completedAtMs)) return false;
181 if (!thread.lastVisitedAt) return false;
182 const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
183 if (Number.isNaN(lastVisitedAtMs)) return true;
184 return completedAtMs > lastVisitedAtMs;
185}
186
187export function resolveThreadListV2WokeAt(
188 thread: EnvironmentThreadShell,
189 options: { readonly now: string },
190): string | null {
191 // Older servers cannot persist an acknowledgement.
192 if (thread.lastVisitedAt === undefined || thread.settledOverride === "settled") return null;
193 const wokeAt = threadWokeAt(thread, options);
194 const wokeAtMs = Date.parse(wokeAt ?? "");
195 const lastVisitedAtMs = Date.parse(thread.lastVisitedAt ?? "");
196 return !Number.isNaN(wokeAtMs) && (Number.isNaN(lastVisitedAtMs) || lastVisitedAtMs < wokeAtMs)
197 ? wokeAt
198 : null;
199}
200
201export function resolveThreadListV2Status(
202 thread: Pick<
203 EnvironmentThreadShell,
204 | "hasPendingApprovals"
205 | "hasPendingUserInput"
206 | "pendingSubagentRequest"
207 | "pendingGuestMessageCount"
208 | "runtime"
209 | "blockedOnThreadWait"
210 >,
211): ThreadListV2Status {
212 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
213 return "approval";
214 }
215 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
216 return "input";
217 }
218 // A guest is waiting on the owner; the agent's own requests come first.
219 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
220 return "request";
221 }
222 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
223 return "waiting";
224 }
225 if (
226 thread.runtime !== null &&
227 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
228 ) {
229 return "working";
230 }
231 if (thread.runtime?.status === "idle") {
232 return "waiting";
233 }
234 if (thread.runtime?.status === "failed") {
235 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
236 }
237 return "ready";
238}
239
240function parseTimestampMs(isoDate: string): number {
241 const parsed = Date.parse(isoDate);
242 return Number.isNaN(parsed) ? 0 : parsed;
243}
244
245export function sortThreadsForListV2<
246 T extends {
247 readonly id: string;
248 readonly createdAt: string;
249 readonly unsettledAt?: string | null | undefined;
250 readonly activeOrderKey?: string | null | undefined;
251 readonly environmentId?: string | undefined;
252 },
253>(threads: readonly T[]): T[] {
254 return sortActiveThreadsByOrderKey(threads);
255}
256
257export function getThreadListV2OrderedSection(input: {
258 readonly threads: readonly EnvironmentThreadShell[];
259 readonly section: "pinned" | "active";
260 readonly pendingOrder?: PendingThreadOrder | null;
261 readonly now: string;
262 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
263 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
264 readonly queuedThreadKeys?: ReadonlySet<string>;
265}): EnvironmentThreadShell[] {
266 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
267 const threads = input.threads.filter((thread) => {
268 if (thread.archivedAt !== null || !isListedThreadLineage(thread.lineage)) return false;
269 if (
270 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
271 thread.settledOverride === "settled" &&
272 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) !== true
273 ) {
274 return false;
275 }
276 if (
277 (input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true) &&
278 effectiveSnoozed(thread, { now: input.now })
279 ) {
280 return false;
281 }
282 return (thread.pinnedAt != null) === (input.section === "pinned");
283 });
284 const ordered =
285 input.section === "pinned"
286 ? sortPinnedThreadsByOrderKey(threads)
287 : sortActiveThreadsByOrderKey(threads);
288 const pending =
289 input.pendingOrder?.section === input.section
290 ? reconcilePendingThreadOrder(input.pendingOrder, ordered)
291 : null;
292 return applyPendingThreadOrder(ordered, input.section, pending);
293}
294
295export interface ThreadListV2Item {
296 readonly thread: EnvironmentThreadShell;
297 readonly variant: "card" | "slim";
298 readonly snoozed: boolean;
299 readonly pinned: boolean;
300 readonly wokeAt: string | null;
301 readonly isLast: boolean;
302}
303
304export interface ThreadListV2Layout {
305 readonly items: ThreadListV2Item[];
306 readonly hiddenSettledCount: number;
307 /** The settled rows the shelf may list, before its visible limit. */
308 readonly listedSettledThreads: ReadonlyArray<EnvironmentThreadShell>;
309 readonly workingCount: number;
310 readonly workingShelfHeaderIndex: number | null;
311 readonly snoozedCount: number;
312 readonly snoozedShelfHeaderIndex: number | null;
313 readonly settledCount: number;
314 readonly settledShelfHeaderIndex: number | null;
315 /** Arm a timeout here to repartition at snooze expiry rather than the next minute tick. */
316 readonly nextSnoozeWakeAt: string | null;
317 /** Threads listed only because their messages match the search. */
318 readonly contentOnlyThreadKeys: ReadonlySet<string>;
319}
320
321export interface ThreadListV2ThreadListItem {
322 readonly type: "v2-thread";
323 readonly key: string;
324 readonly item: ThreadListV2Item;
325 readonly snoozeWakeLabelText: string | undefined;
326 readonly timeLabel: string;
327 readonly snoozePresetMinute: string | undefined;
328 readonly showTrailingDivider: boolean;
329 /** Include queued state in item equality; outbox writes do not update thread shells. */
330 readonly hasQueuedMessages: boolean;
331 readonly canMoveUp: boolean;
332 readonly canMoveDown: boolean;
333}
334
335export interface ThreadListV2PendingListItem {
336 readonly type: "v2-pending";
337 readonly key: string;
338 readonly pendingTask: PendingNewTask;
339 readonly showPendingDivider: boolean;
340 readonly showTrailingDivider: boolean;
341}
342
343export interface ThreadListV2WorkingShelfListItem {
344 readonly type: "v2-working-shelf";
345 readonly key: "v2-working-shelf";
346 readonly count: number;
347 readonly expanded: boolean;
348 readonly disabled: boolean;
349}
350
351export interface ThreadListV2SnoozedShelfListItem {
352 readonly type: "v2-snoozed-shelf";
353 readonly key: "v2-snoozed-shelf";
354 readonly count: number;
355 readonly expanded: boolean;
356 /** Include disabled state in item equality; recycled cells ignore render-closure updates. */
357 readonly disabled: boolean;
358}
359
360export interface ThreadListV2SettledShelfListItem {
361 readonly type: "v2-settled-shelf";
362 readonly key: "v2-settled-shelf";
363 readonly count: number;
364 readonly expanded: boolean;
365 readonly disabled: boolean;
366}
367
368export type ThreadListV2ListItem =
369 | ThreadListV2ThreadListItem
370 | ThreadListV2PendingListItem
371 | ThreadListV2WorkingShelfListItem
372 | ThreadListV2SnoozedShelfListItem
373 | ThreadListV2SettledShelfListItem;
374
375export function isThreadListV2ListItem(value: {
376 readonly type: string;
377}): value is ThreadListV2ListItem {
378 return (
379 value.type === "v2-thread" ||
380 value.type === "v2-pending" ||
381 value.type === "v2-working-shelf" ||
382 value.type === "v2-snoozed-shelf" ||
383 value.type === "v2-settled-shelf"
384 );
385}
386
387/** Compare rebuilt items by content so minute ticks and partition runs do not re-render every mounted row. */
388export function threadListV2ListItemsAreEqual(
389 previous: ThreadListV2ListItem,
390 item: ThreadListV2ListItem,
391): boolean {
392 switch (item.type) {
393 case "v2-thread":
394 return (
395 previous.type === "v2-thread" &&
396 previous.key === item.key &&
397 previous.item.thread === item.item.thread &&
398 previous.item.variant === item.item.variant &&
399 previous.item.snoozed === item.item.snoozed &&
400 previous.item.pinned === item.item.pinned &&
401 previous.item.wokeAt === item.item.wokeAt &&
402 previous.snoozeWakeLabelText === item.snoozeWakeLabelText &&
403 previous.timeLabel === item.timeLabel &&
404 previous.snoozePresetMinute === item.snoozePresetMinute &&
405 previous.showTrailingDivider === item.showTrailingDivider &&
406 previous.hasQueuedMessages === item.hasQueuedMessages &&
407 previous.canMoveUp === item.canMoveUp &&
408 previous.canMoveDown === item.canMoveDown
409 );
410 case "v2-pending":
411 return (
412 previous.type === "v2-pending" &&
413 previous.key === item.key &&
414 previous.pendingTask === item.pendingTask &&
415 previous.showPendingDivider === item.showPendingDivider &&
416 previous.showTrailingDivider === item.showTrailingDivider
417 );
418 case "v2-working-shelf":
419 return (
420 previous.type === "v2-working-shelf" &&
421 previous.count === item.count &&
422 previous.expanded === item.expanded &&
423 previous.disabled === item.disabled
424 );
425 case "v2-snoozed-shelf":
426 return (
427 previous.type === "v2-snoozed-shelf" &&
428 previous.count === item.count &&
429 previous.expanded === item.expanded &&
430 previous.disabled === item.disabled
431 );
432 case "v2-settled-shelf":
433 return (
434 previous.type === "v2-settled-shelf" &&
435 previous.count === item.count &&
436 previous.expanded === item.expanded &&
437 previous.disabled === item.disabled
438 );
439 }
440}
441
442function resolveThreadListV2ItemTimeLabel(
443 item: ThreadListV2Item,
444 showSnoozeWakeLabel: boolean,
445): string {
446 const { thread, variant, snoozed } = item;
447 if (showSnoozeWakeLabel) return "";
448 if (
449 variant === "card" &&
450 (resolveThreadListV2Status(thread) !== "ready" ||
451 item.wokeAt !== null ||
452 threadHasUnseenCompletion(thread))
453 )
454 return "";
455 const settledTimestamp =
456 variant === "slim" && !snoozed ? resolveSettledThreadTimestamp(thread) : null;
457 return relativeTime(
458 settledTimestamp ?? thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
459 );
460}
461
462export function buildThreadListV2ListItems(input: {
463 readonly items: ReadonlyArray<ThreadListV2Item>;
464 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
465 readonly workingCount?: number;
466 readonly workingShelfExpanded?: boolean;
467 readonly workingShelfHeaderIndex?: number | null;
468 readonly snoozedCount?: number;
469 readonly snoozedShelfExpanded?: boolean;
470 readonly snoozedShelfHeaderIndex?: number | null;
471 readonly settledCount?: number;
472 readonly settledShelfExpanded?: boolean;
473 readonly settledShelfHeaderIndex?: number | null;
474 readonly snoozeLabelNow?: string;
475 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
476 readonly queuedThreadKeys?: ReadonlySet<string>;
477 readonly moveAvailability?: ReadonlyMap<string, ThreadMoveAvailability>;
478 readonly shelfPreferencesLoading?: boolean;
479}): ThreadListV2ListItem[] {
480 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
481 const threadItems = input.items.map((item): ThreadListV2ListItem => {
482 const snoozeWakeLabelText =
483 item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
484 ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
485 : undefined;
486 // Put the clock on items so recycler equality limits ticks to rows displaying snooze preset times.
487 const snoozePresetMinute =
488 !item.snoozed &&
489 input.snoozeLabelNow !== undefined &&
490 (input.snoozeEnvironmentIds?.has(item.thread.environmentId) ?? true) &&
491 canSnooze(item.thread, { now: input.snoozeLabelNow })
492 ? input.snoozeLabelNow
493 : undefined;
494 const move =
495 item.variant === "card"
496 ? input.moveAvailability?.get(`${item.thread.environmentId}:${item.thread.id}`)
497 : undefined;
498 return {
499 type: "v2-thread",
500 key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
501 item,
502 snoozeWakeLabelText,
503 timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined),
504 snoozePresetMinute,
505 showTrailingDivider: false,
506 hasQueuedMessages:
507 queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true,
508 canMoveUp: move?.canMoveUp === true,
509 canMoveDown: move?.canMoveDown === true,
510 };
511 });
512 const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({
513 type: "v2-pending",
514 key: `v2-${pendingTask.key}`,
515 pendingTask,
516 showPendingDivider: index === 0,
517 showTrailingDivider: false,
518 }));
519 const workingCount = input.workingCount ?? 0;
520 const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null;
521 const snoozedCount = input.snoozedCount ?? 0;
522 const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
523 const settledCount = input.settledCount ?? 0;
524 const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
525 const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
526 const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd;
527 const activeEnd = workingShelfHeaderIndex ?? workingEnd;
528 const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, activeEnd)];
529 const shelfDisabled = input.shelfPreferencesLoading === true;
530 if (workingShelfHeaderIndex !== null && workingCount > 0) {
531 result.push({
532 type: "v2-working-shelf",
533 key: "v2-working-shelf",
534 count: workingCount,
535 expanded: input.workingShelfExpanded === true,
536 disabled: shelfDisabled,
537 });
538 result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd));
539 }
540 if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
541 result.push({
542 type: "v2-snoozed-shelf",
543 key: "v2-snoozed-shelf",
544 count: snoozedCount,
545 expanded: input.snoozedShelfExpanded === true,
546 disabled: shelfDisabled,
547 });
548 result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
549 }
550 if (settledShelfHeaderIndex !== null && settledCount > 0) {
551 result.push({
552 type: "v2-settled-shelf",
553 key: "v2-settled-shelf",
554 count: settledCount,
555 expanded: input.settledShelfExpanded !== false,
556 disabled: shelfDisabled,
557 });
558 result.push(...threadItems.slice(settledShelfHeaderIndex));
559 }
560 return result.map((entry, index) => {
561 if (entry.type !== "v2-thread" && entry.type !== "v2-pending") return entry;
562 const next = result[index + 1];
563 const showTrailingDivider =
564 next?.type === "v2-thread" || (next?.type === "v2-pending" && !next.showPendingDivider);
565 return showTrailingDivider === entry.showTrailingDivider
566 ? entry
567 : { ...entry, showTrailingDivider };
568 });
569}
570
571// Immutable shells and field-only sorting make element-identical inputs produce identical output.
572let lastSettledInput: ReadonlyArray<EnvironmentThreadShell> = [];
573let lastSettledOutput: ReadonlyArray<EnvironmentThreadShell> = [];
574
575function sortSettledThreadsReusingLast(
576 settled: ReadonlyArray<EnvironmentThreadShell>,
577): ReadonlyArray<EnvironmentThreadShell> {
578 if (settled.length === lastSettledInput.length) {
579 let same = true;
580 for (let index = 0; index < settled.length; index += 1) {
581 if (settled[index] !== lastSettledInput[index]) {
582 same = false;
583 break;
584 }
585 }
586 if (same) return lastSettledOutput;
587 }
588 lastSettledInput = settled;
589 lastSettledOutput = sortSettledThreads(settled);
590 return lastSettledOutput;
591}
592
593export function buildThreadListV2Items(input: {
594 readonly pendingOrder?: PendingThreadOrder | null;
595 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
596 readonly environmentId: EnvironmentId | null;
597 readonly projectRefs?: ReadonlyArray<{
598 readonly environmentId: EnvironmentId;
599 readonly projectId: ProjectId;
600 }> | null;
601 readonly searchQuery: string;
602 readonly matchedThreadKeys?: ReadonlySet<string>;
603 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
604 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
605 readonly settledLimit?: number;
606 readonly now: string;
607 readonly workingShelfEnabled?: boolean;
608 readonly workingShelfExpanded?: boolean;
609 readonly isWorking?: (thread: EnvironmentThreadShell) => boolean;
610 readonly inboxReturnAt?: (thread: EnvironmentThreadShell) => number | undefined;
611 readonly snoozedShelfExpanded?: boolean;
612 readonly settledShelfExpanded?: boolean;
613 readonly selectedThreadKey?: string | null;
614 readonly queuedThreadKeys?: ReadonlySet<string>;
615 /** Whether the shelf may list a settled row yet; older settled rows load in pages. */
616 readonly isListedSettled?: (thread: EnvironmentThreadShell) => boolean;
617 /** Settled threads in scope that are not local (older settled threads not loaded). */
618 readonly unloadedSettledCount?: number;
619}): ThreadListV2Layout {
620 const now = input.now;
621 const pending =
622 input.pendingOrder == null
623 ? null
624 : reconcilePendingThreadOrder(
625 input.pendingOrder,
626 getThreadListV2OrderedSection({
627 ...input,
628 section: input.pendingOrder.section,
629 pendingOrder: null,
630 }),
631 );
632 const query = foldSearchQuery(input.searchQuery);
633 const nowMs = Date.parse(now);
634 const projectKeys = input.projectRefs
635 ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
636 : null;
637
638 const workingShelfEnabled = input.workingShelfEnabled === true;
639 const pinned: EnvironmentThreadShell[] = [];
640 const active: EnvironmentThreadShell[] = [];
641 const working: EnvironmentThreadShell[] = [];
642 const settled: EnvironmentThreadShell[] = [];
643 const snoozed: EnvironmentThreadShell[] = [];
644 let nextSnoozeWakeAt: string | null = null;
645 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
646 const listedThreads = input.threads.filter(
647 (thread) =>
648 thread.archivedAt === null &&
649 isListedThreadLineage(thread.lineage) &&
650 (input.environmentId === null || thread.environmentId === input.environmentId) &&
651 (projectKeys === null || projectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
652 );
653 // The same matches as the command palette, typo fallback included. Only
654 // listed threads are ranked: a hidden exact match must not turn typos off.
655 const rankedMatches =
656 query.length > 0
657 ? rankSearchItems(listedThreads, (thread, options) =>
658 scoreThreadSearch(query, threadSearchSubject(thread, null), nowMs, {
659 ...options,
660 picks: false,
661 }),
662 ).map(({ item }) => item)
663 : null;
664 const matchingThreads = rankedMatches === null ? null : new Set(rankedMatches);
665 // Threads listed only because their messages match; only their rows show
666 // the message and open at it.
667 const contentOnlyThreadKeys = new Set<string>();
668 for (const thread of listedThreads) {
669 if (matchingThreads !== null && !matchingThreads.has(thread)) {
670 const key = threadSearchMatchKey({
671 environmentId: thread.environmentId,
672 threadId: thread.id,
673 });
674 if (input.matchedThreadKeys?.has(key) !== true) continue;
675 contentOnlyThreadKeys.add(key);
676 }
677 const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
678 const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
679 if (supportsSnooze && effectiveSnoozed(thread, { now })) {
680 snoozed.push(thread);
681 if (
682 thread.snoozedUntil != null &&
683 (nextSnoozeWakeAt === null ||
684 parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
685 ) {
686 nextSnoozeWakeAt = thread.snoozedUntil;
687 }
688 continue;
689 }
690 const hasQueuedMessages =
691 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
692 if (supportsSettlement && thread.settledOverride === "settled" && !hasQueuedMessages) {
693 settled.push(thread);
694 } else if (thread.pinnedAt != null) {
695 pinned.push(thread);
696 } else if (workingShelfEnabled && (input.isWorking ?? isThreadWorking)(thread)) {
697 working.push(thread);
698 } else {
699 active.push(thread);
700 }
701 }
702
703 if (rankedMatches !== null) {
704 // Searching lists every match by rank across shelves, as the palette and
705 // the web sidebar do, then threads listed for their messages in the
706 // server's order. Each row keeps its shelf's look.
707 const slim = new Set([...snoozed, ...settled]);
708 const snoozedThreads = new Set(snoozed);
709 const pinnedThreads = new Set(pinned);
710 const threadByKey = new Map(
711 listedThreads.map((thread) => [
712 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
713 thread,
714 ]),
715 );
716 const contentOnly = [...(input.matchedThreadKeys ?? [])].flatMap((key) => {
717 const thread = contentOnlyThreadKeys.has(key) ? threadByKey.get(key) : undefined;
718 return thread ? [thread] : [];
719 });
720 const results = [...rankedMatches, ...contentOnly];
721 return {
722 items: results.map((thread, index) => ({
723 thread,
724 variant: slim.has(thread) ? "slim" : "card",
725 snoozed: snoozedThreads.has(thread),
726 pinned: pinnedThreads.has(thread),
727 wokeAt: slim.has(thread) ? null : resolveThreadListV2WokeAt(thread, { now }),
728 isLast: index === results.length - 1,
729 })),
730 hiddenSettledCount: 0,
731 listedSettledThreads: [],
732 workingCount: 0,
733 workingShelfHeaderIndex: null,
734 snoozedCount: 0,
735 snoozedShelfHeaderIndex: null,
736 settledCount: 0,
737 settledShelfHeaderIndex: null,
738 nextSnoozeWakeAt,
739 contentOnlyThreadKeys,
740 };
741 }
742
743 const orderedActive = workingShelfEnabled
744 ? sortInboxThreadsByReturn(active, input.inboxReturnAt)
745 : applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
746 const orderedWorking = sortWorkingThreadsBySend(working);
747 const orderedSnoozed = [...snoozed].sort(
748 (left, right) =>
749 parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
750 );
751 const selectedThreadKey = input.selectedThreadKey ?? null;
752 const visibleWorking =
753 input.workingShelfExpanded === true
754 ? orderedWorking
755 : orderedWorking.filter(
756 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
757 );
758 const visibleSnoozed =
759 input.snoozedShelfExpanded === true
760 ? orderedSnoozed
761 : orderedSnoozed.filter(
762 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
763 );
764 const orderedSettled = sortSettledThreadsReusingLast(settled);
765 const listedSettled =
766 input.isListedSettled === undefined
767 ? orderedSettled
768 : orderedSettled.filter(input.isListedSettled);
769 const settledTotal = orderedSettled.length + (input.unloadedSettledCount ?? 0);
770 const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
771 const limitedSettled =
772 listedSettled.length > settledLimit ? listedSettled.slice(0, settledLimit) : listedSettled;
773 const selectedSettled =
774 selectedThreadKey === null ||
775 limitedSettled.some((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey)
776 ? undefined
777 : orderedSettled.find(
778 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
779 );
780 const pagedSettled =
781 selectedSettled === undefined ? limitedSettled : [...limitedSettled, selectedSettled];
782 const visibleSettled =
783 input.settledShelfExpanded !== false
784 ? pagedSettled
785 : pagedSettled.filter(
786 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
787 );
788
789 const items: ThreadListV2Item[] = [];
790 for (const thread of applyPendingThreadOrder(
791 sortPinnedThreadsByOrderKey(pinned),
792 "pinned",
793 pending,
794 )) {
795 items.push({
796 thread,
797 variant: "card",
798 snoozed: false,
799 pinned: true,
800 wokeAt: resolveThreadListV2WokeAt(thread, { now }),
801 isLast: false,
802 });
803 }
804 for (const thread of orderedActive) {
805 items.push({
806 thread,
807 variant: "card",
808 snoozed: false,
809 pinned: false,
810 wokeAt: resolveThreadListV2WokeAt(thread, { now }),
811 isLast: false,
812 });
813 }
814 const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null;
815 for (const thread of visibleWorking) {
816 items.push({
817 thread,
818 variant: "card",
819 snoozed: false,
820 pinned: false,
821 wokeAt: resolveThreadListV2WokeAt(thread, { now }),
822 isLast: false,
823 });
824 }
825 const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
826 for (const thread of visibleSnoozed) {
827 items.push({
828 thread,
829 variant: "slim",
830 snoozed: true,
831 pinned: false,
832 wokeAt: null,
833 isLast: false,
834 });
835 }
836 const settledShelfHeaderIndex = settledTotal > 0 ? items.length : null;
837 for (const thread of visibleSettled) {
838 items.push({
839 thread,
840 variant: "slim",
841 snoozed: false,
842 pinned: false,
843 wokeAt: null,
844 isLast: false,
845 });
846 }
847 const last = items.at(-1);
848 if (last) {
849 items[items.length - 1] = { ...last, isLast: true };
850 }
851 return {
852 items,
853 hiddenSettledCount: Math.max(0, settledTotal - pagedSettled.length),
854 listedSettledThreads: listedSettled,
855 workingCount: orderedWorking.length,
856 workingShelfHeaderIndex,
857 snoozedCount: orderedSnoozed.length,
858 snoozedShelfHeaderIndex,
859 settledCount: settledTotal,
860 settledShelfHeaderIndex,
861 nextSnoozeWakeAt,
862 contentOnlyThreadKeys,
863 };
864}