Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationShellSnapshot,
4 OrchestrationThreadShell,
5 ProjectId,
6 ScopedProjectRef,
7 ScopedThreadRef,
8 ThreadForkOrigin,
9 ThreadId,
10} from "@t3tools/contracts";
11import { Atom } from "effect/unstable/reactivity";
12
13import type { EnvironmentThreadShell } from "./models.ts";
14import { scopeThreadShell } from "./models.ts";
15import type { EnvironmentCatalogState } 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<OrchestrationThreadShell> = Object.freeze([]);
26const EMPTY_ENVIRONMENT_THREADS: ReadonlyArray<EnvironmentThreadShell> = Object.freeze([]);
27const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
28const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationThreadShell> = new Map();
29const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
30 ProjectId,
31 ReadonlyArray<ScopedThreadRef>
32> = new Map();
33const EMPTY_SIDE_CHATS_BY_PARENT: ReadonlyMap<
34 ThreadId,
35 ReadonlyArray<EnvironmentThreadShell>
36> = new Map();
37
38export function isSideChat(shell: OrchestrationThreadShell): boolean {
39 return shell.sideChat === true;
40}
41
42export function forkOrigin(shell: OrchestrationThreadShell): ThreadForkOrigin | null {
43 return shell.fork ?? null;
44}
45
46function isHiddenSideChat(
47 shell: OrchestrationThreadShell,
48 threadIds: Pick<ReadonlyMap<ThreadId, unknown>, "has">,
49): boolean {
50 const origin = forkOrigin(shell);
51 return isSideChat(shell) && origin !== null && threadIds.has(origin.sourceThreadId);
52}
53
54export function createEnvironmentThreadShellAtoms(input: {
55 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
56 readonly snapshotAtom: (
57 environmentId: EnvironmentId,
58 ) => Atom.Atom<OrchestrationShellSnapshot | null>;
59}) {
60 // Point reads and aggregate lists share values without keeping an atom alive
61 // for every listed thread. Replaced source objects can be collected.
62 const scopedThreads = new WeakMap<
63 OrchestrationThreadShell,
64 Map<EnvironmentId, EnvironmentThreadShell>
65 >();
66 const scopedThread = (environmentId: EnvironmentId, thread: OrchestrationThreadShell) => {
67 let byEnvironment = scopedThreads.get(thread);
68 if (byEnvironment === undefined) {
69 byEnvironment = new Map();
70 scopedThreads.set(thread, byEnvironment);
71 }
72 let value = byEnvironment.get(environmentId);
73 if (value === undefined) {
74 value = scopeThreadShell(environmentId, thread);
75 byEnvironment.set(environmentId, value);
76 }
77 return value;
78 };
79
80 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
81 Atom.make(
82 (get): ReadonlyArray<OrchestrationThreadShell> =>
83 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
84 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
85 );
86
87 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
88 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationThreadShell> => {
89 const threads = get(environmentThreadsAtom(environmentId));
90 if (threads.length === 0) {
91 return EMPTY_THREAD_INDEX;
92 }
93 return new Map(threads.map((thread) => [thread.id, thread] as const));
94 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
95 );
96
97 // Every thread the environment owns, side chats included. Ownership checks
98 // (worktree cleanup, membership, outbox routing) must read this list. A side
99 // chat shares its parent's worktree, so omitting it would make that worktree
100 // look orphaned when the parent is deleted.
101 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
102 let previous: ReadonlyArray<ScopedThreadRef> = [];
103 return Atom.make((get) => {
104 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
105 environmentId,
106 threadId: thread.id,
107 }));
108 if (threadRefsEqual(previous, next)) {
109 return previous;
110 }
111 previous = next;
112 return next;
113 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
114 });
115
116 // What thread lists show: side chats stay hidden while their parent exists
117 // and are grouped beside it instead.
118 const environmentVisibleThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
119 let previous: ReadonlyArray<ScopedThreadRef> = [];
120 return Atom.make((get) => {
121 const threadIds = get(environmentThreadIndexAtom(environmentId));
122 const next = get(environmentThreadsAtom(environmentId))
123 .filter((thread) => !isHiddenSideChat(thread, threadIds))
124 .map((thread) => ({
125 environmentId,
126 threadId: thread.id,
127 }));
128 if (threadRefsEqual(previous, next)) {
129 return previous;
130 }
131 previous = next;
132 return next;
133 }).pipe(Atom.withLabel(`environment-visible-thread-refs:${environmentId}`));
134 });
135
136 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
137 let previous: ReadonlyMap<
138 ProjectId,
139 ReadonlyArray<ScopedThreadRef>
140 > = EMPTY_THREAD_REFS_BY_PROJECT;
141 return Atom.make((get) => {
142 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
143 const threadIds = get(environmentThreadIndexAtom(environmentId));
144 for (const thread of get(environmentThreadsAtom(environmentId))) {
145 if (isHiddenSideChat(thread, threadIds)) continue;
146 const refs = grouped.get(thread.projectId);
147 const ref = { environmentId, threadId: thread.id };
148 if (refs === undefined) {
149 grouped.set(thread.projectId, [ref]);
150 } else {
151 refs.push(ref);
152 }
153 }
154 if (grouped.size === 0) {
155 previous = EMPTY_THREAD_REFS_BY_PROJECT;
156 return previous;
157 }
158 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
159 for (const [projectId, refs] of grouped) {
160 const previousRefs = previous.get(projectId);
161 next.set(
162 projectId,
163 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
164 );
165 }
166 const previousProjectIds = [...previous.keys()];
167 if (
168 next.size === previous.size &&
169 [...next].every(
170 ([projectId, refs], index) =>
171 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
172 )
173 ) {
174 return previous;
175 }
176 previous = next;
177 return previous;
178 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
179 });
180
181 const environmentSideChatsByParentAtom = Atom.family((environmentId: EnvironmentId) => {
182 let previous: ReadonlyMap<
183 ThreadId,
184 ReadonlyArray<EnvironmentThreadShell>
185 > = EMPTY_SIDE_CHATS_BY_PARENT;
186 let previousSources: ReadonlyMap<ThreadId, ReadonlyArray<OrchestrationThreadShell>> = new Map();
187 return Atom.make((get): ReadonlyMap<ThreadId, ReadonlyArray<EnvironmentThreadShell>> => {
188 const grouped = new Map<ThreadId, OrchestrationThreadShell[]>();
189 const threadIds = get(environmentThreadIndexAtom(environmentId));
190 for (const thread of get(environmentThreadsAtom(environmentId))) {
191 if (!isHiddenSideChat(thread, threadIds)) continue;
192 const origin = forkOrigin(thread);
193 if (origin === null) continue;
194 const siblings = grouped.get(origin.sourceThreadId);
195 if (siblings === undefined) {
196 grouped.set(origin.sourceThreadId, [thread]);
197 } else {
198 siblings.push(thread);
199 }
200 }
201 if (grouped.size === 0) {
202 previous = EMPTY_SIDE_CHATS_BY_PARENT;
203 previousSources = new Map();
204 return previous;
205 }
206 let unchanged = grouped.size === previous.size;
207 const next = new Map<ThreadId, ReadonlyArray<EnvironmentThreadShell>>();
208 for (const [parentId, threads] of grouped) {
209 const previousThreads = previousSources.get(parentId);
210 const previousScoped = previous.get(parentId);
211 const scoped =
212 previousThreads !== undefined &&
213 previousScoped !== undefined &&
214 arrayElementsEqual(previousThreads, threads)
215 ? previousScoped
216 : threads.map((thread) => scopeThreadShell(environmentId, thread));
217 next.set(parentId, scoped);
218 unchanged &&= scoped === previousScoped;
219 }
220 previousSources = grouped;
221 if (unchanged) {
222 return previous;
223 }
224 previous = next;
225 return previous;
226 }).pipe(Atom.withLabel(`environment-side-chats-by-parent:${environmentId}`));
227 });
228
229 const sideChatsByParentAtomFamily = Atom.family((key: string) => {
230 const ref = parseThreadKey(key);
231 return Atom.make(
232 (get): ReadonlyArray<EnvironmentThreadShell> =>
233 get(environmentSideChatsByParentAtom(ref.environmentId)).get(ref.threadId) ??
234 EMPTY_ENVIRONMENT_THREADS,
235 ).pipe(Atom.withLabel(`side-chats-by-parent:${key}`));
236 });
237
238 const threadShellAtomFamily = Atom.family((key: string) => {
239 const ref = parseThreadKey(key);
240 return Atom.make((get) => {
241 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
242 return source === null ? null : scopedThread(ref.environmentId, source);
243 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
244 });
245
246 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
247 const projectRefs = parseProjectRefCollectionKey(key);
248 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
249 return Atom.make((get) => {
250 const next: EnvironmentThreadShell[] = [];
251 const seen = new Set<string>();
252 for (const projectRef of projectRefs) {
253 const refs =
254 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
255 projectRef.projectId,
256 ) ?? EMPTY_SCOPED_THREAD_REFS;
257 if (refs.length === 0) continue;
258 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
259 for (const ref of refs) {
260 const key = threadKey(ref);
261 if (seen.has(key)) {
262 continue;
263 }
264 seen.add(key);
265 const thread = threads.get(ref.threadId);
266 if (thread !== undefined) {
267 next.push(scopedThread(ref.environmentId, thread));
268 }
269 }
270 }
271 if (arrayElementsEqual(previous, next)) {
272 return previous;
273 }
274 previous = next;
275 return previous;
276 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
277 });
278
279 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
280 const threadRefsAtom = Atom.make((get) => {
281 const refs: ScopedThreadRef[] = [];
282 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
283 refs.push(...get(environmentThreadRefsAtom(environmentId)));
284 }
285 if (threadRefsEqual(previousThreadRefs, refs)) {
286 return previousThreadRefs;
287 }
288 previousThreadRefs = refs;
289 return refs;
290 }).pipe(Atom.withLabel("environment-thread-refs"));
291
292 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
293 const threadShellsAtom = Atom.make((get) => {
294 const next: EnvironmentThreadShell[] = [];
295 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
296 for (const thread of get(environmentThreadsAtom(environmentId))) {
297 next.push(scopedThread(environmentId, thread));
298 }
299 }
300 if (arrayElementsEqual(previousThreadShells, next)) {
301 return previousThreadShells;
302 }
303 previousThreadShells = next;
304 return previousThreadShells;
305 }).pipe(Atom.withLabel("environment-thread-shell-list"));
306
307 // The list a thread picker or sidebar renders: `threadShellsAtom` minus side
308 // chats whose parent is still present.
309 let previousVisibleThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
310 const visibleThreadShellsAtom = Atom.make((get) => {
311 const next: EnvironmentThreadShell[] = [];
312 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
313 const threadIds = get(environmentThreadIndexAtom(environmentId));
314 for (const thread of get(environmentThreadsAtom(environmentId))) {
315 if (isHiddenSideChat(thread, threadIds)) continue;
316 next.push(scopedThread(environmentId, thread));
317 }
318 }
319 if (arrayElementsEqual(previousVisibleThreadShells, next)) {
320 return previousVisibleThreadShells;
321 }
322 previousVisibleThreadShells = next;
323 return previousVisibleThreadShells;
324 }).pipe(Atom.withLabel("environment-visible-thread-shell-list"));
325
326 return {
327 environmentThreadsAtom,
328 environmentThreadIndexAtom,
329 environmentThreadRefsAtom,
330 environmentVisibleThreadRefsAtom,
331 environmentThreadRefsByProjectAtom,
332 environmentSideChatsByParentAtom,
333 threadRefsAtom,
334 threadShellsAtom,
335 visibleThreadShellsAtom,
336 sideChatsByParentAtom: (ref: ScopedThreadRef) => sideChatsByParentAtomFamily(threadKey(ref)),
337 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
338 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
339 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
340 };
341}