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

threadShell.ts

275 lines10.4 KB

1import type {
2 EnvironmentId,
3 OrchestrationV2ShellSnapshot,
4 OrchestrationV2ThreadShell,
5 ProjectId,
6 ScopedProjectRef,
7 ScopedThreadRef,
8 ThreadId,
9} from "@t3tools/contracts";
10import { isProviderNativeSubagentThread } from "@t3tools/contracts";
11import { Atom } from "effect/reactivity";
12​
13import type { EnvironmentThreadShell } from "./models.ts";
14import { presentThreadShell } from "./models.ts";
15import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
16import {
17 arrayElementsEqual,
18 parseProjectRefCollectionKey,
19 parseThreadKey,
20 projectRefCollectionKey,
21 threadKey,
22 threadRefsEqual,
23} from "./entities.ts";
24​
25const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([]);
26const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
27const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();
28const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
29 ProjectId,
30 ReadonlyArray<ScopedThreadRef>
31> = new Map();
32​
33export function createEnvironmentThreadShellAtoms(input: {
34 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
35 readonly snapshotAtom: (
36 environmentId: EnvironmentId,
37 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
38}) {
39 // Point reads and aggregate lists share values without keeping an atom alive
40 // for every listed thread. Replaced source objects can be collected.
41 const scopedThreads = new WeakMap<
42 OrchestrationV2ThreadShell,
43 Map<EnvironmentId, EnvironmentThreadShell>
44 >();
45 const scopedThread = (environmentId: EnvironmentId, thread: OrchestrationV2ThreadShell) => {
46 let byEnvironment = scopedThreads.get(thread);
47 if (byEnvironment === undefined) {
48 byEnvironment = new Map();
49 scopedThreads.set(thread, byEnvironment);
50 }
51 let value = byEnvironment.get(environmentId);
52 if (value === undefined) {
53 value = presentThreadShell(environmentId, thread);
54 byEnvironment.set(environmentId, value);
55 }
56 return value;
57 };
58​
59 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
60 Atom.make(
61 (get): ReadonlyArray<OrchestrationV2ThreadShell> =>
62 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
63 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
64 );
65​
66 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
67 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
68 const threads = get(environmentThreadsAtom(environmentId));
69 if (threads.length === 0) {
70 return EMPTY_THREAD_INDEX;
71 }
72 return new Map(threads.map((thread) => [thread.id, thread] as const));
73 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
74 );
75​
76 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
77 let previous: ReadonlyArray<ScopedThreadRef> = [];
78 return Atom.make((get) => {
79 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
80 environmentId,
81 threadId: thread.id,
82 }));
83 if (threadRefsEqual(previous, next)) {
84 return previous;
85 }
86 previous = next;
87 return next;
88 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
89 });
90​
91 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
92 let previous: ReadonlyMap<
93 ProjectId,
94 ReadonlyArray<ScopedThreadRef>
95 > = EMPTY_THREAD_REFS_BY_PROJECT;
96 return Atom.make((get) => {
97 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
98 for (const thread of get(environmentThreadsAtom(environmentId))) {
99 const refs = grouped.get(thread.projectId);
100 const ref = { environmentId, threadId: thread.id };
101 if (refs === undefined) {
102 grouped.set(thread.projectId, [ref]);
103 } else {
104 refs.push(ref);
105 }
106 }
107 if (grouped.size === 0) {
108 previous = EMPTY_THREAD_REFS_BY_PROJECT;
109 return previous;
110 }
111 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
112 for (const [projectId, refs] of grouped) {
113 const previousRefs = previous.get(projectId);
114 next.set(
115 projectId,
116 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
117 );
118 }
119 const previousProjectIds = [...previous.keys()];
120 if (
121 next.size === previous.size &&
122 [...next].every(
123 ([projectId, refs], index) =>
124 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
125 )
126 ) {
127 return previous;
128 }
129 previous = next;
130 return previous;
131 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
132 });
133​
134 const threadShellAtomFamily = Atom.family((key: string) => {
135 const ref = parseThreadKey(key);
136 return Atom.make((get) => {
137 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
138 return source === null ? null : scopedThread(ref.environmentId, source);
139 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
140 });
141​
142 // Child questions are hidden with their sidebar rows. Read their shell summaries,
143 // without subscribing to every child transcript.
144 const childThreadInputsAtomFamily = Atom.family((key: string) => {
145 const ref = parseThreadKey(key);
146 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
147 return Atom.make((get) => {
148 const children = new Map<ThreadId, OrchestrationV2ThreadShell[]>();
149 for (const thread of get(environmentThreadsAtom(ref.environmentId))) {
150 const parent = thread.lineage.parentThreadId;
151 if (parent === null || thread.lineage.relationshipToParent !== "subagent") continue;
152 const siblings = children.get(parent);
153 if (siblings) siblings.push(thread);
154 else children.set(parent, [thread]);
155 }
156 const seen = new Set<ThreadId>([ref.threadId]);
157 const pending = [ref.threadId];
158 const next: EnvironmentThreadShell[] = [];
159 for (const parent of pending) {
160 for (const child of children.get(parent) ?? []) {
161 if (seen.has(child.id)) continue;
162 seen.add(child.id);
163 pending.push(child.id);
164 if (
165 child.pendingRuntimeRequest?.kind === "user_input" &&
166 !isProviderNativeSubagentThread(child)
167 ) {
168 next.push(scopedThread(ref.environmentId, child));
169 }
170 }
171 }
172 // Indicators read only ids and titles, so other shell updates keep the old array.
173 if (
174 previous.length === next.length &&
175 previous.every(
176 (thread, index) => thread.id === next[index]?.id && thread.title === next[index]?.title,
177 )
178 ) {
179 return previous;
180 }
181 previous = next;
182 return next;
183 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
184 });
185​
186 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
187 const projectRefs = parseProjectRefCollectionKey(key);
188 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
189 return Atom.make((get) => {
190 const next: EnvironmentThreadShell[] = [];
191 const seen = new Set<string>();
192 for (const projectRef of projectRefs) {
193 const refs =
194 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
195 projectRef.projectId,
196 ) ?? EMPTY_SCOPED_THREAD_REFS;
197 if (refs.length === 0) continue;
198 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
199 for (const ref of refs) {
200 const key = threadKey(ref);
201 if (seen.has(key)) {
202 continue;
203 }
204 seen.add(key);
205 const thread = threads.get(ref.threadId);
206 if (thread !== undefined) {
207 next.push(scopedThread(ref.environmentId, thread));
208 }
209 }
210 }
211 if (arrayElementsEqual(previous, next)) {
212 return previous;
213 }
214 previous = next;
215 return previous;
216 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
217 });
218​
219 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
220 const threadRefsAtom = Atom.make((get) => {
221 const refs: ScopedThreadRef[] = [];
222 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
223 refs.push(...get(environmentThreadRefsAtom(environmentId)));
224 }
225 if (threadRefsEqual(previousThreadRefs, refs)) {
226 return previousThreadRefs;
227 }
228 previousThreadRefs = refs;
229 return refs;
230 }).pipe(Atom.withLabel("environment-thread-refs"));
231​
232 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
233 const threadShellsAtom = Atom.make((get) => {
234 const next: EnvironmentThreadShell[] = [];
235 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
236 for (const thread of get(environmentThreadsAtom(environmentId))) {
237 next.push(scopedThread(environmentId, thread));
238 }
239 }
240 if (arrayElementsEqual(previousThreadShells, next)) {
241 return previousThreadShells;
242 }
243 previousThreadShells = next;
244 return previousThreadShells;
245 }).pipe(Atom.withLabel("environment-thread-shell-list"));
246​
247 let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];
248 const navigationThreadShellsAtom = Atom.make((get) => {
249 const next: EnvironmentThreadShell[] = [];
250 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
251 for (const thread of get(environmentThreadsAtom(environmentId))) {
252 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
253 continue;
254 next.push(scopedThread(environmentId, thread));
255 }
256 }
257 if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells;
258 previousNavigationShells = next;
259 return next;
260 }).pipe(Atom.withLabel("environment-navigation-thread-shells"));
261​
262 return {
263 environmentThreadsAtom,
264 environmentThreadIndexAtom,
265 environmentThreadRefsAtom,
266 environmentThreadRefsByProjectAtom,
267 threadRefsAtom,
268 threadShellsAtom,
269 navigationThreadShellsAtom,
270 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
271 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
272 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
273 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
274 };