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. Reopening the same active thread
26// within THREAD_OPEN_DEDUPE_MS is deduped, while switching to another thread
27// sends an open so the server persists the latest access order.
28const sentThreadOpens = new Map<string, number>();
29// When this client last opened each thread, sent or not, so recent threads
30// update immediately before the server echo arrives.
31const localThreadOpens = new Map<string, number>();
32let localThreadOpensVersion = 0;
33let lastOpenedThreadKey: string | null = null;
34
35/**
36 * Records that this client opened a thread, and says whether to send the open
37 * to the server now.
38 */
39export function claimThreadOpen(environmentId: EnvironmentId, threadId: string, now: number) {
40 const key = `${environmentId}:${threadId}`;
41 if (now > (localThreadOpens.get(key) ?? Number.NEGATIVE_INFINITY)) {
42 localThreadOpens.set(key, now);
43 localThreadOpensVersion += 1;
44 }
45 if (
46 key === lastOpenedThreadKey &&
47 now - (sentThreadOpens.get(key) ?? Number.NEGATIVE_INFINITY) < THREAD_OPEN_DEDUPE_MS
48 ) {
49 return false;
50 }
51 lastOpenedThreadKey = key;
52 sentThreadOpens.set(key, now);
53 return true;
54}
55
56/** Clears the active-thread dedupe lock when leaving a thread so returning persists a new open. */
57export function releaseThreadOpen(environmentId: EnvironmentId, threadId: string) {
58 if (lastOpenedThreadKey === `${environmentId}:${threadId}`) {
59 lastOpenedThreadKey = null;
60 }
61}
62
63export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchMatch {
64 readonly environmentId: EnvironmentId;
65}
66
67export interface ThreadSearchResultsState {
68 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
69 readonly isLoading: boolean;
70 /**
71 * Every environment asked failed to answer, so an empty result says nothing about matches. One
72 * environment failing beside another that answered still counts as an answer.
73 */
74 readonly failed: boolean;
75 /** Rows of matching older settled threads, which shells that omit them do not hold. */
76 readonly rows: ReadonlyArray<{
77 readonly environmentId: EnvironmentId;
78 readonly read: OrchestrationV2ThreadFamily;
79 }>;
80}
81
82/**
83 * The caller's project scope, which limits message hits on every environment, and how a search
84 * reaches environments whose shells omit older settled threads (others ignore it): its names for
85 * environments, which its own ranking matches, and whether to skip message search.
86 */
87export const ThreadSearchScope = Schema.Struct({
88 projectIds: Schema.optionalKey(Schema.Array(ProjectId)),
89 environmentLabels: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
90 titlesOnly: Schema.optionalKey(Schema.Boolean),
91});
92export type ThreadSearchScope = typeof ThreadSearchScope.Type;
93
94const ThreadSearchKey = Schema.fromJsonString(
95 Schema.Union([
96 Schema.Tuple([Schema.Array(EnvironmentId), OrchestrationSearchThreadsInput.fields.query]),
97 Schema.Tuple([
98 Schema.Array(EnvironmentId),
99 OrchestrationSearchThreadsInput.fields.query,
100 ThreadSearchScope,
101 ]),
102 ]),
103);
104const decodeThreadSearchKey = Schema.decodeUnknownOption(ThreadSearchKey);
105const EMPTY_SEARCH_ROWS: ThreadSearchResultsState["rows"] = [];
106const EMPTY_READS: ReadonlyArray<OrchestrationV2ThreadFamily> = [];
107
108export function makeThreadSearchKey(
109 environmentIds: ReadonlyArray<EnvironmentId>,
110 query: string,
111 scope: ThreadSearchScope = {},
112): string {
113 const sorted = [...environmentIds].sort((left, right) => left.localeCompare(right));
114 return JSON.stringify(Object.keys(scope).length === 0 ? [sorted, query] : [sorted, query, scope]);
115}
116
117function parseThreadSearchKey(key: string) {
118 return decodeThreadSearchKey(key);
119}
120
121export function threadSearchMatchKey(
122 match: Pick<EnvironmentThreadSearchMatch, "environmentId" | "threadId">,
123): string {
124 return JSON.stringify([match.environmentId, match.threadId]);
125}
126
127/**
128 * Message matches from every environment, plus, from environments whose shells omit older settled
129 * threads (`olderSettledBefore` is set), the rows of the best older matches. Callers mount those
130 * rows (`rows`) so their own ranking sees them, as it sees shell rows.
131 */
132export function createThreadSearchResultsAtomFamily<E>(options: {
133 readonly getSearchAtom: (
134 environmentId: EnvironmentId,
135 input: OrchestrationV2SearchThreadsInput,
136 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2SearchThreadsResult, E>>;
137 readonly olderSettledBefore?: (environmentId: EnvironmentId) => Atom.Atom<string | null>;
138 readonly labelPrefix: string;
139}) {
140 const results = Atom.family((key: string) =>
141 Atom.make((get): ThreadSearchResultsState => {
142 const parsedKey = parseThreadSearchKey(key);
143 if (Option.isNone(parsedKey)) {
144 return { matches: [], isLoading: false, failed: false, rows: EMPTY_SEARCH_ROWS };
145 }
146
147 const [environmentIds, query, scope = {}] = parsedKey.value;
148 // The server needs a word of three or more letters to match messages.
149 const searchMessages =
150 scope.titlesOnly !== true && messageSearchTokens(query).long.length > 0;
151 const matches: EnvironmentThreadSearchMatch[] = [];
152 const rows: Array<ThreadSearchResultsState["rows"][number]> = [];
153 let isLoading = false;
154 let asked = 0;
155 let failures = 0;
156
157 for (const environmentId of environmentIds) {
158 const before = options.olderSettledBefore
159 ? get(options.olderSettledBefore(environmentId))
160 : null;
161 if (!searchMessages && before === null) continue;
162 const label = scope.environmentLabels?.[environmentId];
163 const result = get(
164 options.getSearchAtom(environmentId, {
165 query,
166 ...(scope.projectIds === undefined ? {} : { projectIds: scope.projectIds }),
167 ...(before === null
168 ? {}
169 : {
170 olderSettledBefore: before,
171 ...(label === undefined ? {} : { environmentLabel: label }),
172 ...(searchMessages ? {} : { titlesOnly: true }),
173 }),
174 }),
175 );
176 isLoading ||= result.waiting;
177 asked += 1;
178 if (AsyncResult.isFailure(result)) failures += 1;
179 const value = AsyncResult.getOrElse(result, () => null);
180 if (value !== null) {
181 matches.push(...value.matches.map((match) => ({ ...match, environmentId })));
182 if (value.threads !== undefined && value.threads.length > 0) {
183 rows.push({
184 environmentId,
185 read: { snapshotSequence: value.snapshotSequence ?? 0, threads: value.threads },
186 });
187 }
188 }
189 }
190
191 return {
192 matches,
193 isLoading,
194 failed: asked > 0 && failures === asked,
195 rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows,
196 };
197 }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)),
198 );
199 const rowsAtom = Atom.family((rowsKey: string) => {
200 const [key, environmentId] = JSON.parse(rowsKey) as [string, EnvironmentId];
201 let previous = EMPTY_READS;
202 return Atom.make((get) => {
203 const next = get(results(key)).rows.flatMap((row) =>
204 row.environmentId === environmentId ? [row.read] : [],
205 );
206 if (next.length === previous.length && next.every((read, index) => read === previous[index]))
207 return previous;
208 previous = next.length === 0 ? EMPTY_READS : next;
209 return previous;
210 }).pipe(Atom.withLabel(`${options.labelPrefix}-rows:${rowsKey}`));
211 });
212 return {
213 results,
214 /** One environment's older settled rows for a search key, for `mountRows`. */
215 rows: (key: string, environmentId: EnvironmentId) =>
216 rowsAtom(JSON.stringify([key, environmentId])),
217 };
218}
219
220export type ThreadSearchShell = Pick<
221 EnvironmentThreadShell,
222 | "environmentId"
223 | "id"
224 | "title"
225 | "branch"
226 | "createdAt"
227 | "updatedAt"
228 | "latestUserMessageAt"
229 | "latestUserAuthoredMessageAt"
230 | "opens"
231> &
232 Partial<Pick<EnvironmentThreadShell, "pullRequests" | "linkedPullRequest" | "branchPullRequest">>;
233
234/**
235 * What the web and mobile palettes rank a thread shell by. Pass the
236 * environment label only when there are two or more environments.
237 */
238export function threadSearchSubject(
239 thread: ThreadSearchShell,
240 projectTitle: string | null | undefined,
241 environmentLabel?: string | null,
242): ThreadSearchSubject {
243 // A keystroke ranks the same shells again, so a subject is built once per shell.
244 const cached = subjectCache.get(thread);
245 if (
246 cached !== undefined &&
247 cached.projectTitle === projectTitle &&
248 cached.environmentLabel === environmentLabel &&
249 cached.opensVersion === localThreadOpensVersion
250 ) {
251 return cached.subject;
252 }
253 const subject = buildThreadSearchSubject(thread, projectTitle, environmentLabel);
254 subjectCache.set(thread, {
255 projectTitle,
256 environmentLabel,
257 opensVersion: localThreadOpensVersion,
258 subject,
259 });
260 return subject;
261}
262
263const subjectCache = new WeakMap<
264 ThreadSearchShell,
265 {
266 readonly projectTitle: string | null | undefined;
267 readonly environmentLabel: string | null | undefined;
268 readonly opensVersion: number;
269 readonly subject: ThreadSearchSubject;
270 }
271>();
272
273function buildThreadSearchSubject(
274 thread: ThreadSearchShell,
275 projectTitle: string | null | undefined,
276 environmentLabel: string | null | undefined,
277): ThreadSearchSubject {
278 const activityAt = getThreadSortTimestamp(thread, "updated_at");
279 const localOpenedAt = localThreadOpens.get(`${thread.environmentId}:${thread.id}`) ?? 0;
280 return {
281 id: thread.id,
282 title: thread.title,
283 branch: thread.branch,
284 projectTitle: projectTitle ?? null,
285 environmentLabel: environmentLabel ?? null,
286 pullRequests: threadSearchPullRequests(thread),
287 activityAt: Number.isFinite(activityAt) ? activityAt : null,
288 // This client's own latest open counts too: the server merged it, or has
289 // no record yet (an older server ignores opens).
290 opens:
291 localOpenedAt > (thread.opens?.openedAt ?? 0)
292 ? {
293 score: 1,
294 picks: [],
295 ...thread.opens,
296 ...(thread.opens && thread.opens.scoredAt === undefined
297 ? { scoredAt: thread.opens.openedAt }
298 : {}),
299 openedAt: localOpenedAt,
300 }
301 : (thread.opens ?? null),
302 };
303}
304
305/** Message result keys in the order a search box last showed them for `query`. */
306export interface ShownOrder {
307 readonly query: string;
308 readonly keys: ReadonlyArray<string>;
309 /** How many of `keys` are on screen; only those hold their places. */
310 readonly shown: number;
311}
312
313// Rows past the limit a slower environment's best matches may take.
314const LATE_ROOM = 3;
315
316/**
317 * Keep shown rows in place so late results cannot move the pointer or keyboard target.
318 * Allow up to LATE_ROOM extra rows so late best matches remain visible.
319 * Reuse `previous` when unchanged to avoid a React state update.
320 */
321export function nextShownOrder(
322 previous: ShownOrder | null,
323 query: string,
324 ranked: ReadonlyArray<string>,
325 limit: number,
326): ShownOrder {
327 if (previous?.query !== query) {
328 return { query, keys: ranked, shown: Math.min(limit, ranked.length) };
329 }
330 const listed = new Set(ranked);
331 const kept = previous.keys.slice(0, previous.shown).filter((key) => listed.has(key));
332 const held = new Set(kept);
333 const seen = new Set(previous.keys);
334 const rest = ranked.filter((key) => !held.has(key));
335 const arrived = rest.filter((key) => !seen.has(key)).length;
336 const keys = [...kept, ...rest];
337 const shown = Math.min(
338 keys.length,
339 limit + LATE_ROOM,
340 Math.max(limit, kept.length + Math.min(arrived, LATE_ROOM)),
341 );
342 const unchanged =
343 shown === previous.shown &&
344 keys.length === previous.keys.length &&
345 keys.every((key, index) => key === previous.keys[index]);
346 return unchanged ? previous : { query, keys, shown };
347}
348
349export interface SettledThreadSearch {
350 readonly query: string;
351 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
352}
353
354/**
355 * What a search box shows for `query`: its own results once they arrive
356 * (`ready`), else the previous results if `query` refines or widens their
357 * query, so result rows do not blink out and back on every keystroke.
358 * Results for an unrelated query clear.
359 */
360export function visibleThreadSearch(
361 query: string,
362 ready: SettledThreadSearch | null,
363 previous: SettledThreadSearch | null,
364): SettledThreadSearch {
365 if (ready !== null) return ready;
366 const current = foldSearchQuery(query);
367 const before = foldSearchQuery(previous?.query ?? "");
368 return previous !== null &&
369 current.length > 0 &&
370 before.length > 0 &&
371 (current.startsWith(before) || before.startsWith(current))
372 ? previous
373 : { query: "", matches: [] };
374}