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

threadFamilies.ts

224 lines9.6 KB

1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ThreadFamily,
6 type OrchestrationV2ThreadShell,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as SubscriptionRef from "effect/SubscriptionRef";
12import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
13​
14import * as EnvironmentSupervisor from "../connection/supervisor.ts";
15import type * as EnvironmentRegistry from "../connection/registry.ts";
16import { EnvironmentRpcUnavailableError, request } from "../rpc/client.ts";
17import { arrayElementsEqual } from "./entities.ts";
18import { createEnvironmentQueryAtomFamily, selectEnvironmentQueryData } from "./runtime.ts";
19import type { EnvironmentShellState } from "./shell.ts";
20​
21const EMPTY_FAMILY: OrchestrationV2ThreadFamily = { snapshotSequence: 0, threads: [] };
22const EMPTY_MOUNTS: ReadonlyMap<ThreadId, number> = new Map();
23// Generation 0 is the cached shell from before this session's first authoritative snapshot. A read
24// for it would be thrown away once that snapshot lands, so it waits instead.
25const AWAITING_AUTHORITATIVE_SHELL = AsyncResult.initial<never, never>(true);
26​
27/** Whether a family read can decide anything yet. Only a settled read can prove a thread is gone. */
28export type ThreadFamilyRead = "pending" | "failed" | "settled";
29​
30export function threadFamilyRead(
31 result: AsyncResult.AsyncResult<OrchestrationV2ThreadFamily, unknown>,
32): ThreadFamilyRead {
33 // A failure whose retry is in flight is pending, so callers do not restart that retry.
34 if (result.waiting) return "pending";
35 if (AsyncResult.isFailure(result)) return "failed";
36 return AsyncResult.isSuccess(result) ? "settled" : "pending";
38​
39/**
40 * Family rows the shell does not have. A shell row is at least as new as any family copy, since
41 * shell deltas carry every change; a family copy read before the shell removed that thread is
42 * stale.
43 */
44export function threadFamilyRowsMissingFromShell(input: {
45 readonly shellThreads: ReadonlyArray<OrchestrationV2ThreadShell>;
46 readonly families: ReadonlyArray<OrchestrationV2ThreadFamily>;
47 readonly removedAt: ReadonlyMap<ThreadId, number>;
48}): ReadonlyArray<OrchestrationV2ThreadShell> {
49 const present = new Set<ThreadId>(input.shellThreads.map((thread) => thread.id));
50 const missing: OrchestrationV2ThreadShell[] = [];
51 for (const family of input.families) {
52 for (const thread of family.threads) {
53 if (present.has(thread.id)) continue;
54 if ((input.removedAt.get(thread.id) ?? -1) > family.snapshotSequence) continue;
55 present.add(thread.id);
56 missing.push(thread);
57 }
58 }
59 return missing;
61​
62/**
63 * Shells with `omitIdleSubagents` leave idle children to families: the subagent tree sharing a
64 * `lineage.rootThreadId`, read once per shell generation and never persisted. Family rows merge
65 * behind shell rows; shell deltas still carry every change, so a changed child's shell row wins.
66 */
67export function createThreadFamilyAtoms<R, ER, E>(
68 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
69 shellStateAtom: (
70 environmentId: EnvironmentId,
71 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
72) {
73 const shellStateValue = (state: AsyncResult.AsyncResult<EnvironmentShellState, E>) =>
74 Option.getOrNull(AsyncResult.value(state));
75 const generationAtom = Atom.family((environmentId: EnvironmentId) =>
76 Atom.make((get) => shellStateValue(get(shellStateAtom(environmentId)))?.generation ?? 0).pipe(
77 Atom.withLabel(`environment-shell-generation:${environmentId}`),
78 ),
79 );
80​
81 // The generation is part of the key, so a read from before the latest authoritative snapshot is
82 // never used again, even while a new read is pending or failed.
83 const familyQueryAtom = createEnvironmentQueryAtomFamily(runtime, {
84 label: "environment-data:orchestration:thread-family",
85 staleTimeMs: Number.POSITIVE_INFINITY,
86 idleTtlMs: 60_000,
87 execute: Effect.fn("ThreadFamilies.read")(function* (input: {
88 readonly threadId: ThreadId;
89 readonly generation: number;
90 }) {
91 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
92 const session = yield* SubscriptionRef.get(supervisor.session);
93 if (Option.isNone(session)) {
94 return yield* new EnvironmentRpcUnavailableError({
95 environmentId: supervisor.target.environmentId,
96 message: "The environment has no session.",
97 });
98 }
99 // A config failure fails the read: an empty family would read as "the thread is gone".
100 const config = yield* session.value.initialConfig;
101 // Servers without families send every child in the shell, so absent means gone.
102 if (config.shellThreadFamilies !== true) return EMPTY_FAMILY;
103 return yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, {
104 threadId: input.threadId,
105 });
106 }),
107 });
108 const queryFor = (environmentId: EnvironmentId, threadId: ThreadId, generation: number) =>
109 familyQueryAtom({ environmentId, input: { threadId, generation } });
110​
111 const familyAtom = Atom.family((key: string) => {
112 const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId];
113 return Atom.make((get) => {
114 const generation = get(generationAtom(environmentId));
115 return generation === 0
116 ? AWAITING_AUTHORITATIVE_SHELL
117 : get(queryFor(environmentId, threadId, generation));
118 }).pipe(Atom.withLabel(`environment-thread-family:${key}`));
119 });
120 const familyKey = (environmentId: EnvironmentId, threadId: ThreadId) =>
121 JSON.stringify([environmentId, threadId]);
122​
123 /** Reads the current generation's family again, so a failed read does not last the session. */
124 const refresh = (
125 registry: AtomRegistry.AtomRegistry,
126 environmentId: EnvironmentId,
127 threadId: ThreadId,
128 ) => {
129 const generation = registry.get(generationAtom(environmentId));
130 if (generation !== 0) registry.refresh(queryFor(environmentId, threadId, generation));
131 };
132​
133 const mountsAtom = Atom.family((environmentId: EnvironmentId) =>
134 Atom.make(EMPTY_MOUNTS).pipe(
135 Atom.keepAlive,
136 Atom.withLabel(`environment-thread-family-mounts:${environmentId}`),
137 ),
138 );
139​
140 /** Keeps a thread's family in the merged rows until the returned release runs. */
141 const mount = (
142 registry: AtomRegistry.AtomRegistry,
143 environmentId: EnvironmentId,
144 threadId: ThreadId,
145 ): (() => void) => {
146 const atom = mountsAtom(environmentId);
147 const mounts = registry.get(atom);
148 registry.set(atom, new Map(mounts).set(threadId, (mounts.get(threadId) ?? 0) + 1));
149 // Mounting again after a failure retries instead of keeping the failure until reconnect.
150 if (
151 threadFamilyRead(registry.get(familyAtom(familyKey(environmentId, threadId)))) === "failed"
152 ) {
153 refresh(registry, environmentId, threadId);
154 }
155 let released = false;
156 return () => {
157 if (released) return;
158 released = true;
159 const next = new Map(registry.get(atom));
160 const count = (next.get(threadId) ?? 0) - 1;
161 if (count > 0) next.set(threadId, count);
162 else next.delete(threadId);
163 registry.set(atom, next);
164 };
165 };
166​
167 const snapshotAtom = Atom.family((environmentId: EnvironmentId) => {
168 let previous: {
169 readonly snapshot: OrchestrationV2ShellSnapshot;
170 readonly removedAt: ReadonlyMap<ThreadId, number>;
171 readonly families: ReadonlyArray<OrchestrationV2ThreadFamily>;
172 readonly merged: OrchestrationV2ShellSnapshot;
173 } | null = null;
174 return Atom.make((get): OrchestrationV2ShellSnapshot | null => {
175 const state = shellStateValue(get(shellStateAtom(environmentId)));
176 const snapshot = state === null ? null : Option.getOrNull(state.snapshot);
177 const mounts = get(mountsAtom(environmentId));
178 if (snapshot === null || state === null || mounts.size === 0) return snapshot;
179 const families = [...mounts.keys()].flatMap((threadId) => {
180 const family = selectEnvironmentQueryData(
181 get(familyAtom(familyKey(environmentId, threadId))),
182 );
183 return family === null ? [] : [family];
184 });
185 // Most shell updates move only the cursor. With the same rows, removals and families, keep
186 // the merged rows so thread lists skip their rebuild.
187 const unchanged =
188 previous !== null &&
189 previous.snapshot.threads === snapshot.threads &&
190 previous.removedAt === state.removedAt &&
191 arrayElementsEqual(previous.families, families);
192 if (unchanged && previous !== null && previous.snapshot === snapshot) return previous.merged;
193 let merged: OrchestrationV2ShellSnapshot;
194 if (unchanged && previous !== null) {
195 merged =
196 previous.merged === previous.snapshot
197 ? snapshot
198 : { ...snapshot, threads: previous.merged.threads };
199 } else {
200 const extras = threadFamilyRowsMissingFromShell({
201 shellThreads: snapshot.threads,
202 removedAt: state.removedAt,
203 families,
204 });
205 merged =
206 extras.length === 0
207 ? snapshot
208 : { ...snapshot, threads: [...snapshot.threads, ...extras] };
209 }
210 previous = { snapshot, removedAt: state.removedAt, families, merged };
211 return merged;
212 }).pipe(Atom.withLabel(`environment-snapshot-with-families:${environmentId}`));
213 });
214​
215 return {
216 /** The shell snapshot plus the rows of every mounted family. */
217 snapshotAtom,
218 /** The current generation's family read, for decisions that need a settled answer. */
219 familyAtom: (environmentId: EnvironmentId, threadId: ThreadId) =>
220 familyAtom(familyKey(environmentId, threadId)),
221 mount,
222 refresh,
223 };