Open History to see the last commit
1import {
2 EnvironmentId,
3 OrchestrationSearchThreadsInput,
4 ProjectId,
5 type OrchestrationThreadSearchMatch,
6 type OrchestrationV2SearchThreadsInput,
7 type OrchestrationV2SearchThreadsResult,
8 type OrchestrationV2ThreadFamily,
9} from "@t3tools/contracts";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import { AsyncResult, Atom } from "effect/reactivity";
13import {
14 foldSearchQuery,
15 messageSearchTokens,
16 THREAD_OPEN_DEDUPE_MS,
17 type ThreadSearchSubject,
18} from "@t3tools/shared/paletteSearch";
19import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
20
21import type { EnvironmentThreadShell } from "./models.ts";
22import { getThreadSortTimestamp } from "./threadSort.ts";
23
24// When this client last sent an open per thread, by its own clock: a server
25// timestamp would be off by any clock skew. The server merges opens closer
26// together than THREAD_OPEN_DEDUPE_MS anyway, so skipping them saves a command
27// and a broadcast while flipping between threads.
28const sentThreadOpens = new Map<string, number>();
29// When this client last opened each thread, sent or not, so recent threads
30// follow quick switches the server merges.
31const localThreadOpens = new Map<string, number>();
32/**
33 * Records that this client opened a thread, and says whether to send the open
34 * to the server now.
35 */
36export function claimThreadOpen(environmentId: EnvironmentId, threadId: string, now: number) {
37 const key = `${environmentId}:${threadId}`;
38 localThreadOpens.set(key, now);
39 if (now - (sentThreadOpens.get(key) ?? Number.NEGATIVE_INFINITY) < THREAD_OPEN_DEDUPE_MS) {
40 return false;
41 }
42 sentThreadOpens.set(key, now);
43 return true;
44}
45
46export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchMatch {
47 readonly environmentId: EnvironmentId;
48}
49
50export interface ThreadSearchResultsState {
51 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
52 readonly isLoading: boolean;
53 /** Rows of matching older settled threads, which shells that omit them do not hold. */
54 readonly rows: ReadonlyArray<{
55 readonly environmentId: EnvironmentId;
56 readonly read: OrchestrationV2ThreadFamily;
57 }>;
58}
59
60/**
61 * How a search reaches environments whose shells omit older settled threads (others ignore it):
62 * the caller's project scope and its names for environments, which its own ranking matches, and
63 * whether to skip message search.
64 */
65export const ThreadSearchScope = Schema.Struct({
66 projectIds: Schema.optionalKey(Schema.Array(ProjectId)),
67 environmentLabels: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
68 titlesOnly: Schema.optionalKey(Schema.Boolean),
69});
70export type ThreadSearchScope = typeof ThreadSearchScope.Type;
71
72const ThreadSearchKey = Schema.fromJsonString(
73 Schema.Union([
74 Schema.Tuple([Schema.Array(EnvironmentId), OrchestrationSearchThreadsInput.fields.query]),
75 Schema.Tuple([
76 Schema.Array(EnvironmentId),
77 OrchestrationSearchThreadsInput.fields.query,
78 ThreadSearchScope,
79 ]),
80 ]),
81);
82const decodeThreadSearchKey = Schema.decodeUnknownOption(ThreadSearchKey);
83const EMPTY_SEARCH_ROWS: ThreadSearchResultsState["rows"] = [];
84const EMPTY_READS: ReadonlyArray<OrchestrationV2ThreadFamily> = [];
85
86export function makeThreadSearchKey(
87 environmentIds: ReadonlyArray<EnvironmentId>,
88 query: string,
89 scope: ThreadSearchScope = {},
90): string {
91 const sorted = [...environmentIds].sort((left, right) => left.localeCompare(right));
92 return JSON.stringify(Object.keys(scope).length === 0 ? [sorted, query] : [sorted, query, scope]);
93}
94
95function parseThreadSearchKey(key: string) {
96 return decodeThreadSearchKey(key);
97}
98
99export function threadSearchMatchKey(
100 match: Pick<EnvironmentThreadSearchMatch, "environmentId" | "threadId">,
101): string {
102 return JSON.stringify([match.environmentId, match.threadId]);
103}
104
105/**
106 * Message matches from every environment, plus, from environments whose shells omit older settled
107 * threads (`olderSettledBefore` is set), the rows of the best older matches. Callers mount those
108 * rows (`rows`) so their own ranking sees them, as it sees shell rows.
109 */
110export function createThreadSearchResultsAtomFamily<E>(options: {
111 readonly getSearchAtom: (
112 environmentId: EnvironmentId,
113 input: OrchestrationV2SearchThreadsInput,
114 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2SearchThreadsResult, E>>;
115 readonly olderSettledBefore?: (environmentId: EnvironmentId) => Atom.Atom<string | null>;
116 readonly labelPrefix: string;
117}) {
118 const results = Atom.family((key: string) =>
119 Atom.make((get): ThreadSearchResultsState => {
120 const parsedKey = parseThreadSearchKey(key);
121 if (Option.isNone(parsedKey)) {
122 return { matches: [], isLoading: false, rows: EMPTY_SEARCH_ROWS };
123 }
124
125 const [environmentIds, query, scope = {}] = parsedKey.value;
126 // The server needs a word of three or more letters to match messages.
127 const searchMessages =
128 scope.titlesOnly !== true && messageSearchTokens(query).long.length > 0;
129 const matches: EnvironmentThreadSearchMatch[] = [];
130 const rows: Array<ThreadSearchResultsState["rows"][number]> = [];
131 let isLoading = false;
132
133 for (const environmentId of environmentIds) {
134 const before = options.olderSettledBefore
135 ? get(options.olderSettledBefore(environmentId))
136 : null;
137 if (!searchMessages && before === null) continue;
138 const label = scope.environmentLabels?.[environmentId];
139 const result = get(
140 options.getSearchAtom(environmentId, {
141 query,
142 ...(before === null
143 ? {}
144 : {
145 olderSettledBefore: before,
146 ...(scope.projectIds === undefined ? {} : { projectIds: scope.projectIds }),
147 ...(label === undefined ? {} : { environmentLabel: label }),
148 ...(searchMessages ? {} : { titlesOnly: true }),
149 }),
150 }),
151 );
152 isLoading ||= result.waiting;
153 const value = Option.getOrNull(AsyncResult.value(result));
154 if (value !== null) {
155 matches.push(...value.matches.map((match) => ({ ...match, environmentId })));
156 if (value.threads !== undefined && value.threads.length > 0) {
157 rows.push({
158 environmentId,
159 read: { snapshotSequence: value.snapshotSequence ?? 0, threads: value.threads },
160 });
161 }
162 }
163 }
164
165 return { matches, isLoading, rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows };
166 }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)),
167 );
168 const rowsAtom = Atom.family((rowsKey: string) => {
169 const [key, environmentId] = JSON.parse(rowsKey) as [string, EnvironmentId];
170 let previous = EMPTY_READS;
171 return Atom.make((get) => {
172 const next = get(results(key)).rows.flatMap((row) =>
173 row.environmentId === environmentId ? [row.read] : [],
174 );
175 if (next.length === previous.length && next.every((read, index) => read === previous[index]))
176 return previous;
177 previous = next.length === 0 ? EMPTY_READS : next;
178 return previous;
179 }).pipe(Atom.withLabel(`${options.labelPrefix}-rows:${rowsKey}`));
180 });
181 return {
182 results,
183 /** One environment's older settled rows for a search key, for `mountRows`. */
184 rows: (key: string, environmentId: EnvironmentId) =>
185 rowsAtom(JSON.stringify([key, environmentId])),
186 };
187}
188
189export type ThreadSearchShell = Pick<
190 EnvironmentThreadShell,
191 | "environmentId"
192 | "id"
193 | "title"
194 | "branch"
195 | "createdAt"
196 | "updatedAt"
197 | "latestUserMessageAt"
198 | "latestUserAuthoredMessageAt"
199 | "opens"
200> &
201 Partial<Pick<EnvironmentThreadShell, "pullRequests" | "linkedPullRequest" | "branchPullRequest">>;
202
203/**
204 * What the web and mobile palettes rank a thread shell by. Pass the
205 * environment label only when there are two or more environments.
206 */
207export function threadSearchSubject(
208 thread: ThreadSearchShell,
209 projectTitle: string | null | undefined,
210 environmentLabel?: string | null,
211): ThreadSearchSubject {
212 // What the user wrote, not agent wakes or task notices in the user role. A
213 // thread the user never wrote in counts from its creation; an older server
214 // omits the field, so the latest user-role message stands in.
215 const authored = thread.latestUserAuthoredMessageAt;
216 const activityAt =
217 authored === undefined
218 ? getThreadSortTimestamp(thread, "updated_at")
219 : Date.parse(authored ?? thread.createdAt);
220 const localOpenedAt = localThreadOpens.get(`${thread.environmentId}:${thread.id}`) ?? 0;
221 return {
222 id: thread.id,
223 title: thread.title,
224 branch: thread.branch,
225 projectTitle: projectTitle ?? null,
226 environmentLabel: environmentLabel ?? null,
227 pullRequests: threadSearchPullRequests(thread),
228 activityAt: Number.isFinite(activityAt) ? activityAt : null,
229 // This client's own latest open counts too: the server merged it, or has
230 // no record yet (an older server ignores opens).
231 opens:
232 localOpenedAt > (thread.opens?.openedAt ?? 0)
233 ? { score: 1, picks: [], ...thread.opens, openedAt: localOpenedAt }
234 : (thread.opens ?? null),
235 };
236}
237
238/** Message result keys in the order a search box last showed them for `query`. */
239export interface ShownOrder {
240 readonly query: string;
241 readonly keys: ReadonlyArray<string>;
242 /** How many of `keys` are on screen; only those hold their places. */
243 readonly shown: number;
244}
245
246// Rows past the limit a slower environment's best matches may take.
247const LATE_ROOM = 3;
248
249/**
250 * Keep shown rows in place so late results cannot move the pointer or keyboard target.
251 * Allow up to LATE_ROOM extra rows so late best matches remain visible.
252 * Reuse `previous` when unchanged to avoid a React state update.
253 */
254export function nextShownOrder(
255 previous: ShownOrder | null,
256 query: string,
257 ranked: ReadonlyArray<string>,
258 limit: number,
259): ShownOrder {
260 if (previous?.query !== query) {
261 return { query, keys: ranked, shown: Math.min(limit, ranked.length) };
262 }
263 const listed = new Set(ranked);
264 const kept = previous.keys.slice(0, previous.shown).filter((key) => listed.has(key));
265 const held = new Set(kept);
266 const seen = new Set(previous.keys);
267 const rest = ranked.filter((key) => !held.has(key));
268 const arrived = rest.filter((key) => !seen.has(key)).length;
269 const keys = [...kept, ...rest];
270 const shown = Math.min(
271 keys.length,
272 limit + LATE_ROOM,
273 Math.max(limit, kept.length + Math.min(arrived, LATE_ROOM)),
274 );
275 const unchanged =
276 shown === previous.shown &&
277 keys.length === previous.keys.length &&
278 keys.every((key, index) => key === previous.keys[index]);
279 return unchanged ? previous : { query, keys, shown };
280}
281
282export interface SettledThreadSearch {
283 readonly query: string;
284 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
285}
286
287/**
288 * What a search box shows for `query`: its own results once they arrive
289 * (`ready`), else the previous results if `query` refines or widens their
290 * query, so result rows do not blink out and back on every keystroke.
291 * Results for an unrelated query clear.
292 */
293export function visibleThreadSearch(
294 query: string,
295 ready: SettledThreadSearch | null,
296 previous: SettledThreadSearch | null,
297): SettledThreadSearch {
298 if (ready !== null) return ready;
299 const current = foldSearchQuery(query);
300 const before = foldSearchQuery(previous?.query ?? "");
301 return previous !== null &&
302 current.length > 0 &&
303 before.length > 0 &&
304 (current.startsWith(before) || before.startsWith(current))
305 ? previous
306 : { query: "", matches: [] };
307}