Open History to see the last commit
1import {
2 isOlderSettledThreadShell,
3 ORCHESTRATION_V2_WS_METHODS,
4 type EnvironmentId,
5 type OrchestrationV2OlderSettledCursor,
6 type OrchestrationV2OlderSettledThreadsPage,
7 type OrchestrationV2SearchThreadsInput,
8 type OrchestrationV2ThreadFamily,
9 type OrchestrationV2ThreadShell,
10 type ProjectId,
11 type ThreadId,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
17
18import type * as EnvironmentRegistry from "../connection/registry.ts";
19import { request } from "../rpc/client.ts";
20import { createEnvironmentQueryAtomFamily, selectEnvironmentQueryData } from "./runtime.ts";
21import type { EnvironmentShellState } from "./shell.ts";
22import { threadFamilyRead } from "./threadFamilies.ts";
23
24// Rows per page of older settled threads: one "Show more" step of the Settled shelf.
25const OLDER_SETTLED_PAGE_SIZE = 25;
26// A burst of changes (a PR sync touching many old threads) costs one count read.
27const COUNT_REREAD_DELAY = "500 millis";
28
29/** Where an environment's shell cut settled threads, and how many are older per project. */
30export interface OlderSettled {
31 readonly before: string;
32 readonly beforeMs: number;
33 readonly counts: ReadonlyMap<ProjectId, number>;
34}
35
36/** The scope's projects in one environment, or null for all of them. */
37export interface OlderSettledScope {
38 readonly environmentId: EnvironmentId;
39 readonly projectIds: ReadonlyArray<ProjectId> | null;
40}
41
42/**
43 * The pages read below an environment's cut. Everything at or above `frontier` is local: pages
44 * hold the rows that were there when read, and shell deltas keep that range current. A null
45 * frontier means no more can load: every older thread is loaded, or this session has no snapshot.
46 */
47export interface OlderSettledPages {
48 readonly reads: ReadonlyArray<OrchestrationV2ThreadFamily>;
49 readonly frontier: OrchestrationV2OlderSettledCursor | null;
50 readonly status: "ready" | "pending" | "failed";
51}
52
53const NO_PAGES: OlderSettledPages = { reads: [], frontier: null, status: "ready" };
54
55type OlderSettledRow = Pick<
56 OrchestrationV2ThreadShell,
57 "id" | "projectId" | "lineage" | "settledOverride" | "settledAt"
58>;
59
60export interface OlderSettledShelfEnvironment {
61 readonly older: OlderSettled | null;
62 readonly pages: OlderSettledPages;
63}
64
65/**
66 * Changes whenever the older count can: any removal (by largest sequence, so a repeat counts), an
67 * older row that arrives or changes, or an old row arriving outside the set (unsettled). Threads
68 * created after the cut never enter it, as threads settle after creation. Archived-thread events
69 * arrive as removals too, each costing one count read.
70 */
71export function olderSettledCountKey(
72 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
73 beforeMs: number,
74 removedAt: ReadonlyMap<ThreadId, number>,
75): string {
76 let lastRemoval = 0;
77 for (const sequence of removedAt.values()) lastRemoval = Math.max(lastRemoval, sequence);
78 const rows: string[] = [];
79 for (const thread of threads) {
80 if (thread.lineage.relationshipToParent === "subagent") continue;
81 const older = isOlderSettledThreadShell(thread, beforeMs);
82 if (older || DateTime.toEpochMillis(thread.createdAt) < beforeMs) {
83 rows.push(`${thread.id}:${older ? 1 : 0}`);
84 }
85 }
86 return `${lastRemoval}|${rows.sort().join(",")}`;
87}
88
89/** Whether a row sits at or above a page cursor in the server's order (settle time desc, id asc). */
90function atOrAboveCursor(
91 thread: Pick<OrchestrationV2ThreadShell, "id" | "settledAt">,
92 cursor: OrchestrationV2OlderSettledCursor,
93): boolean {
94 if (thread.settledAt === null) return true;
95 const settledAt = DateTime.formatIso(thread.settledAt);
96 return !(
97 settledAt < cursor.settledAt ||
98 (cursor.threadId !== undefined && settledAt === cursor.settledAt && thread.id > cursor.threadId)
99 );
100}
101
102/**
103 * Where a shelf over these environments stops listing: the highest frontier of any environment
104 * that can still load older threads (its cut until its first page). Rows below it could sort under
105 * rows not loaded yet, so the merged list is a correct prefix even while a page loads. A failed
106 * environment holds no one back; its Retry rejoins it.
107 */
108export function settledShelfFrontier(
109 environments: ReadonlyArray<OlderSettledShelfEnvironment>,
110): OrchestrationV2OlderSettledCursor | null {
111 let highest: OrchestrationV2OlderSettledCursor | null = null;
112 for (const { older, pages } of environments) {
113 if (older === null || pages.frontier === null || pages.status === "failed") continue;
114 const frontier = pages.frontier;
115 // On a settle-time tie, a cursor with an id stops above one without, and a smaller id higher.
116 if (
117 highest === null ||
118 frontier.settledAt > highest.settledAt ||
119 (frontier.settledAt === highest.settledAt &&
120 frontier.threadId !== undefined &&
121 (highest.threadId === undefined || frontier.threadId < highest.threadId))
122 ) {
123 highest = frontier;
124 }
125 }
126 return highest;
127}
128
129/**
130 * Whether the Settled shelf may list a row: at or above the shelf's frontier. So a row that turns
131 * older mid-session (a backdated auto-settle, a snooze that ends, an unarchive) waits for the
132 * range that holds it.
133 */
134export function isListedSettledThread(
135 thread: Pick<OrchestrationV2ThreadShell, "id" | "settledAt">,
136 frontier: OrchestrationV2OlderSettledCursor | null,
137): boolean {
138 return frontier === null || atOrAboveCursor(thread, frontier);
139}
140
141/**
142 * Older settled threads in scope that this client does not hold: the server's counts minus the
143 * older rows it has. Add it to the local rows for the Settled label or a project's thread count.
144 */
145export function unloadedOlderSettledCount(input: {
146 readonly olderSettled: (environmentId: EnvironmentId) => OlderSettled | null;
147 readonly scopes: ReadonlyArray<OlderSettledScope>;
148 /** Every row the client holds in scope, in any section. */
149 readonly threads: ReadonlyArray<{
150 readonly environmentId: EnvironmentId;
151 readonly source: OlderSettledRow;
152 }>;
153}): number {
154 let unloaded = 0;
155 for (const scope of input.scopes) {
156 const older = input.olderSettled(scope.environmentId);
157 if (older === null) continue;
158 if (scope.projectIds === null) {
159 for (const count of older.counts.values()) unloaded += count;
160 } else {
161 for (const projectId of scope.projectIds) unloaded += older.counts.get(projectId) ?? 0;
162 }
163 for (const thread of input.threads) {
164 if (
165 thread.environmentId === scope.environmentId &&
166 (scope.projectIds === null || scope.projectIds.includes(thread.source.projectId)) &&
167 isOlderSettledThreadShell(thread.source, older.beforeMs)
168 ) {
169 unloaded -= 1;
170 }
171 }
172 }
173 return Math.max(0, unloaded);
174}
175
176/**
177 * The pages each environment should read: while the shelf lists fewer than `visibleCount` rows,
178 * one more for each environment whose frontier is the shelf's, once its pages have loaded. A
179 * short page ends an environment's chain; counts can lag a backdated settle, so they do not gate.
180 */
181export function wantedOlderSettledPages(input: {
182 readonly requested: ReadonlyMap<EnvironmentId, number>;
183 readonly environments: ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment>;
184 readonly listedCount: number;
185 readonly visibleCount: number;
186}): ReadonlyMap<EnvironmentId, number> {
187 if (input.listedCount >= input.visibleCount) return input.requested;
188 const frontier = settledShelfFrontier([...input.environments.values()]);
189 if (frontier === null) return input.requested;
190 let next: Map<EnvironmentId, number> | null = null;
191 for (const [environmentId, { older, pages }] of input.environments) {
192 if (older === null || pages.status !== "ready" || pages.frontier === null) continue;
193 if (
194 pages.frontier.settledAt !== frontier.settledAt ||
195 pages.frontier.threadId !== frontier.threadId
196 ) {
197 continue;
198 }
199 next ??= new Map(input.requested);
200 next.set(environmentId, (input.requested.get(environmentId) ?? 0) + 1);
201 }
202 return next ?? input.requested;
203}
204
205/**
206 * Shells that omit older settled threads (`omitOlderSettled`) name the cut and count what they left
207 * out. These atoms keep those counts current and read older threads in pages for the Settled shelf.
208 */
209export function createOlderSettledThreadAtoms<R, ER, E>(
210 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
211 shellStateAtom: (
212 environmentId: EnvironmentId,
213 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
214) {
215 const shellStateValue = (state: AsyncResult.AsyncResult<EnvironmentShellState, E>) =>
216 Option.getOrNull(AsyncResult.value(state));
217
218 const countReadAtom = createEnvironmentQueryAtomFamily(runtime, {
219 label: "environment-data:orchestration:older-settled-counts",
220 staleTimeMs: Number.POSITIVE_INFINITY,
221 // A newer key unmounts this read; with no idle time its wait is interrupted before the RPC.
222 idleTtlMs: 0,
223 execute: Effect.fn("OlderSettledThreads.readCounts")(function* (input: {
224 readonly generation: number;
225 readonly before: string;
226 readonly key: string;
227 }) {
228 yield* Effect.sleep(COUNT_REREAD_DELAY);
229 return yield* request(ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads, {
230 before: { settledAt: input.before },
231 limit: 0,
232 });
233 }),
234 });
235
236 const pageReadAtom = createEnvironmentQueryAtomFamily(runtime, {
237 label: "environment-data:orchestration:older-settled-page",
238 staleTimeMs: Number.POSITIVE_INFINITY,
239 // A collapsed shelf keeps no read alive, as an idle one runs again when a reconnect replaces
240 // the session.
241 idleTtlMs: 0,
242 execute: Effect.fn("OlderSettledThreads.readPage")(function* (input: {
243 readonly generation: number;
244 readonly projectIds: ReadonlyArray<ProjectId> | null;
245 readonly before: OrchestrationV2OlderSettledCursor;
246 }) {
247 return yield* request(ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads, {
248 before: input.before,
249 ...(input.projectIds === null ? {} : { projectIds: input.projectIds }),
250 limit: OLDER_SETTLED_PAGE_SIZE,
251 });
252 }),
253 });
254
255 const countsOf = (source: {
256 readonly counts: OrchestrationV2OlderSettledThreadsPage["counts"];
257 }) => new Map(source.counts.map(({ projectId, count }) => [projectId, count] as const));
258
259 const olderSettledAtom = Atom.family((environmentId: EnvironmentId) => {
260 let generation = -1;
261 // The key of the first state seen this generation, when that state is the snapshot itself.
262 let snapshotKey: string | null = null;
263 let keyInputs: { readonly threads: unknown; readonly removedAt: unknown } | null = null;
264 let key = "";
265 let fromSnapshot: OlderSettled | null = null;
266 let lastRead: OlderSettled | null = null;
267 let lastReadPage: OrchestrationV2OlderSettledThreadsPage | null = null;
268 return Atom.make((get): OlderSettled | null => {
269 const state = shellStateValue(get(shellStateAtom(environmentId)));
270 const snapshot = state === null ? null : Option.getOrNull(state.snapshot);
271 const cut = snapshot?.olderSettled;
272 if (state === null || snapshot === null || cut === undefined) return null;
273 if (fromSnapshot?.before !== cut.before || state.generation !== generation) {
274 fromSnapshot = {
275 before: cut.before,
276 beforeMs: DateTime.toEpochMillis(DateTime.makeUnsafe(cut.before)),
277 counts: countsOf(cut),
278 };
279 }
280 // Most shell updates move only the cursor; the key needs new rows or removals.
281 if (keyInputs?.threads !== snapshot.threads || keyInputs.removedAt !== state.removedAt) {
282 keyInputs = { threads: snapshot.threads, removedAt: state.removedAt };
283 key = olderSettledCountKey(snapshot.threads, fromSnapshot.beforeMs, state.removedAt);
284 }
285 if (state.generation !== generation) {
286 generation = state.generation;
287 snapshotKey = snapshot.snapshotSequence === cut.asOfSequence ? key : null;
288 lastRead = null;
289 }
290 // Generation 0 is a cached shell: no reads until this session's first snapshot.
291 if (key === snapshotKey || state.generation === 0) return fromSnapshot;
292 const read = selectEnvironmentQueryData(
293 get(
294 countReadAtom({
295 environmentId,
296 input: { generation: state.generation, before: cut.before, key },
297 }),
298 ),
299 );
300 if (read !== null && read !== lastReadPage) {
301 lastReadPage = read;
302 lastRead = { ...fromSnapshot, counts: countsOf(read) };
303 }
304 return lastRead ?? fromSnapshot;
305 }).pipe(Atom.withLabel(`environment-older-settled:${environmentId}`));
306 });
307
308 const pagesKey = (scope: OlderSettledScope, pages: number) =>
309 JSON.stringify([
310 scope.environmentId,
311 scope.projectIds === null ? null : [...scope.projectIds].sort(),
312 pages,
313 ]);
314
315 const pagesAtom = Atom.family((key: string) => {
316 const [environmentId, projectIds, pages] = JSON.parse(key) as [
317 EnvironmentId,
318 ReadonlyArray<ProjectId> | null,
319 number,
320 ];
321 let previous = NO_PAGES;
322 const keep = (next: OlderSettledPages): OlderSettledPages => {
323 const same =
324 next.status === previous.status &&
325 next.frontier?.settledAt === previous.frontier?.settledAt &&
326 next.frontier?.threadId === previous.frontier?.threadId &&
327 (next.frontier === null) === (previous.frontier === null) &&
328 next.reads.length === previous.reads.length &&
329 next.reads.every((read, index) => read === previous.reads[index]);
330 if (!same) previous = next;
331 return previous;
332 };
333 return Atom.make((get) => {
334 const state = shellStateValue(get(shellStateAtom(environmentId)));
335 const cut = state === null ? undefined : Option.getOrNull(state.snapshot)?.olderSettled;
336 // A cached shell (an environment not connected yet, or offline) must not hold the shelf
337 // back for other environments, so it lists what it holds until its first snapshot.
338 if (state === null || cut === undefined || state.generation === 0) return keep(NO_PAGES);
339 let frontier: OrchestrationV2OlderSettledCursor = { settledAt: cut.before };
340 if (pages === 0) return keep({ reads: [], frontier, status: "ready" });
341 const reads: OrchestrationV2ThreadFamily[] = [];
342 for (let index = 0; index < pages; index += 1) {
343 const result = get(
344 pageReadAtom({
345 environmentId,
346 input: { generation: state.generation, projectIds, before: frontier },
347 }),
348 );
349 const page = selectEnvironmentQueryData(result);
350 if (page === null) {
351 return keep({
352 reads,
353 frontier,
354 status: threadFamilyRead(result) === "failed" ? "failed" : "pending",
355 });
356 }
357 reads.push(page);
358 const last = page.threads.at(-1);
359 if (page.threads.length < OLDER_SETTLED_PAGE_SIZE || last?.settledAt == null) {
360 return keep({ reads, frontier: null, status: "ready" });
361 }
362 frontier = { settledAt: DateTime.formatIso(last.settledAt), threadId: last.id };
363 }
364 return keep({ reads, frontier, status: "ready" });
365 }).pipe(Atom.withLabel(`environment-older-settled-pages:${key}`));
366 });
367
368 const pageRowsAtom = Atom.family((key: string) =>
369 Atom.map(pagesAtom(key), (pages) => pages.reads).pipe(
370 Atom.withLabel(`environment-older-settled-page-rows:${key}`),
371 ),
372 );
373
374 const searchGenerationAtom = Atom.family((environmentId: EnvironmentId) =>
375 Atom.make((get): number | "waiting" | "none" => {
376 const state = shellStateValue(get(shellStateAtom(environmentId)));
377 if (state !== null && state.generation > 0) return state.generation;
378 return state?.status === "synchronizing" ? "waiting" : "none";
379 }),
380 );
381 const searchReadAtom = createEnvironmentQueryAtomFamily(runtime, {
382 label: "environment-data:orchestration:older-settled-search",
383 idleTtlMs: 60_000,
384 execute: Effect.fn("OlderSettledThreads.search")(function* (input: {
385 readonly generation: number;
386 readonly search: OrchestrationV2SearchThreadsInput;
387 }) {
388 return yield* request(ORCHESTRATION_V2_WS_METHODS.searchThreads, input.search);
389 }),
390 });
391 // Keyed by shell generation like pages: rows read before a new snapshot do not merge, so the
392 // search reads them again.
393 const searchAtom = Atom.family((key: string) => {
394 const [environmentId, search] = JSON.parse(key) as [
395 EnvironmentId,
396 OrchestrationV2SearchThreadsInput,
397 ];
398 return Atom.make((get) => {
399 const generation = get(searchGenerationAtom(environmentId));
400 // Nothing is read before this session's first snapshot, which would drop the rows. It shows
401 // as loading only while that snapshot is on its way, so an offline environment never spins.
402 return typeof generation === "number"
403 ? get(searchReadAtom({ environmentId, input: { generation, search } }))
404 : AsyncResult.initial(generation === "waiting");
405 }).pipe(Atom.withLabel(`environment-older-settled-search:${key}`));
406 });
407
408 // One read for a shelf that spans environments: each one's cut, counts and pages.
409 const shelfAtom = Atom.family((key: string) => {
410 const entries = JSON.parse(key) as ReadonlyArray<readonly [string, string]>;
411 let previous: ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment> = new Map();
412 return Atom.make((get): ReadonlyMap<EnvironmentId, OlderSettledShelfEnvironment> => {
413 const shelf = new Map<EnvironmentId, OlderSettledShelfEnvironment>();
414 let changed = previous.size !== entries.length;
415 for (const [environmentId, pagesKey] of entries) {
416 const older = get(olderSettledAtom(environmentId as EnvironmentId));
417 const pages = get(pagesAtom(pagesKey));
418 const prior = previous.get(environmentId as EnvironmentId);
419 changed ||= prior?.older !== older || prior.pages !== pages;
420 shelf.set(environmentId as EnvironmentId, { older, pages });
421 }
422 if (changed) previous = shelf;
423 return previous;
424 }).pipe(Atom.withLabel(`environment-older-settled-shelf:${key}`));
425 });
426
427 /** Reads a failed page again (a no-op when none failed); the pages after it follow. */
428 const retryPages = (
429 registry: AtomRegistry.AtomRegistry,
430 scope: OlderSettledScope,
431 pages: number,
432 ) => {
433 const state = shellStateValue(registry.get(shellStateAtom(scope.environmentId)));
434 const result = registry.get(pagesAtom(pagesKey(scope, pages)));
435 if (state === null || result.status !== "failed" || result.frontier === null) return;
436 registry.refresh(
437 pageReadAtom({
438 environmentId: scope.environmentId,
439 input: {
440 generation: state.generation,
441 projectIds: scope.projectIds === null ? null : [...scope.projectIds].sort(),
442 before: result.frontier,
443 },
444 }),
445 );
446 };
447
448 return {
449 /** The environment's cut and current counts, or null when its shell keeps every settled thread. */
450 olderSettledAtom,
451 /** Each scope's cut, counts and first `pages` pages. */
452 shelfAtom: (
453 scopes: ReadonlyArray<{ readonly scope: OlderSettledScope; readonly pages: number }>,
454 ) =>
455 shelfAtom(
456 JSON.stringify(
457 scopes.map(({ scope, pages }) => [scope.environmentId, pagesKey(scope, pages)] as const),
458 ),
459 ),
460 retryPages,
461 /** The first `pages` pages below the cut for one scope, read in order. */
462 pagesAtom: (scope: OlderSettledScope, pages: number) => pagesAtom(pagesKey(scope, pages)),
463 /** Their rows, for `createThreadFamilyAtoms(...).mountRows`, under `rowsKey`. */
464 pageRowsAtom: (scope: OlderSettledScope, pages: number) => pageRowsAtom(pagesKey(scope, pages)),
465 rowsKey: (scope: OlderSettledScope, pages: number) => `older-settled:${pagesKey(scope, pages)}`,
466 /** `orchestration.searchThreads` for a search that asks for older settled rows. */
467 searchAtom: (environmentId: EnvironmentId, search: OrchestrationV2SearchThreadsInput) =>
468 searchAtom(JSON.stringify([environmentId, search])),
469 };
470}