Open History to see the last commit
1import type { ProjectId } from "@t3tools/contracts";
2import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3import type { EnvironmentThreadShell } from "./models.ts";
4
5export interface ThreadSortInput {
6 readonly createdAt: string;
7 readonly updatedAt: string;
8 readonly latestUserMessageAt?: string | null;
9 readonly messages?: ReadonlyArray<{
10 readonly createdAt: string;
11 readonly role: string;
12 }>;
13}
14
15export function toSortableTimestamp(iso: string | undefined): number | null {
16 if (!iso) return null;
17 const ms = Date.parse(iso);
18 return Number.isFinite(ms) ? ms : null;
19}
20
21export type SettledThreadTimestampInput = Pick<
22 EnvironmentThreadShell,
23 "settledAt" | "latestUserMessageAt" | "latestRun" | "updatedAt"
24>;
25
26export function resolveSettledThreadTimestamp(thread: SettledThreadTimestampInput): string | null {
27 if (thread.settledAt != null && toSortableTimestamp(thread.settledAt) !== null) {
28 return thread.settledAt;
29 }
30
31 let latest: string | null = null;
32 let latestMs = Number.NEGATIVE_INFINITY;
33 for (const candidate of [
34 thread.latestUserMessageAt,
35 thread.latestRun?.requestedAt,
36 thread.latestRun?.startedAt,
37 thread.latestRun?.completedAt,
38 ]) {
39 const parsed = toSortableTimestamp(candidate ?? undefined);
40 if (candidate != null && parsed !== null && parsed > latestMs) {
41 latest = candidate;
42 latestMs = parsed;
43 }
44 }
45 if (latest !== null) return latest;
46 return toSortableTimestamp(thread.updatedAt) === null ? null : thread.updatedAt;
47}
48
49export function sortSettledThreads<T extends SettledThreadTimestampInput & { readonly id: string }>(
50 threads: readonly T[],
51): T[] {
52 return threads
53 .map((thread) => {
54 const timestamp = resolveSettledThreadTimestamp(thread);
55 return { thread, timestampMs: timestamp === null ? 0 : Date.parse(timestamp) };
56 })
57 .sort(
58 (left, right) =>
59 right.timestampMs - left.timestampMs ||
60 // Plain order, as the server pages ties (ids mix upper and lower case).
61 (left.thread.id < right.thread.id ? -1 : left.thread.id > right.thread.id ? 1 : 0),
62 )
63 .map(({ thread }) => thread);
64}
65
66function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
67 for (const value of values) {
68 const timestamp = toSortableTimestamp(value ?? undefined);
69 if (timestamp !== null) {
70 return timestamp;
71 }
72 }
73
74 return null;
75}
76
77function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
78 if (thread.latestUserMessageAt) {
79 const latestUserMessageTimestamp = toSortableTimestamp(thread.latestUserMessageAt);
80 if (latestUserMessageTimestamp !== null) {
81 return latestUserMessageTimestamp;
82 }
83 }
84
85 let latestUserMessageTimestamp: number | null = null;
86
87 for (const message of thread.messages ?? []) {
88 if (message.role !== "user") continue;
89 const messageTimestamp = toSortableTimestamp(message.createdAt);
90 if (messageTimestamp === null) continue;
91 latestUserMessageTimestamp =
92 latestUserMessageTimestamp === null
93 ? messageTimestamp
94 : Math.max(latestUserMessageTimestamp, messageTimestamp);
95 }
96
97 if (latestUserMessageTimestamp !== null) {
98 return latestUserMessageTimestamp;
99 }
100
101 return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
102}
103
104export function getThreadSortTimestamp(
105 thread: ThreadSortInput,
106 sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
107): number {
108 if (sortOrder === "created_at") {
109 return (
110 getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
111 );
112 }
113 return getLatestUserMessageTimestamp(thread);
114}
115
116function activeThreadAnchorTimestampMs(thread: {
117 readonly createdAt: string;
118 readonly unsettledAt?: string | null | undefined;
119}): number {
120 return Math.max(
121 toSortableTimestamp(thread.createdAt) ?? 0,
122 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
123 );
124}
125
126export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
127 threads: readonly T[],
128 sortOrder: SidebarThreadSortOrder,
129): T[] {
130 if (threads.length < 2) return [...threads];
131 return threads
132 .map((thread) => ({ thread, timestamp: getThreadSortTimestamp(thread, sortOrder) }))
133 .sort(
134 (left, right) =>
135 right.timestamp - left.timestamp ||
136 (left.thread.id < right.thread.id ? 1 : left.thread.id > right.thread.id ? -1 : 0),
137 )
138 .map(({ thread }) => thread);
139}
140
141export function getLatestThreadForProject<
142 T extends {
143 readonly id: string;
144 readonly projectId: ProjectId;
145 readonly archivedAt: string | null;
146 } & ThreadSortInput,
147>(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
148 let latest: T | null = null;
149 let latestTimestamp = Number.NEGATIVE_INFINITY;
150 for (const thread of threads) {
151 if (thread.projectId !== projectId || thread.archivedAt !== null) continue;
152 const timestamp = getThreadSortTimestamp(thread, sortOrder);
153 if (
154 latest === null ||
155 timestamp > latestTimestamp ||
156 (timestamp === latestTimestamp && thread.id > latest.id)
157 ) {
158 latest = thread;
159 latestTimestamp = timestamp;
160 }
161 }
162 return latest;
163}
164
165const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz";
166
167function isValidPinOrderKey(key: string): boolean {
168 if (key.length === 0) return false;
169 for (const char of key) {
170 if (!PIN_ORDER_DIGITS.includes(char)) return false;
171 }
172 // A trailing minimum digit would leave no room to sort a key immediately
173 // before this one; generators never produce it, so treat it as corrupt.
174 return key.at(-1) !== PIN_ORDER_DIGITS[0];
175}
176
177/** Midpoint of two digit strings interpreted as fractions in (0, 1).
178 "" stands for the open bound on either side. Requires a < b. */
179function pinOrderMidpoint(a: string, b: string): string {
180 if (b !== "" && a >= b) throw new Error("pinOrderMidpoint: bounds out of order");
181 if (b !== "") {
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 if (b.length > 1) return b.charAt(0);
192 return PIN_ORDER_DIGITS.charAt(digitA) + pinOrderMidpoint(a.slice(1), "");
193}
194
195/** Key that sorts strictly between two neighbors; null bounds mean "top of
196 the pinned block" / "bottom of the keyed run". Returns null instead of
197 throwing when existing keys are corrupt or out of order — callers fall
198 back to rewriting the section. */
199export function pinOrderKeyBetween(before: string | null, after: string | null): string | null {
200 const a = before ?? "";
201 const b = after ?? "";
202 if (a !== "" && !isValidPinOrderKey(a)) return null;
203 if (b !== "" && !isValidPinOrderKey(b)) return null;
204 if (b !== "" && a >= b) return null;
205 return pinOrderMidpoint(a, b);
206}
207
208export function generateSpreadPinOrderKeys(count: number): string[] {
209 let width = 2;
210 let space = PIN_ORDER_DIGITS.length ** width;
211 while (space <= (count + 1) * 2) {
212 width += 1;
213 space *= PIN_ORDER_DIGITS.length;
214 }
215 const step = space / (count + 1);
216 const keys: string[] = [];
217 for (let i = 0; i < count; i += 1) {
218 let value = Math.round(step * (i + 1));
219 if (value % PIN_ORDER_DIGITS.length === 0) value += 1;
220 let key = "";
221 for (let digit = 0; digit < width; digit += 1) {
222 key = PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length) + key;
223 value = Math.floor(value / PIN_ORDER_DIGITS.length);
224 }
225 keys.push(key);
226 }
227 return keys;
228}
229
230export function planPinnedReorder(input: {
231 readonly orderedIds: readonly string[];
232 /** Include retained keys from hidden rows; only orderedIds receive writes. */
233 readonly keysById: ReadonlyMap<string, string | null | undefined>;
234 readonly movedId: string;
235}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> {
236 const { orderedIds, keysById, movedId } = input;
237 const visibleIds = new Set(orderedIds);
238 const reservedKeys = new Set(
239 [...keysById].flatMap(([id, key]) => (!visibleIds.has(id) && key != null ? [key] : [])),
240 );
241 const movedIndex = orderedIds.indexOf(movedId);
242 if (movedIndex === -1) return [];
243 const beforeId = movedIndex > 0 ? orderedIds[movedIndex - 1] : null;
244 const afterId = movedIndex < orderedIds.length - 1 ? orderedIds[movedIndex + 1] : null;
245 const beforeKey = beforeId != null ? (keysById.get(beforeId) ?? null) : null;
246 const afterKey = afterId != null ? (keysById.get(afterId) ?? null) : null;
247 const beforeUsable = beforeId === null || beforeKey != null;
248 const afterUsable = afterId === null || afterKey != null;
249 if (beforeUsable && afterUsable) {
250 let key = pinOrderKeyBetween(beforeKey, afterKey);
251 while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);
252 if (key !== null) return [{ id: movedId, orderKey: key }];
253 }
254 const keys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)
255 .filter((key) => !reservedKeys.has(key))
256 .slice(0, orderedIds.length);
257 return orderedIds.flatMap((id, index) => {
258 const key = keys[index]!;
259 return keysById.get(id) === key ? [] : [{ id, orderKey: key }];
260 });
261}
262
263export function sortPinnedThreadsByOrderKey<
264 T extends {
265 readonly id: string;
266 readonly createdAt: string;
267 readonly pinOrderKey?: string | null | undefined;
268 /** Thread ids are only unique within an environment, and the pinned
269 block merges environments — the tiebreak needs both parts or two
270 clients could render equal-key threads in stream-arrival order. */
271 readonly environmentId?: string | undefined;
272 },
273>(threads: readonly T[]): T[] {
274 if (threads.length < 2) return [...threads];
275 const keyed: T[] = [];
276 const keyless: T[] = [];
277 for (const thread of threads) {
278 (thread.pinOrderKey != null ? keyed : keyless).push(thread);
279 }
280 const identityTiebreak = (left: T, right: T) =>
281 left.id.localeCompare(right.id) ||
282 (left.environmentId ?? "").localeCompare(right.environmentId ?? "");
283 keyed.sort((left, right) => {
284 const leftKey = left.pinOrderKey!;
285 const rightKey = right.pinOrderKey!;
286 return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : identityTiebreak(left, right);
287 });
288 const timestamps = new Map(
289 keyless.map((thread) => [thread, toSortableTimestamp(thread.createdAt) ?? 0]),
290 );
291 keyless.sort(
292 (left, right) =>
293 timestamps.get(right)! - timestamps.get(left)! || identityTiebreak(left, right),
294 );
295 return [...keyed, ...keyless];
296}
297
298export function sortActiveThreadsByOrderKey<
299 T extends {
300 readonly id: string;
301 readonly createdAt: string;
302 readonly unsettledAt?: string | null | undefined;
303 readonly activeOrderKey?: string | null | undefined;
304 readonly environmentId?: string | undefined;
305 },
306>(threads: readonly T[]): T[] {
307 if (threads.length < 2) return [...threads];
308 const timestamps = new Map<T, number>();
309 for (const thread of threads) {
310 if (thread.activeOrderKey == null) {
311 timestamps.set(thread, activeThreadAnchorTimestampMs(thread));
312 }
313 }
314 return [...threads].sort((left, right) => {
315 const leftKey = left.activeOrderKey;
316 const rightKey = right.activeOrderKey;
317 if (leftKey == null && rightKey != null) return -1;
318 if (leftKey != null && rightKey == null) return 1;
319 let order = 0;
320 if (leftKey != null && rightKey != null) {
321 order = leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
322 } else {
323 order = timestamps.get(right)! - timestamps.get(left)!;
324 }
325 return (
326 order ||
327 left.id.localeCompare(right.id) ||
328 (left.environmentId ?? "").localeCompare(right.environmentId ?? "")
329 );
330 });
331}