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

shell.ts

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