@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 287 lines 10.1 KB
Raw
1 import type { ProjectId } from "@t3tools/contracts";
2 import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3 import { generateSpreadPinOrderKeys, pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey";
4 import type { EnvironmentThreadShell } from "./models.ts";
5
6 export { generateSpreadPinOrderKeys, pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey";
7
8 export interface ThreadSortInput {
9 readonly createdAt: string;
10 readonly updatedAt: string;
11 readonly latestUserMessageAt?: string | null;
12 readonly latestUserAuthoredMessageAt?: string | null;
13 readonly messages?: ReadonlyArray<{
14 readonly createdAt: string;
15 readonly role: string;
16 }>;
17 }
18
19 export function toSortableTimestamp(iso: string | undefined): number | null {
20 if (!iso) return null;
21 const ms = Date.parse(iso);
22 return Number.isFinite(ms) ? ms : null;
23 }
24
25 export type SettledThreadTimestampInput = Pick<
26 EnvironmentThreadShell,
27 "settledAt" | "latestUserMessageAt" | "latestRun" | "updatedAt"
28 >;
29
30 export function resolveSettledThreadTimestamp(thread: SettledThreadTimestampInput): string | null {
31 if (thread.settledAt != null && toSortableTimestamp(thread.settledAt) !== null) {
32 return thread.settledAt;
33 }
34 return resolveThreadActivityTimestamp(thread);
35 }
36
37 export function resolveThreadActivityTimestamp(
38 thread: Pick<EnvironmentThreadShell, "latestUserMessageAt" | "latestRun" | "updatedAt">,
39 ): string | null {
40 let latest: string | null = null;
41 let latestMs = Number.NEGATIVE_INFINITY;
42 for (const candidate of [
43 thread.latestUserMessageAt,
44 thread.latestRun?.requestedAt,
45 thread.latestRun?.startedAt,
46 thread.latestRun?.completedAt,
47 ]) {
48 const parsed = toSortableTimestamp(candidate ?? undefined);
49 if (candidate != null && parsed !== null && parsed > latestMs) {
50 latest = candidate;
51 latestMs = parsed;
52 }
53 }
54 if (latest !== null) return latest;
55 return toSortableTimestamp(thread.updatedAt) === null ? null : thread.updatedAt;
56 }
57
58 export function sortSettledThreads<T extends SettledThreadTimestampInput & { readonly id: string }>(
59 threads: readonly T[],
60 ): T[] {
61 return threads
62 .map((thread) => {
63 const timestamp = resolveSettledThreadTimestamp(thread);
64 return { thread, timestampMs: timestamp === null ? 0 : Date.parse(timestamp) };
65 })
66 .sort(
67 (left, right) =>
68 right.timestampMs - left.timestampMs ||
69 // Plain order, as the server pages ties (ids mix upper and lower case).
70 (left.thread.id < right.thread.id ? -1 : left.thread.id > right.thread.id ? 1 : 0),
71 )
72 .map(({ thread }) => thread);
73 }
74
75 function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
76 for (const value of values) {
77 const timestamp = toSortableTimestamp(value ?? undefined);
78 if (timestamp !== null) {
79 return timestamp;
80 }
81 }
82
83 return null;
84 }
85
86 function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
87 // Agents also post in the user role; only what the user wrote counts. A thread
88 // the user never wrote in counts from its creation; older servers omit the field.
89 if (thread.latestUserAuthoredMessageAt !== undefined) {
90 return (
91 getFirstSortableTimestamp(
92 thread.latestUserAuthoredMessageAt,
93 thread.createdAt,
94 thread.updatedAt,
95 ) ?? Number.NEGATIVE_INFINITY
96 );
97 }
98
99 if (thread.latestUserMessageAt) {
100 const latestUserMessageTimestamp = toSortableTimestamp(thread.latestUserMessageAt);
101 if (latestUserMessageTimestamp !== null) {
102 return latestUserMessageTimestamp;
103 }
104 }
105
106 let latestUserMessageTimestamp: number | null = null;
107
108 for (const message of thread.messages ?? []) {
109 if (message.role !== "user") continue;
110 const messageTimestamp = toSortableTimestamp(message.createdAt);
111 if (messageTimestamp === null) continue;
112 latestUserMessageTimestamp =
113 latestUserMessageTimestamp === null
114 ? messageTimestamp
115 : Math.max(latestUserMessageTimestamp, messageTimestamp);
116 }
117
118 if (latestUserMessageTimestamp !== null) {
119 return latestUserMessageTimestamp;
120 }
121
122 return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
123 }
124
125 export function getThreadSortTimestamp(
126 thread: ThreadSortInput,
127 sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
128 ): number {
129 if (sortOrder === "created_at") {
130 return (
131 getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
132 );
133 }
134 return getLatestUserMessageTimestamp(thread);
135 }
136
137 function activeThreadAnchorTimestampMs(thread: {
138 readonly createdAt: string;
139 readonly unsettledAt?: string | null | undefined;
140 }): number {
141 return Math.max(
142 toSortableTimestamp(thread.createdAt) ?? 0,
143 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
144 );
145 }
146
147 export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
148 threads: readonly T[],
149 sortOrder: SidebarThreadSortOrder,
150 ): T[] {
151 if (threads.length < 2) return [...threads];
152 return threads
153 .map((thread) => ({ thread, timestamp: getThreadSortTimestamp(thread, sortOrder) }))
154 .sort(
155 (left, right) =>
156 right.timestamp - left.timestamp ||
157 (left.thread.id < right.thread.id ? 1 : left.thread.id > right.thread.id ? -1 : 0),
158 )
159 .map(({ thread }) => thread);
160 }
161
162 export function getLatestThreadForProject<
163 T extends {
164 readonly id: string;
165 readonly projectId: ProjectId;
166 readonly archivedAt: string | null;
167 } & ThreadSortInput,
168 >(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
169 let latest: T | null = null;
170 let latestTimestamp = Number.NEGATIVE_INFINITY;
171 for (const thread of threads) {
172 if (thread.projectId !== projectId || thread.archivedAt !== null) continue;
173 const timestamp = getThreadSortTimestamp(thread, sortOrder);
174 if (
175 latest === null ||
176 timestamp > latestTimestamp ||
177 (timestamp === latestTimestamp && thread.id > latest.id)
178 ) {
179 latest = thread;
180 latestTimestamp = timestamp;
181 }
182 }
183 return latest;
184 }
185
186 export function planPinnedReorder(input: {
187 readonly orderedIds: readonly string[];
188 /** Include retained keys from hidden rows; only orderedIds receive writes. */
189 readonly keysById: ReadonlyMap<string, string | null | undefined>;
190 readonly movedId: string;
191 }): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> {
192 const { orderedIds, keysById, movedId } = input;
193 const visibleIds = new Set(orderedIds);
194 const reservedKeys = new Set(
195 [...keysById].flatMap(([id, key]) => (!visibleIds.has(id) && key != null ? [key] : [])),
196 );
197 const movedIndex = orderedIds.indexOf(movedId);
198 if (movedIndex === -1) return [];
199 const beforeId = movedIndex > 0 ? orderedIds[movedIndex - 1] : null;
200 const afterId = movedIndex < orderedIds.length - 1 ? orderedIds[movedIndex + 1] : null;
201 const beforeKey = beforeId != null ? (keysById.get(beforeId) ?? null) : null;
202 const afterKey = afterId != null ? (keysById.get(afterId) ?? null) : null;
203 const beforeUsable = beforeId === null || beforeKey != null;
204 const afterUsable = afterId === null || afterKey != null;
205 if (beforeUsable && afterUsable) {
206 let key = pinOrderKeyBetween(beforeKey, afterKey);
207 while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);
208 if (key !== null) return [{ id: movedId, orderKey: key }];
209 }
210 const keys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)
211 .filter((key) => !reservedKeys.has(key))
212 .slice(0, orderedIds.length);
213 return orderedIds.flatMap((id, index) => {
214 const key = keys[index]!;
215 return keysById.get(id) === key ? [] : [{ id, orderKey: key }];
216 });
217 }
218
219 export function sortPinnedThreadsByOrderKey<
220 T extends {
221 readonly id: string;
222 readonly createdAt: string;
223 readonly pinOrderKey?: string | null | undefined;
224 /** Thread ids are only unique within an environment, and the pinned
225 block merges environments — the tiebreak needs both parts or two
226 clients could render equal-key threads in stream-arrival order. */
227 readonly environmentId?: string | undefined;
228 },
229 >(threads: readonly T[]): T[] {
230 if (threads.length < 2) return [...threads];
231 const keyed: T[] = [];
232 const keyless: T[] = [];
233 for (const thread of threads) {
234 (thread.pinOrderKey != null ? keyed : keyless).push(thread);
235 }
236 const identityTiebreak = (left: T, right: T) =>
237 left.id.localeCompare(right.id) ||
238 (left.environmentId ?? "").localeCompare(right.environmentId ?? "");
239 keyed.sort((left, right) => {
240 const leftKey = left.pinOrderKey!;
241 const rightKey = right.pinOrderKey!;
242 return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : identityTiebreak(left, right);
243 });
244 const timestamps = new Map(
245 keyless.map((thread) => [thread, toSortableTimestamp(thread.createdAt) ?? 0]),
246 );
247 keyless.sort(
248 (left, right) =>
249 timestamps.get(right)! - timestamps.get(left)! || identityTiebreak(left, right),
250 );
251 return [...keyed, ...keyless];
252 }
253
254 export function sortActiveThreadsByOrderKey<
255 T extends {
256 readonly id: string;
257 readonly createdAt: string;
258 readonly unsettledAt?: string | null | undefined;
259 readonly activeOrderKey?: string | null | undefined;
260 readonly environmentId?: string | undefined;
261 },
262 >(threads: readonly T[]): T[] {
263 if (threads.length < 2) return [...threads];
264 const timestamps = new Map<T, number>();
265 for (const thread of threads) {
266 if (thread.activeOrderKey == null) {
267 timestamps.set(thread, activeThreadAnchorTimestampMs(thread));
268 }
269 }
270 return [...threads].sort((left, right) => {
271 const leftKey = left.activeOrderKey;
272 const rightKey = right.activeOrderKey;
273 if (leftKey == null && rightKey != null) return -1;
274 if (leftKey != null && rightKey == null) return 1;
275 let order = 0;
276 if (leftKey != null && rightKey != null) {
277 order = leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
278 } else {
279 order = timestamps.get(right)! - timestamps.get(left)!;
280 }
281 return (
282 order ||
283 left.id.localeCompare(right.id) ||
284 (left.environmentId ?? "").localeCompare(right.environmentId ?? "")
285 );
286 });
287 }