Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadSearch.ts

226 lines7.7 KB

1import {
2 EnvironmentId,
3 OrchestrationSearchThreadsInput,
4 type OrchestrationSearchThreadsResult,
5 type OrchestrationThreadSearchMatch,
6} from "@t3tools/contracts";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import { AsyncResult, Atom } from "effect/reactivity";
10import {
11 foldSearchQuery,
12 THREAD_OPEN_DEDUPE_MS,
13 type ThreadSearchSubject,
14} from "@t3tools/shared/paletteSearch";
15import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
16​
17import type { EnvironmentThreadShell } from "./models.ts";
18import { getThreadSortTimestamp } from "./threadSort.ts";
19​
20// When this client last sent an open per thread, by its own clock: a server
21// timestamp would be off by any clock skew. The server merges opens closer
22// together than THREAD_OPEN_DEDUPE_MS anyway, so skipping them saves a command
23// and a broadcast while flipping between threads.
24const sentThreadOpens = new Map<string, number>();
25// When this client last opened each thread, sent or not, so recent threads
26// follow quick switches the server merges.
27const localThreadOpens = new Map<string, number>();
28/**
29 * Records that this client opened a thread, and says whether to send the open
30 * to the server now.
31 */
32export function claimThreadOpen(environmentId: EnvironmentId, threadId: string, now: number) {
33 const key = `${environmentId}:${threadId}`;
34 localThreadOpens.set(key, now);
35 if (now - (sentThreadOpens.get(key) ?? Number.NEGATIVE_INFINITY) < THREAD_OPEN_DEDUPE_MS) {
36 return false;
37 }
38 sentThreadOpens.set(key, now);
39 return true;
41​
42export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchMatch {
43 readonly environmentId: EnvironmentId;
45​
46export interface ThreadSearchResultsState {
47 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
48 readonly isLoading: boolean;
50​
51const ThreadSearchKey = Schema.fromJsonString(
52 Schema.Tuple([Schema.Array(EnvironmentId), OrchestrationSearchThreadsInput.fields.query]),
53);
54const decodeThreadSearchKey = Schema.decodeUnknownOption(ThreadSearchKey);
55​
56export function makeThreadSearchKey(
57 environmentIds: ReadonlyArray<EnvironmentId>,
58 query: string,
59): string {
60 return JSON.stringify([
61 [...environmentIds].sort((left, right) => left.localeCompare(right)),
62 query,
63 ]);
65​
66function parseThreadSearchKey(key: string) {
67 return decodeThreadSearchKey(key);
69​
70export function threadSearchMatchKey(
71 match: Pick<EnvironmentThreadSearchMatch, "environmentId" | "threadId">,
72): string {
73 return JSON.stringify([match.environmentId, match.threadId]);
75​
76export function createThreadSearchResultsAtomFamily<E>(options: {
77 readonly getSearchAtom: (
78 environmentId: EnvironmentId,
79 query: string,
80 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationSearchThreadsResult, E>>;
81 readonly labelPrefix: string;
82}) {
83 return Atom.family((key: string) =>
84 Atom.make((get): ThreadSearchResultsState => {
85 const parsedKey = parseThreadSearchKey(key);
86 if (Option.isNone(parsedKey)) {
87 return { matches: [], isLoading: false };
88 }
89​
90 const [environmentIds, query] = parsedKey.value;
91 const matches: EnvironmentThreadSearchMatch[] = [];
92 let isLoading = false;
93​
94 for (const environmentId of environmentIds) {
95 const result = get(options.getSearchAtom(environmentId, query));
96 isLoading ||= result.waiting;
97 const value = Option.getOrNull(AsyncResult.value(result));
98 if (value !== null) {
99 matches.push(...value.matches.map((match) => ({ ...match, environmentId })));
100 }
101 }
102​
103 return { matches, isLoading };
104 }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)),
105 );
107​
108export type ThreadSearchShell = Pick<
109 EnvironmentThreadShell,
110 | "environmentId"
111 | "id"
112 | "title"
113 | "branch"
114 | "createdAt"
115 | "updatedAt"
116 | "latestUserMessageAt"
117 | "latestUserAuthoredMessageAt"
118 | "opens"
119> &
120 Partial<Pick<EnvironmentThreadShell, "pullRequests" | "linkedPullRequest" | "branchPullRequest">>;
121​
122/**
123 * What the web and mobile palettes rank a thread shell by. Pass the
124 * environment label only when there are two or more environments.
125 */
126export function threadSearchSubject(
127 thread: ThreadSearchShell,
128 projectTitle: string | null | undefined,
129 environmentLabel?: string | null,
130): ThreadSearchSubject {
131 // What the user wrote, not agent wakes or task notices in the user role. A
132 // thread the user never wrote in counts from its creation; an older server
133 // omits the field, so the latest user-role message stands in.
134 const authored = thread.latestUserAuthoredMessageAt;
135 const activityAt =
136 authored === undefined
137 ? getThreadSortTimestamp(thread, "updated_at")
138 : Date.parse(authored ?? thread.createdAt);
139 const localOpenedAt = localThreadOpens.get(`${thread.environmentId}:${thread.id}`) ?? 0;
140 return {
141 id: thread.id,
142 title: thread.title,
143 branch: thread.branch,
144 projectTitle: projectTitle ?? null,
145 environmentLabel: environmentLabel ?? null,
146 pullRequests: threadSearchPullRequests(thread),
147 activityAt: Number.isFinite(activityAt) ? activityAt : null,
148 // This client's own latest open counts too: the server merged it, or has
149 // no record yet (an older server ignores opens).
150 opens:
151 localOpenedAt > (thread.opens?.openedAt ?? 0)
152 ? { score: 1, picks: [], ...thread.opens, openedAt: localOpenedAt }
153 : (thread.opens ?? null),
154 };
156​
157/** Message result keys in the order a search box last showed them for `query`. */
158export interface ShownOrder {
159 readonly query: string;
160 readonly keys: ReadonlyArray<string>;
161 /** How many of `keys` are on screen; only those hold their places. */
162 readonly shown: number;
164​
165// Rows past the limit a slower environment's best matches may take.
166const LATE_ROOM = 3;
167​
168/**
169 * Keep shown rows in place so late results cannot move the pointer or keyboard target.
170 * Allow up to LATE_ROOM extra rows so late best matches remain visible.
171 * Reuse `previous` when unchanged to avoid a React state update.
172 */
173export function nextShownOrder(
174 previous: ShownOrder | null,
175 query: string,
176 ranked: ReadonlyArray<string>,
177 limit: number,
178): ShownOrder {
179 if (previous?.query !== query) {
180 return { query, keys: ranked, shown: Math.min(limit, ranked.length) };
181 }
182 const listed = new Set(ranked);
183 const kept = previous.keys.slice(0, previous.shown).filter((key) => listed.has(key));
184 const held = new Set(kept);
185 const seen = new Set(previous.keys);
186 const rest = ranked.filter((key) => !held.has(key));
187 const arrived = rest.filter((key) => !seen.has(key)).length;
188 const keys = [...kept, ...rest];
189 const shown = Math.min(
190 keys.length,
191 limit + LATE_ROOM,
192 Math.max(limit, kept.length + Math.min(arrived, LATE_ROOM)),
193 );
194 const unchanged =
195 shown === previous.shown &&
196 keys.length === previous.keys.length &&
197 keys.every((key, index) => key === previous.keys[index]);
198 return unchanged ? previous : { query, keys, shown };
200​
201export interface SettledThreadSearch {
202 readonly query: string;
203 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
205​
206/**
207 * What a search box shows for `query`: its own results once they arrive
208 * (`ready`), else the previous results if `query` refines or widens their
209 * query, so result rows do not blink out and back on every keystroke.
210 * Results for an unrelated query clear.
211 */
212export function visibleThreadSearch(
213 query: string,
214 ready: SettledThreadSearch | null,
215 previous: SettledThreadSearch | null,
216): SettledThreadSearch {
217 if (ready !== null) return ready;
218 const current = foldSearchQuery(query);
219 const before = foldSearchQuery(previous?.query ?? "");
220 return previous !== null &&
221 current.length > 0 &&
222 before.length > 0 &&
223 (current.startsWith(before) || before.startsWith(current))
224 ? previous
225 : { query: "", matches: [] };