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