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