Open History to see the last commit
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/unstable/reactivity";
10
11export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchMatch {
12 readonly environmentId: EnvironmentId;
13}
14
15export interface ThreadSearchResultsState {
16 readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
17 readonly isLoading: boolean;
18}
19
20const ThreadSearchKey = Schema.Tuple([
21 Schema.Array(EnvironmentId),
22 OrchestrationSearchThreadsInput.fields.query,
23]);
24const decodeThreadSearchKey = Schema.decodeUnknownSync(ThreadSearchKey);
25
26export function makeThreadSearchKey(
27 environmentIds: ReadonlyArray<EnvironmentId>,
28 query: string,
29): string {
30 return JSON.stringify([
31 [...environmentIds].sort((left, right) => left.localeCompare(right)),
32 query,
33 ]);
34}
35
36function parseThreadSearchKey(key: string) {
37 return decodeThreadSearchKey(JSON.parse(key));
38}
39
40export function threadSearchMatchKey(
41 match: Pick<EnvironmentThreadSearchMatch, "environmentId" | "threadId">,
42): string {
43 return JSON.stringify([match.environmentId, match.threadId]);
44}
45
46/**
47 * Combines one search query atom per environment. Failed and disconnected
48 * environments contribute no content matches, preserving local title search
49 * as the compatibility fallback.
50 */
51export function createThreadSearchResultsAtomFamily<E>(options: {
52 readonly getSearchAtom: (
53 environmentId: EnvironmentId,
54 query: string,
55 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationSearchThreadsResult, E>>;
56 readonly labelPrefix: string;
57}) {
58 return Atom.family((key: string) =>
59 Atom.make((get): ThreadSearchResultsState => {
60 const [environmentIds, query] = parseThreadSearchKey(key);
61 const matches: EnvironmentThreadSearchMatch[] = [];
62 let isLoading = false;
63
64 for (const environmentId of environmentIds) {
65 const result = get(options.getSearchAtom(environmentId, query));
66 isLoading ||= result.waiting;
67 const value = Option.getOrNull(AsyncResult.value(result));
68 if (value !== null) {
69 matches.push(
70 ...value.matches.map((match) => ({
71 ...match,
72 environmentId,
73 })),
74 );
75 }
76 }
77
78 return { matches, isLoading };
79 }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)),
80 );
81}