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 type { EnvironmentId, 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 || thread.lineage.relationshipToParent === "subagent")
269 return false;
270 if (
271 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
272 thread.settledOverride === "settled" &&
273 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) !== true
274 ) {
275 return false;
276 }
277 if (
278 (input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true) &&
279 effectiveSnoozed(thread, { now: input.now })
280 ) {
281 return false;
282 }
283 return (thread.pinnedAt != null) === (input.section === "pinned");
284 });
285 const ordered =
286 input.section === "pinned"
287 ? sortPinnedThreadsByOrderKey(threads)
288 : sortActiveThreadsByOrderKey(threads);
289 const pending =
290 input.pendingOrder?.section === input.section
291 ? reconcilePendingThreadOrder(input.pendingOrder, ordered)
292 : null;
293 return applyPendingThreadOrder(ordered, input.section, pending);
294}
295
296export interface ThreadListV2Item {
297 readonly thread: EnvironmentThreadShell;
298 readonly variant: "card" | "slim";
299 readonly snoozed: boolean;
300 readonly pinned: boolean;
301 readonly wokeAt: string | null;
302 readonly isLast: boolean;
303}
304
305export interface ThreadListV2Layout {
306 readonly items: ThreadListV2Item[];
307 readonly hiddenSettledCount: number;
308 /** The settled rows the shelf may list, before its visible limit. */
309 readonly listedSettledThreads: ReadonlyArray<EnvironmentThreadShell>;
310 readonly workingCount: number;
311 readonly workingShelfHeaderIndex: number | null;
312 readonly snoozedCount: number;
313 readonly snoozedShelfHeaderIndex: number | null;
314 readonly settledCount: number;
315 readonly settledShelfHeaderIndex: number | null;
316 /** Arm a timeout here to repartition at snooze expiry rather than the next minute tick. */
317 readonly nextSnoozeWakeAt: string | null;
318 /** Threads listed only because their messages match the search. */
319 readonly contentOnlyThreadKeys: ReadonlySet<string>;
320}
321
322export interface ThreadListV2ThreadListItem {
323 readonly type: "v2-thread";
324 readonly key: string;
325 readonly item: ThreadListV2Item;
326 readonly snoozeWakeLabelText: string | undefined;
327 readonly timeLabel: string;
328 readonly snoozePresetMinute: string | undefined;
329 readonly showTrailingDivider: boolean;
330 /** Include queued state in item equality; outbox writes do not update thread shells. */
331 readonly hasQueuedMessages: boolean;
332 readonly canMoveUp: boolean;
333 readonly canMoveDown: boolean;
334}
335
336export interface ThreadListV2PendingListItem {
337 readonly type: "v2-pending";
338 readonly key: string;
339 readonly pendingTask: PendingNewTask;
340 readonly showPendingDivider: boolean;
341 readonly showTrailingDivider: boolean;
342}
343
344export interface ThreadListV2WorkingShelfListItem {
345 readonly type: "v2-working-shelf";
346 readonly key: "v2-working-shelf";
347 readonly count: number;
348 readonly expanded: boolean;
349 readonly disabled: boolean;
350}
351
352export interface ThreadListV2SnoozedShelfListItem {
353 readonly type: "v2-snoozed-shelf";
354 readonly key: "v2-snoozed-shelf";
355 readonly count: number;
356 readonly expanded: boolean;
357 /** Include disabled state in item equality; recycled cells ignore render-closure updates. */
358 readonly disabled: boolean;
359}
360
361export interface ThreadListV2SettledShelfListItem {
362 readonly type: "v2-settled-shelf";
363 readonly key: "v2-settled-shelf";
364 readonly count: number;
365 readonly expanded: boolean;
366 readonly disabled: boolean;
367}
368
369export type ThreadListV2ListItem =
370 | ThreadListV2ThreadListItem
371 | ThreadListV2PendingListItem
372 | ThreadListV2WorkingShelfListItem
373 | ThreadListV2SnoozedShelfListItem
374 | ThreadListV2SettledShelfListItem;
375
376export function isThreadListV2ListItem(value: {
377 readonly type: string;
378}): value is ThreadListV2ListItem {
379 return (
380 value.type === "v2-thread" ||
381 value.type === "v2-pending" ||
382 value.type === "v2-working-shelf" ||
383 value.type === "v2-snoozed-shelf" ||
384 value.type === "v2-settled-shelf"
385 );
386}
387
388/** Compare rebuilt items by content so minute ticks and partition runs do not re-render every mounted row. */
389export function threadListV2ListItemsAreEqual(
390 previous: ThreadListV2ListItem,
391 item: ThreadListV2ListItem,
392): boolean {
393 switch (item.type) {
394 case "v2-thread":
395 return (
396 previous.type === "v2-thread" &&
397 previous.key === item.key &&
398 previous.item.thread === item.item.thread &&
399 previous.item.variant === item.item.variant &&
400 previous.item.snoozed === item.item.snoozed &&
401 previous.item.pinned === item.item.pinned &&
402 previous.item.wokeAt === item.item.wokeAt &&
403 previous.snoozeWakeLabelText === item.snoozeWakeLabelText &&
404 previous.timeLabel === item.timeLabel &&
405 previous.snoozePresetMinute === item.snoozePresetMinute &&
406 previous.showTrailingDivider === item.showTrailingDivider &&
407 previous.hasQueuedMessages === item.hasQueuedMessages &&
408 previous.canMoveUp === item.canMoveUp &&
409 previous.canMoveDown === item.canMoveDown
410 );
411 case "v2-pending":
412 return (
413 previous.type === "v2-pending" &&
414 previous.key === item.key &&
415 previous.pendingTask === item.pendingTask &&
416 previous.showPendingDivider === item.showPendingDivider &&
417 previous.showTrailingDivider === item.showTrailingDivider
418 );
419 case "v2-working-shelf":
420 return (
421 previous.type === "v2-working-shelf" &&
422 previous.count === item.count &&
423 previous.expanded === item.expanded &&
424 previous.disabled === item.disabled
425 );
426 case "v2-snoozed-shelf":
427 return (
428 previous.type === "v2-snoozed-shelf" &&
429 previous.count === item.count &&
430 previous.expanded === item.expanded &&
431 previous.disabled === item.disabled
432 );
433 case "v2-settled-shelf":
434 return (
435 previous.type === "v2-settled-shelf" &&
436 previous.count === item.count &&
437 previous.expanded === item.expanded &&
438 previous.disabled === item.disabled
439 );
440 }
441}
442
443function resolveThreadListV2ItemTimeLabel(
444 item: ThreadListV2Item,
445 showSnoozeWakeLabel: boolean,
446): string {
447 const { thread, variant, snoozed } = item;
448 if (showSnoozeWakeLabel) return "";
449 if (
450 variant === "card" &&
451 (resolveThreadListV2Status(thread) !== "ready" ||
452 item.wokeAt !== null ||
453 threadHasUnseenCompletion(thread))
454 )
455 return "";
456 const settledTimestamp =
457 variant === "slim" && !snoozed ? resolveSettledThreadTimestamp(thread) : null;
458 return relativeTime(
459 settledTimestamp ?? thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
460 );
461}
462
463export function buildThreadListV2ListItems(input: {
464 readonly items: ReadonlyArray<ThreadListV2Item>;
465 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
466 readonly workingCount?: number;
467 readonly workingShelfExpanded?: boolean;
468 readonly workingShelfHeaderIndex?: number | null;
469 readonly snoozedCount?: number;
470 readonly snoozedShelfExpanded?: boolean;
471 readonly snoozedShelfHeaderIndex?: number | null;
472 readonly settledCount?: number;
473 readonly settledShelfExpanded?: boolean;
474 readonly settledShelfHeaderIndex?: number | null;
475 readonly snoozeLabelNow?: string;
476 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
477 readonly queuedThreadKeys?: ReadonlySet<string>;
478 readonly moveAvailability?: ReadonlyMap<string, ThreadMoveAvailability>;
479 readonly shelfPreferencesLoading?: boolean;
480}): ThreadListV2ListItem[] {
481 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
482 const threadItems = input.items.map((item): ThreadListV2ListItem => {
483 const snoozeWakeLabelText =
484 item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
485 ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
486 : undefined;
487 // Put the clock on items so recycler equality limits ticks to rows displaying snooze preset times.
488 const snoozePresetMinute =
489 !item.snoozed &&
490 input.snoozeLabelNow !== undefined &&
491 (input.snoozeEnvironmentIds?.has(item.thread.environmentId) ?? true) &&
492 canSnooze(item.thread, { now: input.snoozeLabelNow })
493 ? input.snoozeLabelNow
494 : undefined;
495 const move =
496 item.variant === "card"
497 ? input.moveAvailability?.get(`${item.thread.environmentId}:${item.thread.id}`)
498 : undefined;
499 return {
500 type: "v2-thread",
501 key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
502 item,
503 snoozeWakeLabelText,
504 timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined),
505 snoozePresetMinute,
506 showTrailingDivider: false,
507 hasQueuedMessages:
508 queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true,
509 canMoveUp: move?.canMoveUp === true,
510 canMoveDown: move?.canMoveDown === true,
511 };
512 });
513 const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({
514 type: "v2-pending",
515 key: `v2-${pendingTask.key}`,
516 pendingTask,
517 showPendingDivider: index === 0,
518 showTrailingDivider: false,
519 }));
520 const workingCount = input.workingCount ?? 0;
521 const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null;
522 const snoozedCount = input.snoozedCount ?? 0;
523 const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
524 const settledCount = input.settledCount ?? 0;
525 const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
526 const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
527 const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd;
528 const activeEnd = workingShelfHeaderIndex ?? workingEnd;
529 const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, activeEnd)];
530 const shelfDisabled = input.shelfPreferencesLoading === true;
531 if (workingShelfHeaderIndex !== null && workingCount > 0) {
532 result.push({
533 type: "v2-working-shelf",
534 key: "v2-working-shelf",
535 count: workingCount,
536 expanded: input.workingShelfExpanded === true,
537 disabled: shelfDisabled,
538 });
539 result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd));
540 }
541 if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
542 result.push({
543 type: "v2-snoozed-shelf",
544 key: "v2-snoozed-shelf",
545 count: snoozedCount,
546 expanded: input.snoozedShelfExpanded === true,
547 disabled: shelfDisabled,
548 });
549 result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
550 }
551 if (settledShelfHeaderIndex !== null && settledCount > 0) {
552 result.push({
553 type: "v2-settled-shelf",
554 key: "v2-settled-shelf",
555 count: settledCount,
556 expanded: input.settledShelfExpanded !== false,
557 disabled: shelfDisabled,
558 });
559 result.push(...threadItems.slice(settledShelfHeaderIndex));
560 }
561 return result.map((entry, index) => {
562 if (entry.type !== "v2-thread" && entry.type !== "v2-pending") return entry;
563 const next = result[index + 1];
564 const showTrailingDivider =
565 next?.type === "v2-thread" || (next?.type === "v2-pending" && !next.showPendingDivider);
566 return showTrailingDivider === entry.showTrailingDivider
567 ? entry
568 : { ...entry, showTrailingDivider };
569 });
570}
571
572// Immutable shells and field-only sorting make element-identical inputs produce identical output.
573let lastSettledInput: ReadonlyArray<EnvironmentThreadShell> = [];
574let lastSettledOutput: ReadonlyArray<EnvironmentThreadShell> = [];
575
576function sortSettledThreadsReusingLast(
577 settled: ReadonlyArray<EnvironmentThreadShell>,
578): ReadonlyArray<EnvironmentThreadShell> {
579 if (settled.length === lastSettledInput.length) {
580 let same = true;
581 for (let index = 0; index < settled.length; index += 1) {
582 if (settled[index] !== lastSettledInput[index]) {
583 same = false;
584 break;
585 }
586 }
587 if (same) return lastSettledOutput;
588 }
589 lastSettledInput = settled;
590 lastSettledOutput = sortSettledThreads(settled);
591 return lastSettledOutput;
592}
593
594export function buildThreadListV2Items(input: {
595 readonly pendingOrder?: PendingThreadOrder | null;
596 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
597 readonly environmentId: EnvironmentId | null;
598 readonly projectRefs?: ReadonlyArray<{
599 readonly environmentId: EnvironmentId;
600 readonly projectId: ProjectId;
601 }> | null;
602 readonly searchQuery: string;
603 readonly matchedThreadKeys?: ReadonlySet<string>;
604 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
605 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
606 readonly settledLimit?: number;
607 readonly now: string;
608 readonly workingShelfEnabled?: boolean;
609 readonly workingShelfExpanded?: boolean;
610 readonly isWorking?: (thread: EnvironmentThreadShell) => boolean;
611 readonly inboxReturnAt?: (thread: EnvironmentThreadShell) => number | undefined;
612 readonly snoozedShelfExpanded?: boolean;
613 readonly settledShelfExpanded?: boolean;
614 readonly selectedThreadKey?: string | null;
615 readonly queuedThreadKeys?: ReadonlySet<string>;
616 /** Whether the shelf may list a settled row yet; older settled rows load in pages. */
617 readonly isListedSettled?: (thread: EnvironmentThreadShell) => boolean;
618 /** Settled threads in scope that are not local (older settled threads not loaded). */
619 readonly unloadedSettledCount?: number;
620}): ThreadListV2Layout {
621 const now = input.now;
622 const pending =
623 input.pendingOrder == null
624 ? null
625 : reconcilePendingThreadOrder(
626 input.pendingOrder,
627 getThreadListV2OrderedSection({
628 ...input,
629 section: input.pendingOrder.section,
630 pendingOrder: null,
631 }),
632 );
633 const query = foldSearchQuery(input.searchQuery);
634 const nowMs = Date.parse(now);
635 const projectKeys = input.projectRefs
636 ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
637 : null;
638
639 const workingShelfEnabled = input.workingShelfEnabled === true;
640 const pinned: EnvironmentThreadShell[] = [];
641 const active: EnvironmentThreadShell[] = [];
642 const working: EnvironmentThreadShell[] = [];
643 const settled: EnvironmentThreadShell[] = [];
644 const snoozed: EnvironmentThreadShell[] = [];
645 let nextSnoozeWakeAt: string | null = null;
646 const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
647 const listedThreads = input.threads.filter(
648 (thread) =>
649 thread.archivedAt === null &&
650 thread.lineage.relationshipToParent !== "subagent" &&
651 (input.environmentId === null || thread.environmentId === input.environmentId) &&
652 (projectKeys === null || projectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
653 );
654 // The same matches as the command palette, typo fallback included. Only
655 // listed threads are ranked: a hidden exact match must not turn typos off.
656 const rankedMatches =
657 query.length > 0
658 ? rankSearchItems(listedThreads, (thread, options) =>
659 scoreThreadSearch(query, threadSearchSubject(thread, null), nowMs, {
660 ...options,
661 picks: false,
662 }),
663 ).map(({ item }) => item)
664 : null;
665 const matchingThreads = rankedMatches === null ? null : new Set(rankedMatches);
666 // Threads listed only because their messages match; only their rows show
667 // the message and open at it.
668 const contentOnlyThreadKeys = new Set<string>();
669 for (const thread of listedThreads) {
670 if (matchingThreads !== null && !matchingThreads.has(thread)) {
671 const key = threadSearchMatchKey({
672 environmentId: thread.environmentId,
673 threadId: thread.id,
674 });
675 if (input.matchedThreadKeys?.has(key) !== true) continue;
676 contentOnlyThreadKeys.add(key);
677 }
678 const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
679 const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
680 if (supportsSnooze && effectiveSnoozed(thread, { now })) {
681 snoozed.push(thread);
682 if (
683 thread.snoozedUntil != null &&
684 (nextSnoozeWakeAt === null ||
685 parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
686 ) {
687 nextSnoozeWakeAt = thread.snoozedUntil;
688 }
689 continue;
690 }
691 const hasQueuedMessages =
692 queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
693 if (supportsSettlement && thread.settledOverride === "settled" && !hasQueuedMessages) {
694 settled.push(thread);
695 } else if (thread.pinnedAt != null) {
696 pinned.push(thread);
697 } else if (workingShelfEnabled && (input.isWorking ?? isThreadWorking)(thread)) {
698 working.push(thread);
699 } else {
700 active.push(thread);
701 }
702 }
703
704 if (rankedMatches !== null) {
705 // Searching lists every match by rank across shelves, as the palette and
706 // the web sidebar do, then threads listed for their messages in the
707 // server's order. Each row keeps its shelf's look.
708 const slim = new Set([...snoozed, ...settled]);
709 const snoozedThreads = new Set(snoozed);
710 const pinnedThreads = new Set(pinned);
711 const threadByKey = new Map(
712 listedThreads.map((thread) => [
713 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
714 thread,
715 ]),
716 );
717 const contentOnly = [...(input.matchedThreadKeys ?? [])].flatMap((key) => {
718 const thread = contentOnlyThreadKeys.has(key) ? threadByKey.get(key) : undefined;
719 return thread ? [thread] : [];
720 });
721 const results = [...rankedMatches, ...contentOnly];
722 return {
723 items: results.map((thread, index) => ({
724 thread,
725 variant: slim.has(thread) ? "slim" : "card",
726 snoozed: snoozedThreads.has(thread),
727 pinned: pinnedThreads.has(thread),
728 wokeAt: slim.has(thread) ? null : resolveThreadListV2WokeAt(thread, { now }),
729 isLast: index === results.length - 1,
730 })),
731 hiddenSettledCount: 0,
732 listedSettledThreads: [],
733 workingCount: 0,
734 workingShelfHeaderIndex: null,
735 snoozedCount: 0,
736 snoozedShelfHeaderIndex: null,
737 settledCount: 0,
738 settledShelfHeaderIndex: null,
739 nextSnoozeWakeAt,
740 contentOnlyThreadKeys,
741 };
742 }
743
744 const orderedActive = workingShelfEnabled
745 ? sortInboxThreadsByReturn(active, input.inboxReturnAt)
746 : applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
747 const orderedWorking = sortWorkingThreadsBySend(working);
748 const orderedSnoozed = [...snoozed].sort(
749 (left, right) =>
750 parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
751 );
752 const selectedThreadKey = input.selectedThreadKey ?? null;
753 const visibleWorking =
754 input.workingShelfExpanded === true
755 ? orderedWorking
756 : orderedWorking.filter(
757 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
758 );
759 const visibleSnoozed =
760 input.snoozedShelfExpanded === true
761 ? orderedSnoozed
762 : orderedSnoozed.filter(
763 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
764 );
765 const orderedSettled = sortSettledThreadsReusingLast(settled);
766 const listedSettled =
767 input.isListedSettled === undefined
768 ? orderedSettled
769 : orderedSettled.filter(input.isListedSettled);
770 const settledTotal = orderedSettled.length + (input.unloadedSettledCount ?? 0);
771 const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
772 const limitedSettled =
773 listedSettled.length > settledLimit ? listedSettled.slice(0, settledLimit) : listedSettled;
774 const selectedSettled =
775 selectedThreadKey === null ||
776 limitedSettled.some((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey)
777 ? undefined
778 : orderedSettled.find(
779 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
780 );
781 const pagedSettled =
782 selectedSettled === undefined ? limitedSettled : [...limitedSettled, selectedSettled];
783 const visibleSettled =
784 input.settledShelfExpanded !== false
785 ? pagedSettled
786 : pagedSettled.filter(
787 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
788 );
789
790 const items: ThreadListV2Item[] = [];
791 for (const thread of applyPendingThreadOrder(
792 sortPinnedThreadsByOrderKey(pinned),
793 "pinned",
794 pending,
795 )) {
796 items.push({
797 thread,
798 variant: "card",
799 snoozed: false,
800 pinned: true,
801 wokeAt: resolveThreadListV2WokeAt(thread, { now }),
802 isLast: false,
803 });
804 }
805 for (const thread of orderedActive) {
806 items.push({
807 thread,
808 variant: "card",
809 snoozed: false,
810 pinned: false,
811 wokeAt: resolveThreadListV2WokeAt(thread, { now }),
812 isLast: false,
813 });
814 }
815 const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null;
816 for (const thread of visibleWorking) {
817 items.push({
818 thread,
819 variant: "card",
820 snoozed: false,
821 pinned: false,
822 wokeAt: resolveThreadListV2WokeAt(thread, { now }),
823 isLast: false,
824 });
825 }
826 const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
827 for (const thread of visibleSnoozed) {
828 items.push({
829 thread,
830 variant: "slim",
831 snoozed: true,
832 pinned: false,
833 wokeAt: null,
834 isLast: false,
835 });
836 }
837 const settledShelfHeaderIndex = settledTotal > 0 ? items.length : null;
838 for (const thread of visibleSettled) {
839 items.push({
840 thread,
841 variant: "slim",
842 snoozed: false,
843 pinned: false,
844 wokeAt: null,
845 isLast: false,
846 });
847 }
848 const last = items.at(-1);
849 if (last) {
850 items[items.length - 1] = { ...last, isLast: true };
851 }
852 return {
853 items,
854 hiddenSettledCount: Math.max(0, settledTotal - pagedSettled.length),
855 listedSettledThreads: listedSettled,
856 workingCount: orderedWorking.length,
857 workingShelfHeaderIndex,
858 snoozedCount: orderedSnoozed.length,
859 snoozedShelfHeaderIndex,
860 settledCount: settledTotal,
861 settledShelfHeaderIndex,
862 nextSnoozeWakeAt,
863 contentOnlyThreadKeys,
864 };
865}