Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6 type OrchestrationV2ThreadShell,
7 type ServerConfig,
8 type ThreadId,
9 type ThreadPullRequestLink,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Clock from "effect/Clock";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Semaphore from "effect/Semaphore";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import { AsyncResult, Atom } from "effect/reactivity";
22
23import * as EnvironmentRegistry from "../connection/registry.ts";
24import { connectionProjectionPhase } from "../connection/model.ts";
25import * as EnvironmentSupervisor from "../connection/supervisor.ts";
26import * as ConnectionWakeups from "../connection/wakeups.ts";
27import { safeErrorLogAttributes } from "../errors/safeLog.ts";
28import * as Persistence from "../platform/persistence.ts";
29import { runCachePersistence } from "./cachePersistence.ts";
30import { subscribeDynamicWithSession } from "../rpc/client.ts";
31import type { RpcSession } from "../rpc/session.ts";
32import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
33import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
34import {
35 applyShellStreamEvents,
36 type ShellStreamEvent,
37 mergeShellSnapshotProjects,
38 reuseUnchangedThreadShells,
39 sameThreadPullRequests,
40} from "./shellReducer.ts";
41import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
42import { followStreamInEnvironment } from "./runtime.ts";
43
44export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
45
46export interface EnvironmentShellState {
47 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
48 readonly status: EnvironmentShellStatus;
49 readonly error: Option.Option<string>;
50 /**
51 * Changes with each authoritative snapshot (not enrichment refreshes); 0 until the first one.
52 * Thread families read for an older generation may miss changes from before the latest snapshot,
53 * so they are read again.
54 */
55 readonly generation: number;
56 /** Sequences of the thread removals applied since the latest authoritative snapshot. */
57 readonly removedAt: ReadonlyMap<ThreadId, number>;
58}
59
60const EMPTY_REMOVALS: ReadonlyMap<ThreadId, number> = new Map();
61// Shared by every shell state, so a rebuilt one never reuses a generation another already used.
62let lastShellGeneration = 0;
63
64export const EMPTY_SHELL_STATE: EnvironmentShellState = {
65 snapshot: Option.none(),
66 status: "empty",
67 error: Option.none(),
68 generation: 0,
69 removedAt: EMPTY_REMOVALS,
70};
71
72function shellStatusForSnapshot(
73 snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
74): EnvironmentShellStatus {
75 return Option.isSome(snapshot) ? "cached" : "empty";
76}
77
78function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
79 if (value.loadPullRequests === undefined) return value;
80 const { loadPullRequests: _deferred, ...snapshot } = value;
81 return snapshot;
82}
83
84const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
85
86/**
87 * Replay does not refresh the older-settled cut, rows that left the newest window, or
88 * projections the server rebuilt, so drift grows with the age of the last server snapshot.
89 */
90const CACHE_RESUME_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000;
91
92type ShellOriginIdentity = Omit<Persistence.ShellCacheOrigin, "snapshotAt">;
93
94interface ShellSubscription {
95 readonly session: RpcSession;
96 /** What a snapshot from this subscription descends from; null when the server did not say. */
97 readonly identity: ShellOriginIdentity | null;
98}
99
100function canResumeFrom(
101 origin: Persistence.ShellCacheOrigin | undefined,
102 identity: ShellOriginIdentity | null,
103 now: number,
104): boolean {
105 if (origin === undefined || identity === null) return false;
106 const age = now - origin.snapshotAt;
107 return (
108 origin.serverVersion === identity.serverVersion &&
109 origin.databaseMigration === identity.databaseMigration &&
110 origin.omitIdleSubagents === identity.omitIdleSubagents &&
111 origin.omitOlderSettled === identity.omitOlderSettled &&
112 age >= 0 &&
113 age < CACHE_RESUME_MAX_AGE_MILLIS
114 );
115}
116
117interface LiveShell {
118 readonly snapshot: OrchestrationV2ShellSnapshot;
119 // Read together with the rows, so a save never pairs them with another snapshot's origin.
120 readonly origin: Persistence.ShellCacheOrigin | undefined;
121}
122
123export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
124 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
125 const cache = yield* Persistence.EnvironmentCacheStore;
126 const snapshotLoader = yield* ShellSnapshotLoader.ShellSnapshotLoader;
127 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
128 const environmentId = supervisor.target.environmentId;
129 const cached = yield* cache.loadShell(environmentId).pipe(
130 Effect.catch((error) =>
131 Effect.logWarning("Could not load cached environment shell.").pipe(
132 Effect.annotateLogs({
133 environmentId,
134 ...safeErrorLogAttributes(error),
135 }),
136 Effect.as(Option.none<Persistence.CachedShellSnapshot>()),
137 ),
138 ),
139 );
140 const cachedOrigin = Option.isSome(cached) ? cached.value.origin : undefined;
141 const cachedSnapshot = Option.map(cached, ({ origin: _origin, ...rows }) =>
142 withoutDeferredPullRequests(rows),
143 );
144 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
145 ...EMPTY_SHELL_STATE,
146 snapshot: cachedSnapshot,
147 status: shellStatusForSnapshot(cachedSnapshot),
148 });
149 const awaitingCompletion = yield* Ref.make(false);
150 const activeSubscription = yield* Ref.make<ShellSubscription | null>(null);
151 // The server snapshot the in-memory rows descend from, directly or through the cache.
152 // Only a server snapshot renews it; `snapshot-required` drops it.
153 const origin = yield* Ref.make(cachedOrigin);
154 const reloadRequests = yield* Queue.unbounded<void>();
155 const latestLive = yield* Ref.make<Option.Option<LiveShell>>(Option.none());
156 const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
157
158 const persistenceLock = yield* Semaphore.make(1);
159 let lastPersisted: LiveShell | undefined;
160 // Rows still waiting for their deferred pull request links, which must not be saved:
161 // the cache would keep them without links until the next server refresh.
162 let pendingLinkRows: ReadonlySet<OrchestrationV2ThreadShell> = new Set();
163 const persistLatest = Effect.fn("EnvironmentShellState.persistLatest")(function* (
164 flush: boolean,
165 ) {
166 while (true) {
167 const latest = yield* Ref.get(latestLive);
168 if (Option.isNone(latest) || latest.value === lastPersisted) return;
169 const { snapshot, origin } = latest.value;
170 if (snapshot.threads.some((thread) => pendingLinkRows.has(thread))) return;
171 if (
172 lastPersisted !== undefined &&
173 origin === lastPersisted.origin &&
174 snapshot.snapshotSequence >= lastPersisted.snapshot.snapshotSequence &&
175 snapshot.schemaVersion === lastPersisted.snapshot.schemaVersion &&
176 snapshot.projects === lastPersisted.snapshot.projects &&
177 snapshot.threads === lastPersisted.snapshot.threads &&
178 snapshot.archivedThreads === lastPersisted.snapshot.archivedThreads
179 ) {
180 // Keep the live cursor without rewriting the rows. Remember it here too so a
181 // later authoritative reset to a lower sequence still reaches the cache.
182 lastPersisted = latest.value;
183 return;
184 }
185 const saved = yield* cache.saveShell(environmentId, snapshot, origin).pipe(
186 Effect.as(true),
187 Effect.catch((error) =>
188 Effect.logWarning("Could not persist environment shell cache.").pipe(
189 Effect.annotateLogs({ environmentId, ...safeErrorLogAttributes(error) }),
190 Effect.as(false),
191 ),
192 ),
193 );
194 if (!saved) return;
195 lastPersisted = latest.value;
196 if (!flush) return;
197 }
198 }, persistenceLock.withPermit);
199 const persist = () => persistLatest(false);
200 const flushLiveShellSnapshot = persistLatest(true);
201
202 // Register before scoped worker fibers so reverse finalizer order interrupts
203 // those fibers first and this flush sees a stable latestLiveSnapshot.
204 yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
205
206 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
207
208 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
209 Effect.andThen(
210 SubscriptionRef.update(state, (current) => ({
211 ...current,
212 status: shellStatusForSnapshot(current.snapshot),
213 })),
214 ),
215 Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
216 Effect.asVoid,
217 );
218 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
219 ...current,
220 status: "synchronizing" as const,
221 error: Option.none(),
222 }));
223 const setReady = SubscriptionRef.update(state, (current) =>
224 current.status === "live"
225 ? current
226 : {
227 ...current,
228 status: "synchronizing" as const,
229 error: Option.none(),
230 },
231 );
232 const setStreamError = (error: unknown) =>
233 Ref.set(awaitingCompletion, false).pipe(
234 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
235 Effect.annotateLogs({
236 environmentId,
237 ...safeErrorLogAttributes(error),
238 }),
239 Effect.andThen(
240 SubscriptionRef.update(state, (current) => ({
241 ...current,
242 status: shellStatusForSnapshot(current.snapshot),
243 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
244 })),
245 ),
246 );
247
248 // Server items and deferred link fills both read the snapshot and write it back; one at a
249 // time, so neither can overwrite what the other wrote in between.
250 const snapshotWriteLock = yield* Semaphore.make(1);
251
252 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
253 entries: ReadonlyArray<readonly [RpcSession, OrchestrationV2ShellStreamItem]>,
254 pendingLinkIds?: ReadonlySet<ThreadId>,
255 ) {
256 // Read under the lock: items buffered across a session change must not land on the
257 // rows the next session loaded.
258 const subscription = yield* Ref.get(activeSubscription);
259 const items = entries.flatMap(([session, item]) =>
260 session === subscription?.session ? [item] : [],
261 );
262 const initial = yield* SubscriptionRef.get(state);
263 let waiting = yield* Ref.get(awaitingCompletion);
264 let next = initial;
265 let receivedAuthoritativeSnapshot = false;
266 let snapshotRequired = false;
267 let deltas: Array<ShellStreamEvent> = [];
268 const flushDeltas = () => {
269 if (deltas.length > 0 && Option.isSome(next.snapshot)) {
270 let sequence = next.snapshot.value.snapshotSequence;
271 let removedAt: Map<ThreadId, number> | undefined;
272 for (const delta of deltas) {
273 if (delta.sequence <= sequence) continue;
274 switch (delta.kind) {
275 case "thread.removed":
276 removedAt ??= new Map(next.removedAt);
277 removedAt.set(delta.threadId, delta.sequence);
278 break;
279 case "thread.updated":
280 case "project.updated":
281 case "project.removed":
282 break;
283 default:
284 continue;
285 }
286 sequence = delta.sequence;
287 }
288 next = {
289 ...next,
290 removedAt: removedAt ?? next.removedAt,
291 snapshot: Option.some(applyShellStreamEvents(next.snapshot.value, deltas)),
292 status: waiting ? "synchronizing" : "live",
293 error: Option.none(),
294 };
295 }
296 deltas = [];
297 };
298 for (const item of items) {
299 if (item.kind === "snapshot-required") {
300 snapshotRequired = true;
301 continue;
302 }
303 if (item.kind !== "snapshot" && item.kind !== "synchronized") {
304 deltas.push(item);
305 continue;
306 }
307 // Snapshots can reset the cursor; completion markers change the sync status.
308 flushDeltas();
309 if (item.kind === "synchronized") {
310 waiting = false;
311 if (Option.isSome(next.snapshot)) {
312 next = {
313 ...next,
314 status: "live",
315 error: Option.none(),
316 // A cache resume that caught up is as current as a snapshot for generation readers.
317 generation: next.generation === 0 ? ++lastShellGeneration : next.generation,
318 };
319 }
320 continue;
321 }
322 const authoritative = item.resolvedRepositoryIdentityRoots === undefined;
323 const nextSnapshot = mergeShellSnapshotProjects(
324 Option.getOrNull(next.snapshot),
325 item.snapshot,
326 item.resolvedRepositoryIdentityRoots === undefined
327 ? undefined
328 : { resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots },
329 );
330 if (authoritative) receivedAuthoritativeSnapshot = true;
331 next = {
332 snapshot: Option.some(nextSnapshot),
333 status: waiting ? "synchronizing" : "live",
334 error: Option.none(),
335 generation: authoritative ? ++lastShellGeneration : next.generation,
336 removedAt: authoritative ? EMPTY_REMOVALS : next.removedAt,
337 };
338 }
339 flushDeltas();
340 yield* Ref.set(awaitingCompletion, waiting);
341 let nextOrigin = yield* Ref.get(origin);
342 if (snapshotRequired) {
343 // The rows stay on screen but reload before the next resume; the cache keeps the old
344 // origin until that reload saves, which costs at most one more refusal.
345 nextOrigin = undefined;
346 yield* Ref.set(origin, nextOrigin);
347 yield* Queue.offer(reloadRequests, undefined);
348 } else if (receivedAuthoritativeSnapshot) {
349 nextOrigin =
350 subscription?.identity == null
351 ? undefined
352 : { ...subscription.identity, snapshotAt: yield* Clock.currentTimeMillis };
353 yield* Ref.set(origin, nextOrigin);
354 }
355 if (next === initial) return;
356 if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
357 pendingLinkRows = new Set(
358 next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)),
359 );
360 }
361 if (Option.isSome(next.snapshot)) {
362 yield* Ref.set(
363 latestLive,
364 Option.some({ snapshot: next.snapshot.value, origin: nextOrigin }),
365 );
366 }
367 yield* SubscriptionRef.set(state, next);
368 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
369 yield* Queue.offer(persistence, next.snapshot.value);
370 }
371 }, snapshotWriteLock.withPermit);
372
373 const stateScope = yield* Effect.scope;
374 // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
375 // not land on rows a newer snapshot reused.
376
377 let activeFill: Fiber.Fiber<void> | undefined;
378 const cancelActiveFill = Effect.suspend(() => {
379 const fill = activeFill;
380 activeFill = undefined;
381 return fill === undefined ? Effect.void : Fiber.interrupt(fill);
382 });
383 const fillDeferredPullRequests = Effect.fnUntraced(function* (
384 source: DeferredShellSnapshot,
385 applied: OrchestrationV2ShellSnapshot,
386 ) {
387 yield* cancelActiveFill;
388 if (source.loadPullRequests === undefined) return;
389 const arrivedRows = new Set(applied.threads);
390 const arrivedIds = new Set(source.threads.map((thread) => thread.id));
391 pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
392 activeFill = yield* source.loadPullRequests.pipe(
393 Effect.flatMap((linksByThreadId) =>
394 writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
395 ),
396 Effect.forkIn(stateScope),
397 );
398 });
399 const writeFilledLinks = Effect.fnUntraced(
400 function* (
401 linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
402 arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
403 arrivedIds: ReadonlySet<ThreadId>,
404 ) {
405 const filled = yield* SubscriptionRef.modify(
406 state,
407 (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
408 if (Option.isNone(current.snapshot)) return [Option.none(), current];
409 const snapshot = current.snapshot.value;
410 let changed = false;
411 const threads = snapshot.threads.map((thread) => {
412 if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
413 const links = linksByThreadId.get(thread.id);
414 if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
415 changed = true;
416 if (links === undefined) {
417 const { pullRequests: _previous, ...row } = thread;
418 return row;
419 }
420 return { ...thread, pullRequests: links };
421 });
422 if (!changed) return [Option.none(), current];
423 const next = { ...snapshot, threads };
424 return [Option.some(next), { ...current, snapshot: Option.some(next) }];
425 },
426 );
427 pendingLinkRows = new Set();
428 const live = yield* Ref.get(latestLive);
429 if (Option.isNone(live)) return;
430 const latest = Option.isSome(filled) ? filled.value : live.value.snapshot;
431 yield* Ref.set(latestLive, Option.some({ snapshot: latest, origin: live.value.origin }));
432 yield* Queue.offer(persistence, latest);
433 },
434 (effect) => snapshotWriteLock.withPermit(effect),
435 );
436 if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
437 yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
438 }
439
440 const resubscriptions = Stream.merge(
441 Stream.fromQueue(reloadRequests),
442 Option.match(wakeups, {
443 onNone: () => Stream.never,
444 onSome: (service) =>
445 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
446 }),
447 );
448
449 yield* setSynchronizing;
450 yield* Effect.forkScoped(
451 subscribeDynamicWithSession(
452 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
453 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
454 const identity = yield* session.initialConfig.pipe(
455 Effect.map((config): ShellOriginIdentity => {
456 const omitIdleSubagents = config.shellThreadFamilies === true;
457 return {
458 serverVersion: config.environment.serverVersion,
459 // Migrations rewrite projections without events, so a migrated server reloads.
460 databaseMigration: config.environment.databaseMigration ?? null,
461 omitIdleSubagents,
462 omitOlderSettled: config.shellOlderSettled === true && omitIdleSubagents,
463 };
464 }),
465 Effect.orElseSucceed(() => null),
466 );
467 const { omitIdleSubagents, omitOlderSettled } = identity ?? {
468 omitIdleSubagents: false,
469 omitOlderSettled: false,
470 };
471 yield* Ref.set(activeSubscription, { session, identity });
472 yield* Ref.set(awaitingCompletion, true);
473 yield* setSynchronizing;
474
475 // Rows from a recent server snapshot with the same omissions and server build resume
476 // from their cursor, in memory or from the cache. Anything else reloads the HTTP
477 // snapshot so a valid cursor cannot preserve stale or incomplete data.
478 let current = yield* SubscriptionRef.get(state);
479 let canResume =
480 Option.isSome(current.snapshot) &&
481 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis);
482 // Only rows the client already held may be refused; a cursor from the snapshot just
483 // loaded falls back to the socket snapshot, so a refusal cannot loop.
484 const resumingHeldRows = canResume;
485 if (!canResume) {
486 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
487 Effect.flatMap(
488 Option.match({
489 onSome: Effect.succeed,
490 onNone: () =>
491 SubscriptionRef.changes(supervisor.prepared).pipe(
492 Stream.filter(Option.isSome),
493 Stream.map((value) => value.value),
494 Stream.runHead,
495 Effect.map(Option.getOrThrow),
496 ),
497 }),
498 ),
499 );
500 // HTTP and the socket must agree, or omitted children would return through the socket.
501 const httpSnapshot = yield* snapshotLoader.load(prepared, {
502 omitIdleSubagents,
503 omitOlderSettled,
504 });
505 if (Option.isSome(httpSnapshot)) {
506 yield* cancelActiveFill;
507 const previous = yield* SubscriptionRef.get(state);
508 const snapshot = reuseUnchangedThreadShells(
509 Option.getOrNull(previous.snapshot),
510 withoutDeferredPullRequests(httpSnapshot.value),
511 );
512 const pendingLinkIds = new Set(
513 httpSnapshot.value.loadPullRequests === undefined
514 ? []
515 : httpSnapshot.value.threads.map((thread) => thread.id),
516 );
517 yield* applyItems([[session, { kind: "snapshot", snapshot }]], pendingLinkIds);
518 canResume = true;
519 current = yield* SubscriptionRef.get(state);
520 if (Option.isSome(current.snapshot)) {
521 yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value);
522 }
523 }
524 }
525
526 const omission = {
527 ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}),
528 ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}),
529 };
530 if (!canResume || Option.isNone(current.snapshot)) {
531 return { ...omission, requestCompletionMarker: true as const };
532 }
533 return {
534 afterSequence: current.snapshot.value.snapshotSequence,
535 ...(resumingHeldRows ? { httpSnapshotFallback: true as const } : {}),
536 ...omission,
537 requestCompletionMarker: true as const,
538 };
539 }),
540 {
541 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
542 retryExpectedFailureAfter: "250 millis",
543 resubscribe: resubscriptions,
544 },
545 ).pipe(Stream.runForEachArray((entries) => applyItems(entries))),
546 );
547 yield* SubscriptionRef.changes(supervisor.state).pipe(
548 Stream.runForEach((connectionState) => {
549 switch (connectionProjectionPhase(connectionState)) {
550 case "synchronizing":
551 return setSynchronizing;
552 case "disconnected":
553 return setDisconnected;
554 case "ready":
555 return setReady;
556 }
557 }),
558 Effect.forkScoped,
559 );
560
561 return state;
562});
563
564function shellStateChanges(environmentId: EnvironmentId) {
565 return followStreamInEnvironment(
566 environmentId,
567 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
568 );
569}
570
571export interface EnvironmentShellSummary {
572 readonly hasSnapshot: boolean;
573 readonly hasSynchronizingShell: boolean;
574 readonly firstError: string | null;
575}
576
577const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
578 hasSnapshot: false,
579 hasSynchronizingShell: false,
580 firstError: null,
581});
582
583const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
584
585function shellSummariesEqual(
586 left: EnvironmentShellSummary,
587 right: EnvironmentShellSummary,
588): boolean {
589 return (
590 left.hasSnapshot === right.hasSnapshot &&
591 left.hasSynchronizingShell === right.hasSynchronizingShell &&
592 left.firstError === right.firstError
593 );
594}
595
596function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
597 if (left.size !== right.size) {
598 return false;
599 }
600 for (const [key, value] of left) {
601 if (right.get(key) !== value) {
602 return false;
603 }
604 }
605 return true;
606}
607
608export function createEnvironmentShellSummaryAtom(input: {
609 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
610 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
611}) {
612 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
613 return Atom.make((get) => {
614 let hasSnapshot = false;
615 let hasSynchronizingShell = false;
616 let firstError: string | null = null;
617
618 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
619 const state = get(input.shellStateValueAtom(environmentId));
620 hasSynchronizingShell ||= state.status === "synchronizing";
621 if (firstError === null) {
622 firstError = Option.getOrNull(state.error);
623 }
624 if (Option.isNone(state.snapshot)) {
625 continue;
626 }
627 hasSnapshot = true;
628 }
629
630 const next: EnvironmentShellSummary = {
631 hasSnapshot,
632 hasSynchronizingShell,
633 firstError,
634 };
635 if (shellSummariesEqual(previousSummary, next)) {
636 return previousSummary;
637 }
638 previousSummary = next;
639 return previousSummary;
640 }).pipe(Atom.withLabel("environment-shell-summary"));
641}
642
643export function createEnvironmentServerConfigsAtom(input: {
644 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
645 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
646}) {
647 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
648 return Atom.make((get) => {
649 const next = new Map<EnvironmentId, ServerConfig>();
650 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
651 const config = get(input.serverConfigValueAtom(environmentId));
652 if (config !== null) {
653 next.set(environmentId, config);
654 }
655 }
656 if (mapsEqual(previousServerConfigs, next)) {
657 return previousServerConfigs;
658 }
659 previousServerConfigs = next;
660 return previousServerConfigs;
661 }).pipe(Atom.withLabel("environment-server-configs"));
662}
663
664/**
665 * Every shell push replaces the state, so views that gate on load progress read these
666 * primitives instead and stay put while threads stream.
667 */
668function createEnvironmentShellProgressAtoms(
669 stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,
670) {
671 return {
672 statusAtom: Atom.family((environmentId: EnvironmentId) =>
673 Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(
674 Atom.withLabel(`environment-shell-status:${environmentId}`),
675 ),
676 ),
677 hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>
678 Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(
679 Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),
680 ),
681 ),
682 };
683}
684
685export function createEnvironmentShellAtoms<R, E>(
686 runtime: Atom.AtomRuntime<
687 | EnvironmentRegistry.EnvironmentRegistry
688 | Persistence.EnvironmentCacheStore
689 | ShellSnapshotLoader.ShellSnapshotLoader
690 | R,
691 E
692 >,
693) {
694 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
695 runtime.atom(shellStateChanges(environmentId), {
696 initialValue: EMPTY_SHELL_STATE,
697 }),
698 );
699
700 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
701 Atom.make((get) =>
702 AsyncResult.getOrElse(get(stateAtom(environmentId)), () => EMPTY_SHELL_STATE),
703 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
704 );
705
706 const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);
707
708 return {
709 stateAtom,
710 stateValueAtom,
711 statusAtom,
712 hasSnapshotAtom,
713 };
714}
715
716export * from "./models.ts";
717export * from "./shellCommands.ts";
718export * from "./shellReducer.ts";
719export * from "./shellPullRequests.ts";
720export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
721export * from "./snapshots.ts";