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

threadSort.ts

379 lines14.7 KB

1import type { OrchestrationThreadShell, ProjectId } from "@t3tools/contracts";
2import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3​
4export interface ThreadSortInput {
5 readonly createdAt: string;
6 readonly updatedAt: string;
7 readonly latestUserMessageAt?: string | null;
8 readonly messages?: ReadonlyArray<{
9 readonly createdAt: string;
10 readonly role: string;
11 }>;
13​
14export function toSortableTimestamp(iso: string | undefined): number | null {
15 if (!iso) return null;
16 const ms = Date.parse(iso);
17 return Number.isFinite(ms) ? ms : null;
19​
20export type SettledThreadTimestampInput = Pick<
21 OrchestrationThreadShell,
22 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
23>;
24​
25/** The timestamp a settled row sorts and labels by on every client: settledAt
26 when stamped, otherwise the latest message or turn stamp, then updatedAt. */
27export function resolveSettledThreadTimestamp(thread: SettledThreadTimestampInput): string | null {
28 if (thread.settledAt != null && toSortableTimestamp(thread.settledAt) !== null) {
29 return thread.settledAt;
30 }
31​
32 let latest: string | null = null;
33 let latestMs = Number.NEGATIVE_INFINITY;
34 for (const candidate of [
35 thread.latestUserMessageAt,
36 thread.latestTurn?.requestedAt,
37 thread.latestTurn?.startedAt,
38 thread.latestTurn?.completedAt,
39 ]) {
40 const parsed = toSortableTimestamp(candidate ?? undefined);
41 if (candidate != null && parsed !== null && parsed > latestMs) {
42 latest = candidate;
43 latestMs = parsed;
44 }
45 }
46 if (latest !== null) return latest;
47 return toSortableTimestamp(thread.updatedAt) === null ? null : thread.updatedAt;
49​
50function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
51 for (const value of values) {
52 const timestamp = toSortableTimestamp(value ?? undefined);
53 if (timestamp !== null) {
54 return timestamp;
55 }
56 }
57​
58 return null;
60​
61function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
62 if (thread.latestUserMessageAt) {
63 const latestUserMessageTimestamp = toSortableTimestamp(thread.latestUserMessageAt);
64 if (latestUserMessageTimestamp !== null) {
65 return latestUserMessageTimestamp;
66 }
67 }
68​
69 let latestUserMessageTimestamp: number | null = null;
70​
71 for (const message of thread.messages ?? []) {
72 if (message.role !== "user") continue;
73 const messageTimestamp = toSortableTimestamp(message.createdAt);
74 if (messageTimestamp === null) continue;
75 latestUserMessageTimestamp =
76 latestUserMessageTimestamp === null
77 ? messageTimestamp
78 : Math.max(latestUserMessageTimestamp, messageTimestamp);
79 }
80​
81 if (latestUserMessageTimestamp !== null) {
82 return latestUserMessageTimestamp;
83 }
84​
85 return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
87​
88export function getThreadSortTimestamp(
89 thread: ThreadSortInput,
90 sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
91): number {
92 if (sortOrder === "created_at") {
93 return (
94 getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
95 );
96 }
97 return getLatestUserMessageTimestamp(thread);
99​
100/**
101 * Sort anchor for the active thread list: creation time, re-anchored to
102 * unsettledAt when the thread last re-entered the active list (an explicit
103 * un-settle, or a settled thread waking on activity). The list stays static
104 * between lifecycle transitions, but an un-settled thread surfaces at the
105 * top instead of sinking back to its creation-order slot. Shared by web and
106 * mobile so both render the same order. Malformed timestamps sink to 0.
107 */
108function activeThreadAnchorTimestampMs(thread: {
109 readonly createdAt: string;
110 readonly unsettledAt?: string | null | undefined;
111}): number {
112 return Math.max(
113 toSortableTimestamp(thread.createdAt) ?? 0,
114 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
115 );
117​
118export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
119 threads: readonly T[],
120 sortOrder: SidebarThreadSortOrder,
121): T[] {
122 if (threads.length < 2) return [...threads];
123 return threads
124 .map((thread) => ({ thread, timestamp: getThreadSortTimestamp(thread, sortOrder) }))
125 .sort(
126 (left, right) =>
127 right.timestamp - left.timestamp ||
128 (left.thread.id < right.thread.id ? 1 : left.thread.id > right.thread.id ? -1 : 0),
129 )
130 .map(({ thread }) => thread);
132​
133export function getLatestThreadForProject<
134 T extends {
135 readonly id: string;
136 readonly projectId: ProjectId;
137 readonly archivedAt: string | null;
138 } & ThreadSortInput,
139>(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
140 let latest: T | null = null;
141 let latestTimestamp = Number.NEGATIVE_INFINITY;
142 for (const thread of threads) {
143 if (thread.projectId !== projectId || thread.archivedAt !== null) continue;
144 const timestamp = getThreadSortTimestamp(thread, sortOrder);
145 if (
146 latest === null ||
147 timestamp > latestTimestamp ||
148 (timestamp === latestTimestamp && thread.id > latest.id)
149 ) {
150 latest = thread;
151 latestTimestamp = timestamp;
152 }
153 }
154 return latest;
156​
157// ── Pinned reorder: fractional index keys ──────────────────────────────
158// Pinned threads carry an optional pinOrderKey (a base-26 string). The
159// pinned block sorts keyed threads by plain string comparison, so a drag
160// (web) or Move up/down (mobile) writes ONE key to ONE thread on that
161// thread's own server — neighbors, possibly living on other servers, are
162// never touched, and every client connected to the same servers converges
163// on the same order.
164const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz";
165​
166function isValidPinOrderKey(key: string): boolean {
167 if (key.length === 0) return false;
168 for (const char of key) {
169 if (!PIN_ORDER_DIGITS.includes(char)) return false;
170 }
171 // A trailing minimum digit would leave no room to sort a key immediately
172 // before this one; generators never produce it, so treat it as corrupt.
173 return key.at(-1) !== PIN_ORDER_DIGITS[0];
175​
176/** Midpoint of two digit strings interpreted as fractions in (0, 1).
177 "" stands for the open bound on either side. Requires a < b. */
178function pinOrderMidpoint(a: string, b: string): string {
179 if (b !== "" && a >= b) throw new Error("pinOrderMidpoint: bounds out of order");
180 if (b !== "") {
181 // Recurse past the longest common prefix ("a" pads the shorter side).
182 let n = 0;
183 while ((a.charAt(n) || PIN_ORDER_DIGITS[0]) === b.charAt(n)) n += 1;
184 if (n > 0) return b.slice(0, n) + pinOrderMidpoint(a.slice(n), b.slice(n));
185 }
186 const digitA = a === "" ? 0 : PIN_ORDER_DIGITS.indexOf(a.charAt(0));
187 const digitB = b === "" ? PIN_ORDER_DIGITS.length : PIN_ORDER_DIGITS.indexOf(b.charAt(0));
188 if (digitB - digitA > 1) {
189 return PIN_ORDER_DIGITS.charAt(Math.round((digitA + digitB) / 2));
190 }
191 // Consecutive leading digits: either b has spare digits to shorten into,
192 // or we extend a (never producing a trailing minimum digit — the base
193 // case midpoint("", "") is the middle of the alphabet).
194 if (b.length > 1) return b.charAt(0);
195 return PIN_ORDER_DIGITS.charAt(digitA) + pinOrderMidpoint(a.slice(1), "");
197​
198/** Key that sorts strictly between two neighbors; null bounds mean "top of
199 the pinned block" / "bottom of the keyed run". Returns null instead of
200 throwing when existing keys are corrupt or out of order — callers fall
201 back to rewriting the section. */
202export function pinOrderKeyBetween(before: string | null, after: string | null): string | null {
203 const a = before ?? "";
204 const b = after ?? "";
205 if (a !== "" && !isValidPinOrderKey(a)) return null;
206 if (b !== "" && !isValidPinOrderKey(b)) return null;
207 if (b !== "" && a >= b) return null;
208 return pinOrderMidpoint(a, b);
210​
211/** Evenly spaced keys for materializing an order. Wider keys keep a large
212 active list from exhausting the space between two-digit keys. */
213export function generateSpreadPinOrderKeys(count: number): string[] {
214 let width = 2;
215 let space = PIN_ORDER_DIGITS.length ** width;
216 while (space <= (count + 1) * 2) {
217 width += 1;
218 space *= PIN_ORDER_DIGITS.length;
219 }
220 const step = space / (count + 1);
221 const keys: string[] = [];
222 for (let i = 0; i < count; i += 1) {
223 let value = Math.round(step * (i + 1));
224 // Skip values whose low digit is the minimum (a trailing "a" key).
225 if (value % PIN_ORDER_DIGITS.length === 0) value += 1;
226 let key = "";
227 for (let digit = 0; digit < width; digit += 1) {
228 key = PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length) + key;
229 value = Math.floor(value / PIN_ORDER_DIGITS.length);
230 }
231 keys.push(key);
232 }
233 return keys;
235​
236/**
237 * Assignments needed to realize a new pinned order. When the moved thread
238 * sits between two keyed (or absent) neighbors, this is a single write to
239 * the moved thread. When a neighbor is keyless (threads pinned before
240 * reordering shipped), the whole section gets fresh spread keys — a
241 * one-time materialization; every move after that is single-write. Active
242 * reordering uses the same planner with activeOrderKey values.
243 */
244export function planPinnedReorder(input: {
245 /** Thread ids in the desired visual order (after the move). */
246 readonly orderedIds: readonly string[];
247 /** Include retained keys from hidden rows; only orderedIds receive writes. */
248 readonly keysById: ReadonlyMap<string, string | null | undefined>;
249 readonly movedId: string;
250}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> {
251 const { orderedIds, keysById, movedId } = input;
252 const visibleIds = new Set(orderedIds);
253 const reservedKeys = new Set(
254 [...keysById].flatMap(([id, key]) => (!visibleIds.has(id) && key != null ? [key] : [])),
255 );
256 const movedIndex = orderedIds.indexOf(movedId);
257 if (movedIndex === -1) return [];
258 const beforeId = movedIndex > 0 ? orderedIds[movedIndex - 1] : null;
259 const afterId = movedIndex < orderedIds.length - 1 ? orderedIds[movedIndex + 1] : null;
260 const beforeKey = beforeId != null ? (keysById.get(beforeId) ?? null) : null;
261 const afterKey = afterId != null ? (keysById.get(afterId) ?? null) : null;
262 const beforeUsable = beforeId === null || beforeKey != null;
263 const afterUsable = afterId === null || afterKey != null;
264 if (beforeUsable && afterUsable) {
265 let key = pinOrderKeyBetween(beforeKey, afterKey);
266 while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);
267 if (key !== null) return [{ id: movedId, orderKey: key }];
268 }
269 // Keyless neighbor (or corrupt keys): rewrite the section in the new order.
270 const keys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)
271 .filter((key) => !reservedKeys.has(key))
272 .slice(0, orderedIds.length);
273 return orderedIds.flatMap((id, index) => {
274 const key = keys[index]!;
275 return keysById.get(id) === key ? [] : [{ id, orderKey: key }];
276 });
278​
279/**
280 * Pinned block order: user-arranged keys first (string comparison, id
281 * tiebreak), then keyless threads newest-created first — so threads on
282 * servers that predate reordering keep the static creation order at the
283 * bottom of the block instead of breaking the section.
284 */
285export function sortPinnedThreadsByOrderKey<
286 T extends {
287 readonly id: string;
288 readonly createdAt: string;
289 readonly pinOrderKey?: string | null | undefined;
290 /** Thread ids are only unique within an environment, and the pinned
291 block merges environments — the tiebreak needs both parts or two
292 clients could render equal-key threads in stream-arrival order. */
293 readonly environmentId?: string | undefined;
294 },
295>(threads: readonly T[]): T[] {
296 if (threads.length < 2) return [...threads];
297 const keyed: T[] = [];
298 const keyless: T[] = [];
299 for (const thread of threads) {
300 (thread.pinOrderKey != null ? keyed : keyless).push(thread);
301 }
302 const identityTiebreak = (left: T, right: T) =>
303 left.id.localeCompare(right.id) ||
304 (left.environmentId ?? "").localeCompare(right.environmentId ?? "");
305 keyed.sort((left, right) => {
306 const leftKey = left.pinOrderKey!;
307 const rightKey = right.pinOrderKey!;
308 return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : identityTiebreak(left, right);
309 });
310 const timestamps = new Map(
311 keyless.map((thread) => [thread, toSortableTimestamp(thread.createdAt) ?? 0]),
312 );
313 keyless.sort(
314 (left, right) =>
315 timestamps.get(right)! - timestamps.get(left)! || identityTiebreak(left, right),
316 );
317 return [...keyed, ...keyless];
319​
320/** New and reopened threads lead the active list. Arranged threads follow
321 their saved keys; activity leaves both groups in place. */
322export function sortActiveThreadsByOrderKey<
323 T extends {
324 readonly id: string;
325 readonly createdAt: string;
326 readonly unsettledAt?: string | null | undefined;
327 readonly activeOrderKey?: string | null | undefined;
328 readonly environmentId?: string | undefined;
329 },
330>(threads: readonly T[]): T[] {
331 if (threads.length < 2) return [...threads];
332 const timestamps = new Map<T, number>();
333 for (const thread of threads) {
334 if (thread.activeOrderKey == null) {
335 timestamps.set(thread, activeThreadAnchorTimestampMs(thread));
336 }
337 }
338 return [...threads].sort((left, right) => {
339 const leftKey = left.activeOrderKey;
340 const rightKey = right.activeOrderKey;
341 if (leftKey == null && rightKey != null) return -1;
342 if (leftKey != null && rightKey == null) return 1;
343 let order = 0;
344 if (leftKey != null && rightKey != null) {
345 order = leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
346 } else {
347 order = timestamps.get(right)! - timestamps.get(left)!;
348 }
349 return (
350 order ||
351 left.id.localeCompare(right.id) ||
352 (left.environmentId ?? "").localeCompare(right.environmentId ?? "")
353 );
354 });
356​
357/**
358 * planPinnedReorder specialized for mobile's Move up / Move down menu
359 * actions: swap the moved thread with its displayed neighbor. Null when the
360 * move falls off either end of the list. Same single-write-per-move
361 * semantics as a web drag.
362 */
363export function planPinnedMove(input: {
364 /** Reorder-capable pinned thread ids in displayed order. */
365 readonly orderedIds: readonly string[];
366 readonly keysById: ReadonlyMap<string, string | null | undefined>;
367 readonly movedId: string;
368 readonly direction: "up" | "down";
369}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> | null {
370 const { orderedIds, keysById, movedId, direction } = input;
371 const from = orderedIds.indexOf(movedId);
372 if (from === -1) return null;
373 const to = direction === "up" ? from - 1 : from + 1;
374 if (to < 0 || to >= orderedIds.length) return null;
375 const newOrder = [...orderedIds];
376 newOrder.splice(from, 1);
377 newOrder.splice(to, 0, movedId);
378 return planPinnedReorder({ orderedIds: newOrder, keysById, movedId });