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

threadSearch.ts

229 lines7.9 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 * The order to show message results in, and how many: rows already shown for
170 * this query keep their places, and results that arrive later, from a slower
171 * environment, go below them with up to LATE_ROOM rows past `limit`. Nothing
172 * moves under the pointer or the keyboard highlight, and a late best match
173 * still shows. Returns `previous` when nothing changed, so it can sit in React
174 * state.
175 */
176export function nextShownOrder(
177 previous: ShownOrder | null,
178 query: string,
179 ranked: ReadonlyArray<string>,
180 limit: number,
181): ShownOrder {
182 if (previous?.query !== query) {
183 return { query, keys: ranked, shown: Math.min(limit, ranked.length) };
184 }
185 const listed = new Set(ranked);
186 const kept = previous.keys.slice(0, previous.shown).filter((key) => listed.has(key));
187 const held = new Set(kept);
188 const seen = new Set(previous.keys);
189 const rest = ranked.filter((key) => !held.has(key));
190 const arrived = rest.filter((key) => !seen.has(key)).length;
191 const keys = [...kept, ...rest];
192 const shown = Math.min(
193 keys.length,
194 limit + LATE_ROOM,
195 Math.max(limit, kept.length + Math.min(arrived, LATE_ROOM)),
196 );
197 const unchanged =
198 shown === previous.shown &&
199 keys.length === previous.keys.length &&
200 keys.every((key, index) => key === previous.keys[index]);
201 return unchanged ? previous : { query, keys, shown };
203​
204export interface SettledThreadSearch {
205 readonly query: string;
206 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
208​
209/**
210 * What a search box shows for `query`: its own results once they arrive
211 * (`ready`), else the previous results if `query` refines or widens their
212 * query, so result rows do not blink out and back on every keystroke.
213 * Results for an unrelated query clear.
214 */
215export function visibleThreadSearch(
216 query: string,
217 ready: SettledThreadSearch | null,
218 previous: SettledThreadSearch | null,
219): SettledThreadSearch {
220 if (ready !== null) return ready;
221 const current = foldSearchQuery(query);
222 const before = foldSearchQuery(previous?.query ?? "");
223 return previous !== null &&
224 current.length > 0 &&
225 before.length > 0 &&
226 (current.startsWith(before) || before.startsWith(current))
227 ? previous
228 : { query: "", matches: [] };