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

threadShell.ts

290 lines11.1 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​
33// An async question outlives the subagent's run, but once that run ends the
34// parent is no longer waiting on the answer, so it stops counting as input.
35// The activity run stays set when a follow-up is queued behind a blocked run;
36// older servers omit it, so fall back to the latest run's status.
37const isChildRunLive = (
38 thread: Pick<OrchestrationV2ThreadShell, "activityRunStatus" | "status">,
39) =>
40 thread.activityRunStatus !== undefined
41 ? thread.activityRunStatus !== null
42 : thread.status === "preparing" ||
43 thread.status === "starting" ||
44 thread.status === "running" ||
45 thread.status === "waiting";
46​
47export function createEnvironmentThreadShellAtoms(input: {
48 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
49 readonly snapshotAtom: (
50 environmentId: EnvironmentId,
51 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
52}) {
53 // Point reads and aggregate lists share values without keeping an atom alive
54 // for every listed thread. Replaced source objects can be collected.
55 const scopedThreads = new WeakMap<
56 OrchestrationV2ThreadShell,
57 Map<EnvironmentId, EnvironmentThreadShell>
58 >();
59 const scopedThread = (environmentId: EnvironmentId, thread: OrchestrationV2ThreadShell) => {
60 let byEnvironment = scopedThreads.get(thread);
61 if (byEnvironment === undefined) {
62 byEnvironment = new Map();
63 scopedThreads.set(thread, byEnvironment);
64 }
65 let value = byEnvironment.get(environmentId);
66 if (value === undefined) {
67 value = presentThreadShell(environmentId, thread);
68 byEnvironment.set(environmentId, value);
69 }
70 return value;
71 };
72​
73 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
74 Atom.make(
75 (get): ReadonlyArray<OrchestrationV2ThreadShell> =>
76 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
77 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
78 );
79​
80 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
81 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
82 const threads = get(environmentThreadsAtom(environmentId));
83 if (threads.length === 0) {
84 return EMPTY_THREAD_INDEX;
85 }
86 return new Map(threads.map((thread) => [thread.id, thread] as const));
87 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
88 );
89​
90 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
91 let previous: ReadonlyArray<ScopedThreadRef> = [];
92 return Atom.make((get) => {
93 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
94 environmentId,
95 threadId: thread.id,
96 }));
97 if (threadRefsEqual(previous, next)) {
98 return previous;
99 }
100 previous = next;
101 return next;
102 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
103 });
104​
105 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
106 let previous: ReadonlyMap<
107 ProjectId,
108 ReadonlyArray<ScopedThreadRef>
109 > = EMPTY_THREAD_REFS_BY_PROJECT;
110 return Atom.make((get) => {
111 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
112 for (const thread of get(environmentThreadsAtom(environmentId))) {
113 const refs = grouped.get(thread.projectId);
114 const ref = { environmentId, threadId: thread.id };
115 if (refs === undefined) {
116 grouped.set(thread.projectId, [ref]);
117 } else {
118 refs.push(ref);
119 }
120 }
121 if (grouped.size === 0) {
122 previous = EMPTY_THREAD_REFS_BY_PROJECT;
123 return previous;
124 }
125 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
126 for (const [projectId, refs] of grouped) {
127 const previousRefs = previous.get(projectId);
128 next.set(
129 projectId,
130 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
131 );
132 }
133 const previousProjectIds = [...previous.keys()];
134 if (
135 next.size === previous.size &&
136 [...next].every(
137 ([projectId, refs], index) =>
138 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
139 )
140 ) {
141 return previous;
142 }
143 previous = next;
144 return previous;
145 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
146 });
147​
148 const threadShellAtomFamily = Atom.family((key: string) => {
149 const ref = parseThreadKey(key);
150 return Atom.make((get) => {
151 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
152 return source === null ? null : scopedThread(ref.environmentId, source);
153 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
154 });
155​
156 // Child questions are hidden with their sidebar rows. Read their shell summaries,
157 // without subscribing to every child transcript.
158 const childThreadInputsAtomFamily = Atom.family((key: string) => {
159 const ref = parseThreadKey(key);
160 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
161 return Atom.make((get) => {
162 const children = new Map<ThreadId, OrchestrationV2ThreadShell[]>();
163 for (const thread of get(environmentThreadsAtom(ref.environmentId))) {
164 const parent = thread.lineage.parentThreadId;
165 if (parent === null || thread.lineage.relationshipToParent !== "subagent") continue;
166 const siblings = children.get(parent);
167 if (siblings) siblings.push(thread);
168 else children.set(parent, [thread]);
169 }
170 const seen = new Set<ThreadId>([ref.threadId]);
171 const pending = [ref.threadId];
172 const next: EnvironmentThreadShell[] = [];
173 for (const parent of pending) {
174 for (const child of children.get(parent) ?? []) {
175 if (seen.has(child.id)) continue;
176 seen.add(child.id);
177 pending.push(child.id);
178 if (
179 child.pendingRuntimeRequest?.kind === "user_input" &&
180 isChildRunLive(child) &&
181 !isProviderNativeSubagentThread(child)
182 ) {
183 next.push(scopedThread(ref.environmentId, child));
184 }
185 }
186 }
187 // Indicators read only ids and titles, so other shell updates keep the old array.
188 if (
189 previous.length === next.length &&
190 previous.every(
191 (thread, index) => thread.id === next[index]?.id && thread.title === next[index]?.title,
192 )
193 ) {
194 return previous;
195 }
196 previous = next;
197 return next;
198 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
199 });
200​
201 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
202 const projectRefs = parseProjectRefCollectionKey(key);
203 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
204 return Atom.make((get) => {
205 const next: EnvironmentThreadShell[] = [];
206 const seen = new Set<string>();
207 for (const projectRef of projectRefs) {
208 const refs =
209 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
210 projectRef.projectId,
211 ) ?? EMPTY_SCOPED_THREAD_REFS;
212 if (refs.length === 0) continue;
213 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
214 for (const ref of refs) {
215 const key = threadKey(ref);
216 if (seen.has(key)) {
217 continue;
218 }
219 seen.add(key);
220 const thread = threads.get(ref.threadId);
221 if (thread !== undefined) {
222 next.push(scopedThread(ref.environmentId, thread));
223 }
224 }
225 }
226 if (arrayElementsEqual(previous, next)) {
227 return previous;
228 }
229 previous = next;
230 return previous;
231 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
232 });
233​
234 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
235 const threadRefsAtom = Atom.make((get) => {
236 const refs: ScopedThreadRef[] = [];
237 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
238 refs.push(...get(environmentThreadRefsAtom(environmentId)));
239 }
240 if (threadRefsEqual(previousThreadRefs, refs)) {
241 return previousThreadRefs;
242 }
243 previousThreadRefs = refs;
244 return refs;
245 }).pipe(Atom.withLabel("environment-thread-refs"));
246​
247 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
248 const threadShellsAtom = 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 next.push(scopedThread(environmentId, thread));
253 }
254 }
255 if (arrayElementsEqual(previousThreadShells, next)) {
256 return previousThreadShells;
257 }
258 previousThreadShells = next;
259 return previousThreadShells;
260 }).pipe(Atom.withLabel("environment-thread-shell-list"));
261​
262 let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];
263 const navigationThreadShellsAtom = Atom.make((get) => {
264 const next: EnvironmentThreadShell[] = [];
265 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
266 for (const thread of get(environmentThreadsAtom(environmentId))) {
267 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
268 continue;
269 next.push(scopedThread(environmentId, thread));
270 }
271 }
272 if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells;
273 previousNavigationShells = next;
274 return next;
275 }).pipe(Atom.withLabel("environment-navigation-thread-shells"));
276​
277 return {
278 environmentThreadsAtom,
279 environmentThreadIndexAtom,
280 environmentThreadRefsAtom,
281 environmentThreadRefsByProjectAtom,
282 threadRefsAtom,
283 threadShellsAtom,
284 navigationThreadShellsAtom,
285 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
286 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
287 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
288 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
289 };