Open History to see the last commit
1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import {
3 effectiveSnoozed,
4 hasQueuedTurnStart,
5 QUEUED_TURN_START_GRACE_MS,
6 resolveSnoozePresets,
7 snoozeWakeLabel,
8} from "@t3tools/client-runtime/state/thread-settled";
9import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
10import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
11import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
12import {
13 sortActiveThreadsByOrderKey,
14 resolveSettledThreadTimestamp,
15 sortPinnedThreadsByOrderKey,
16} from "@t3tools/client-runtime/state/thread-sort";
17import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
18
19import type { PendingNewTask } from "../../state/use-pending-new-tasks";
20
21import {
22 applyPendingThreadOrder,
23 reconcilePendingThreadOrder,
24 type PendingThreadOrder,
25} from "./threadOrder";
26
27export { snoozeWakeLabel };
28
29/**
30 * Thread List v2 model, ported from the web sidebar v2
31 * (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
32 *
33 * Four visual states, three colors: color is reserved for "act now"
34 * (approval), "in motion" (working), and "broken" (failed). Ready is the
35 * unlabeled resting state.
36 */
37export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
38export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
39
40export function resolveThreadListV2SnoozeMenuSelection(input: {
41 readonly event: string;
42 readonly displayedPresets: ReadonlyArray<SnoozePreset>;
43 readonly now: Date;
44}):
45 | { readonly _tag: "selected"; readonly preset: SnoozePreset }
46 | { readonly _tag: "expired" }
47 | { readonly _tag: "not-snooze" } {
48 if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" };
49
50 const currentPreset = resolveSnoozePresets(input.now).find(
51 (candidate) => input.event === `snooze:${candidate.id}`,
52 );
53 if (currentPreset) return { _tag: "selected", preset: currentPreset };
54
55 const displayedPreset = input.displayedPresets.find(
56 (candidate) => input.event === `snooze:${candidate.id}`,
57 );
58 if (displayedPreset && Date.parse(displayedPreset.snoozedUntil) > input.now.getTime()) {
59 return { _tag: "selected", preset: displayedPreset };
60 }
61 return { _tag: "expired" };
62}
63
64export function resolveThreadListV2SwipeActions(input: {
65 readonly variant: "card" | "slim";
66 readonly settlementSupported: boolean;
67 readonly snoozeSupported: boolean;
68 readonly snoozable: boolean;
69 /** Row is on the snoozed shelf. */
70 readonly snoozed?: boolean;
71}): {
72 readonly primary: Exclude<ThreadListV2SwipeAction, "snooze">;
73 readonly secondary: "snooze" | null;
74} {
75 if (input.snoozed === true) {
76 return { primary: "unsnooze", secondary: null };
77 }
78 const primary = input.settlementSupported
79 ? input.variant === "slim"
80 ? "unsettle"
81 : "settle"
82 : "archive";
83 return {
84 primary,
85 secondary: input.snoozeSupported && input.snoozable ? "snooze" : null,
86 };
87}
88
89/**
90 * The point at which a queued-turn snooze guard expires on its own. Rows arm
91 * a one-shot timer for this boundary so Snooze appears without waiting for an
92 * unrelated render. User-blocked threads return null because only fresh
93 * server data can make them snoozable.
94 */
95export function resolveThreadListV2SnoozeGateExpiryMs(
96 thread: Pick<
97 EnvironmentThreadShell,
98 "hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
99 >,
100 options: { readonly now: string },
101): number | null {
102 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
103 if (!hasQueuedTurnStart(thread, options)) return null;
104 const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
105 if (Number.isNaN(messageAtMs)) return null;
106 return messageAtMs + QUEUED_TURN_START_GRACE_MS;
107}
108
109// Settled-tail paging: recent history is the common lookup; the deep tail
110// stays behind an explicit Show more. Shared by the compact Home list and
111// the iPad sidebar so both page identically.
112export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
113export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
114
115/**
116 * The flat Thread List v2 is the default on every app variant; the Settings →
117 * Legacy toggle opts a device back into the grouped legacy list. Preferences
118 * persist as sparse patches, so `undefined` genuinely means "never chosen".
119 *
120 * `preferencesLoaded` guards the startup window: preferences load
121 * asynchronously, and rendering one list before the stored choice arrives would
122 * remount the whole thing a tick later. While loading, hold the default — that
123 * is where every device without an explicit legacy opt-in lands anyway.
124 */
125export function resolveThreadListV2Enabled(input: {
126 readonly legacyPreference: boolean | undefined;
127 readonly preferencesLoaded: boolean;
128}): boolean {
129 if (!input.preferencesLoaded) {
130 return true;
131 }
132 return input.legacyPreference !== true;
133}
134
135export function resolveThreadListV2Status(
136 thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
137): ThreadListV2Status {
138 if (thread.hasPendingApprovals) {
139 return "approval";
140 }
141 if (thread.hasPendingUserInput) {
142 return "input";
143 }
144 if (thread.session?.status === "running" || thread.session?.status === "starting") {
145 return "working";
146 }
147 if (thread.session?.status === "error") {
148 return "failed";
149 }
150 return "ready";
151}
152
153/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
154 poison the whole ordering, so it sinks to the epoch instead. */
155function parseTimestampMs(isoDate: string): number {
156 const parsed = Date.parse(isoDate);
157 return Number.isNaN(parsed) ? 0 : parsed;
158}
159
160/** The active order shared by web and native: new/reopened rows, then the
161 saved arrangement. Activity does not move a thread. */
162export function sortThreadsForListV2<
163 T extends {
164 readonly id: string;
165 readonly createdAt: string;
166 readonly unsettledAt?: string | null | undefined;
167 readonly activeOrderKey?: string | null | undefined;
168 readonly environmentId?: string | undefined;
169 },
170>(threads: readonly T[]): T[] {
171 return sortActiveThreadsByOrderKey(threads);
172}
173
174/** Canonical card section for Move up/down, independent of search or scope. */
175export function getThreadListV2OrderedSection(input: {
176 readonly threads: readonly EnvironmentThreadShell[];
177 readonly section: "pinned" | "active";
178 readonly pendingOrder?: PendingThreadOrder | null;
179 readonly now: string;
180 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
181 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
182 readonly queuedThreadKeys?: ReadonlySet<string>;
183}): EnvironmentThreadShell[] {
184 const threads = input.threads.filter((thread) => {
185 if (thread.archivedAt !== null) return false;
186 if (
187 (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
188 thread.settledOverride === "settled" &&
189 input.queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) !== true
190 ) {
191 return false;
192 }
193 if (
194 (input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true) &&
195 effectiveSnoozed(thread, { now: input.now })
196 ) {
197 return false;
198 }
199 return (thread.pinnedAt != null) === (input.section === "pinned");
200 });
201 const ordered =
202 input.section === "pinned"
203 ? sortPinnedThreadsByOrderKey(threads)
204 : sortActiveThreadsByOrderKey(threads);
205 const pending =
206 input.pendingOrder?.section === input.section
207 ? reconcilePendingThreadOrder(input.pendingOrder, ordered)
208 : null;
209 return applyPendingThreadOrder(ordered, input.section, pending);
210}
211
212export interface ThreadListV2Item {
213 readonly thread: EnvironmentThreadShell;
214 readonly variant: "card" | "slim";
215 /** Snoozed-shelf row: shows the wake countdown and offers Wake. */
216 readonly snoozed: boolean;
217 /** Pinned-block row: renders the pin glyph and offers Unpin. */
218 readonly pinned: boolean;
219 readonly isLast: boolean;
220}
221
222export interface ThreadListV2Layout {
223 readonly items: ThreadListV2Item[];
224 /** Settled threads beyond the render limit (behind "Show more"). */
225 readonly hiddenSettledCount: number;
226 /** Snoozed threads matching the current filters. */
227 readonly snoozedCount: number;
228 /** Index in `items` where the Snoozed shelf header belongs. The header is
229 still rendered when the shelf is collapsed and no snoozed rows exist. */
230 readonly snoozedShelfHeaderIndex: number | null;
231 /** Total settled threads in scope, including rows hidden by collapse/paging. */
232 readonly settledCount: number;
233 /** Index in `items` where the Settled shelf header belongs. */
234 readonly settledShelfHeaderIndex: number | null;
235 /** Soonest wake time among snoozed threads, or null. Callers arm
236 a timeout at this boundary so the list re-partitions the moment a
237 snooze expires instead of on the next minute tick. */
238 readonly nextSnoozeWakeAt: string | null;
239}
240
241export interface ThreadListV2ThreadListItem {
242 readonly type: "v2-thread";
243 readonly key: string;
244 readonly item: ThreadListV2Item;
245 /** Precomputed so recycled-list equality can see a minute-tick change. */
246 readonly snoozeWakeLabelText: string | undefined;
247}
248
249export interface ThreadListV2PendingListItem {
250 readonly type: "v2-pending";
251 readonly key: string;
252 readonly pendingTask: PendingNewTask;
253 /** First queued row after the active block draws the PENDING divider. */
254 readonly showPendingDivider: boolean;
255}
256
257export interface ThreadListV2SnoozedShelfListItem {
258 readonly type: "v2-snoozed-shelf";
259 readonly key: "v2-snoozed-shelf";
260 readonly count: number;
261 readonly expanded: boolean;
262}
263
264export interface ThreadListV2SettledShelfListItem {
265 readonly type: "v2-settled-shelf";
266 readonly key: "v2-settled-shelf";
267 readonly count: number;
268 readonly expanded: boolean;
269}
270
271export type ThreadListV2ListItem =
272 | ThreadListV2ThreadListItem
273 | ThreadListV2PendingListItem
274 | ThreadListV2SnoozedShelfListItem
275 | ThreadListV2SettledShelfListItem;
276
277/**
278 * Builds the shared mobile order: active → pending → snoozed shelf → settled.
279 * Pending tasks are waiting rather than asking, and parked work remains
280 * reachable without competing with either the inbox or settled history.
281 */
282export function buildThreadListV2ListItems(input: {
283 readonly items: ReadonlyArray<ThreadListV2Item>;
284 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
285 readonly snoozedCount?: number;
286 readonly snoozedShelfExpanded?: boolean;
287 readonly snoozedShelfHeaderIndex?: number | null;
288 readonly settledCount?: number;
289 readonly settledShelfExpanded?: boolean;
290 readonly settledShelfHeaderIndex?: number | null;
291 readonly snoozeLabelNow?: string;
292}): ThreadListV2ListItem[] {
293 const threadItems = input.items.map((item): ThreadListV2ListItem => ({
294 type: "v2-thread",
295 key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`,
296 item,
297 snoozeWakeLabelText:
298 item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined
299 ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow })
300 : undefined,
301 }));
302 const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({
303 type: "v2-pending",
304 key: `v2-${pendingTask.key}`,
305 pendingTask,
306 showPendingDivider: index === 0,
307 }));
308 const snoozedCount = input.snoozedCount ?? 0;
309 const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
310 const settledCount = input.settledCount ?? 0;
311 const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
312 const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length;
313 const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
314 const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems];
315 if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
316 result.push({
317 type: "v2-snoozed-shelf",
318 key: "v2-snoozed-shelf",
319 count: snoozedCount,
320 expanded: input.snoozedShelfExpanded === true,
321 });
322 result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd));
323 }
324 if (settledShelfHeaderIndex !== null && settledCount > 0) {
325 result.push({
326 type: "v2-settled-shelf",
327 key: "v2-settled-shelf",
328 count: settledCount,
329 expanded: input.settledShelfExpanded !== false,
330 });
331 result.push(...threadItems.slice(settledShelfHeaderIndex));
332 }
333 return result;
334}
335
336/**
337 * Partitions visible threads into the active card block (saved order) and
338 * the settled recency tail, matching the web v2 list.
339 */
340export function buildThreadListV2Items(input: {
341 readonly pendingOrder?: PendingThreadOrder | null;
342 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
343 readonly environmentId: EnvironmentId | null;
344 readonly projectRefs?: ReadonlyArray<{
345 readonly environmentId: EnvironmentId;
346 readonly projectId: ProjectId;
347 }> | null;
348 readonly searchQuery: string;
349 readonly matchedThreadKeys?: ReadonlySet<string>;
350 /** Environments whose server supports thread.settle/unsettle. Threads on
351 other environments never classify as settled — the user could neither
352 un-settle nor pin them. Absent = no gating (tests). */
353 readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
354 /** Environments whose server supports thread.snooze/unsnooze. Same
355 contract as settlementEnvironmentIds. */
356 readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
357 /** Max settled rows to render; the rest are counted, not built. */
358 readonly settledLimit?: number;
359 /** Second-precise clock used for time-based classification. */
360 readonly now: string;
361 /** Expands the snoozed shelf into rows. Collapsed is the default. */
362 readonly snoozedShelfExpanded?: boolean;
363 /** Expands the settled shelf into rows. Expanded is the default. */
364 readonly settledShelfExpanded?: boolean;
365 /** The selected thread remains visible on an otherwise collapsed shelf so
366 a split-view detail can never lose its navigation row. */
367 readonly selectedThreadKey?: string | null;
368 /** Thread keys (`environmentId:threadId`) with a message waiting in the
369 outbox. Such a thread has work the user is waiting on, so it stays in
370 the active block even when the server has settled it. */
371 readonly queuedThreadKeys?: ReadonlySet<string>;
372}): ThreadListV2Layout {
373 const now = input.now;
374 const pending =
375 input.pendingOrder == null
376 ? null
377 : reconcilePendingThreadOrder(
378 input.pendingOrder,
379 getThreadListV2OrderedSection({
380 ...input,
381 section: input.pendingOrder.section,
382 pendingOrder: null,
383 }),
384 );
385 const query = input.searchQuery.trim().toLocaleLowerCase();
386 const projectKeys = input.projectRefs
387 ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
388 : null;
389
390 const pinned: EnvironmentThreadShell[] = [];
391 const active: EnvironmentThreadShell[] = [];
392 const settled: EnvironmentThreadShell[] = [];
393 const snoozed: EnvironmentThreadShell[] = [];
394 let nextSnoozeWakeAt: string | null = null;
395 for (const thread of input.threads) {
396 // Callers pass live shells. The server stamps settledOverride for the tail.
397 if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
398 if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
399 continue;
400 }
401 if (
402 query.length > 0 &&
403 !thread.title.toLocaleLowerCase().includes(query) &&
404 !threadPullRequestSearchTerms(thread).some((term) =>
405 term.toLocaleLowerCase().includes(query),
406 ) &&
407 input.matchedThreadKeys?.has(
408 threadSearchMatchKey({
409 environmentId: thread.environmentId,
410 threadId: thread.id,
411 }),
412 ) !== true
413 ) {
414 continue;
415 }
416 const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
417 const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
418 // Snooze outranks settlement and pinning until the thread wakes.
419 if (supportsSnooze && effectiveSnoozed(thread, { now })) {
420 snoozed.push(thread);
421 if (
422 thread.snoozedUntil != null &&
423 (nextSnoozeWakeAt === null ||
424 parseTimestampMs(thread.snoozedUntil) < parseTimestampMs(nextSnoozeWakeAt))
425 ) {
426 nextSnoozeWakeAt = thread.snoozedUntil;
427 }
428 continue;
429 }
430 const hasQueuedMessages =
431 input.queuedThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
432 if (supportsSettlement && thread.settledOverride === "settled" && !hasQueuedMessages) {
433 settled.push(thread);
434 } else if (thread.pinnedAt != null) {
435 pinned.push(thread);
436 } else {
437 active.push(thread);
438 }
439 }
440
441 const orderedActive = applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
442 const orderedSnoozed = [...snoozed].sort(
443 (left, right) =>
444 parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
445 );
446 const selectedThreadKey = input.selectedThreadKey ?? null;
447 const visibleSnoozed =
448 input.snoozedShelfExpanded === true
449 ? orderedSnoozed
450 : orderedSnoozed.filter(
451 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
452 );
453 const orderedSettled = [...settled].sort(
454 (left, right) =>
455 parseTimestampMs(resolveSettledThreadTimestamp(right) ?? "") -
456 parseTimestampMs(resolveSettledThreadTimestamp(left) ?? ""),
457 );
458 const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
459 const pagedSettled =
460 orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
461 const selectedSettled = orderedSettled
462 .slice(pagedSettled.length)
463 .find((thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey);
464 if (selectedSettled !== undefined) pagedSettled.push(selectedSettled);
465 const visibleSettled =
466 input.settledShelfExpanded !== false
467 ? pagedSettled
468 : pagedSettled.filter(
469 (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
470 );
471
472 const items: ThreadListV2Item[] = [];
473 for (const thread of applyPendingThreadOrder(
474 sortPinnedThreadsByOrderKey(pinned),
475 "pinned",
476 pending,
477 )) {
478 items.push({
479 thread,
480 variant: "card",
481 snoozed: false,
482 pinned: true,
483 isLast: false,
484 });
485 }
486 for (const thread of orderedActive) {
487 items.push({
488 thread,
489 variant: "card",
490 snoozed: false,
491 pinned: false,
492 isLast: false,
493 });
494 }
495 const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
496 for (const thread of visibleSnoozed) {
497 items.push({
498 thread,
499 variant: "slim",
500 snoozed: true,
501 pinned: false,
502 isLast: false,
503 });
504 }
505 const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null;
506 for (const thread of visibleSettled) {
507 items.push({
508 thread,
509 variant: "slim",
510 snoozed: false,
511 pinned: false,
512 isLast: false,
513 });
514 }
515 const last = items.at(-1);
516 if (last) {
517 items[items.length - 1] = { ...last, isLast: true };
518 }
519 return {
520 items,
521 hiddenSettledCount: orderedSettled.length - pagedSettled.length,
522 snoozedCount: orderedSnoozed.length,
523 snoozedShelfHeaderIndex,
524 settledCount: orderedSettled.length,
525 settledShelfHeaderIndex,
526 nextSnoozeWakeAt,
527 };
528}