@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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