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

threadListV2.ts

822 lines28.9 KB

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