The best way to control Claude Code, Codex and more from any computer or phone

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