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

shell.ts

669 lines25.0 KB

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