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 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>;
56}
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";
74}
75
76function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
77 if (value.loadPullRequests === undefined) return value;
78 const { loadPullRequests: _deferred, ...snapshot } = value;
79 return snapshot;
80}
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 /* oxlint-disable oxc/no-accumulating-spread -- This copies a fixed-shape state record, not a growing collection. */
215 let next = initial;
216 let receivedSnapshot = false;
217 for (const item of items) {
218 if (item.kind === "synchronized") {
219 waiting = false;
220 if (Option.isSome(next.snapshot)) {
221 next = { ...next, status: "live", error: Option.none() };
222 }
223 continue;
224 }
225 const authoritative =
226 item.kind === "snapshot" && item.resolvedRepositoryIdentityRoots === undefined;
227 const nextSnapshot =
228 item.kind === "snapshot"
229 ? mergeShellSnapshotProjects(
230 Option.getOrNull(next.snapshot),
231 item.snapshot,
232 item.resolvedRepositoryIdentityRoots === undefined
233 ? undefined
234 : {
235 resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,
236 },
237 )
238 : Option.match(next.snapshot, {
239 onNone: () => null,
240 onSome: (snapshot) =>
241 item.sequence > snapshot.snapshotSequence
242 ? applyShellStreamEvent(snapshot, item)
243 : snapshot,
244 });
245 if (nextSnapshot === null) continue;
246 receivedSnapshot ||= item.kind === "snapshot";
247 const removal =
248 item.kind === "thread.removed" &&
249 Option.exists(next.snapshot, (snapshot) => item.sequence > snapshot.snapshotSequence)
250 ? item
251 : null;
252 next = {
253 snapshot: Option.some(nextSnapshot),
254 status: waiting ? "synchronizing" : "live",
255 error: Option.none(),
256 generation: authoritative ? ++lastShellGeneration : next.generation,
257 removedAt: authoritative
258 ? EMPTY_REMOVALS
259 : removal === null
260 ? next.removedAt
261 : new Map(next.removedAt).set(removal.threadId, removal.sequence),
262 };
263 }
264 /* oxlint-enable oxc/no-accumulating-spread */
265 yield* Ref.set(awaitingCompletion, waiting);
266 if (next === initial) return;
267 if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
268 pendingLinkRows = new Set(
269 next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)),
270 );
271 }
272 if (Option.isSome(next.snapshot)) {
273 yield* Ref.set(latestLiveSnapshot, next.snapshot);
274 }
275 yield* SubscriptionRef.set(state, next);
276 if (receivedSnapshot) {
277 const session = yield* Ref.get(activeSubscriptionSession);
278 if (session !== null) {
279 yield* Ref.set(lastAuthoritativeSession, session);
280 }
281 }
282 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
283 yield* Queue.offer(persistence, next.snapshot.value);
284 }
285 }, snapshotWriteLock.withPermit);
286
287 const stateScope = yield* Effect.scope;
288 // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
289 // not land on rows a newer snapshot reused.
290
291 let activeFill: Fiber.Fiber<void> | undefined;
292 const cancelActiveFill = Effect.suspend(() => {
293 const fill = activeFill;
294 activeFill = undefined;
295 return fill === undefined ? Effect.void : Fiber.interrupt(fill);
296 });
297 const fillDeferredPullRequests = Effect.fnUntraced(function* (
298 source: DeferredShellSnapshot,
299 applied: OrchestrationV2ShellSnapshot,
300 ) {
301 yield* cancelActiveFill;
302 if (source.loadPullRequests === undefined) return;
303 const arrivedRows = new Set(applied.threads);
304 const arrivedIds = new Set(source.threads.map((thread) => thread.id));
305 pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
306 activeFill = yield* source.loadPullRequests.pipe(
307 Effect.flatMap((linksByThreadId) =>
308 writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
309 ),
310 Effect.forkIn(stateScope),
311 );
312 });
313 const writeFilledLinks = Effect.fnUntraced(
314 function* (
315 linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
316 arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
317 arrivedIds: ReadonlySet<ThreadId>,
318 ) {
319 const filled = yield* SubscriptionRef.modify(
320 state,
321 (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
322 if (Option.isNone(current.snapshot)) return [Option.none(), current];
323 const snapshot = current.snapshot.value;
324 let changed = false;
325 const threads = snapshot.threads.map((thread) => {
326 if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
327 const links = linksByThreadId.get(thread.id);
328 if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
329 changed = true;
330 if (links === undefined) {
331 const { pullRequests: _previous, ...row } = thread;
332 return row;
333 }
334 return { ...thread, pullRequests: links };
335 });
336 if (!changed) return [Option.none(), current];
337 const next = { ...snapshot, threads };
338 return [Option.some(next), { ...current, snapshot: Option.some(next) }];
339 },
340 );
341 pendingLinkRows = new Set();
342 const live = yield* Ref.get(latestLiveSnapshot);
343 if (Option.isNone(live)) return;
344 const latest = Option.isSome(filled) ? filled : live;
345 yield* Ref.set(latestLiveSnapshot, latest);
346 yield* Queue.offer(persistence, latest.value);
347 },
348 (effect) => snapshotWriteLock.withPermit(effect),
349 );
350 if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
351 yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
352 }
353
354 const foregroundResubscriptions = Option.match(wakeups, {
355 onNone: () => Stream.never,
356 onSome: (service) =>
357 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
358 });
359
360 yield* setSynchronizing;
361 yield* Effect.forkScoped(
362 subscribeDynamic(
363 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
364 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
365 yield* Ref.set(activeSubscriptionSession, session);
366 const { omitIdleSubagents, omitOlderSettled } = yield* session.initialConfig.pipe(
367 Effect.map((config) => ({
368 omitIdleSubagents: config.shellThreadFamilies === true,
369 omitOlderSettled:
370 config.shellOlderSettled === true && config.shellThreadFamilies === true,
371 })),
372 Effect.orElseSucceed(() => ({ omitIdleSubagents: false, omitOlderSettled: false })),
373 );
374 yield* Ref.set(awaitingCompletion, true);
375 yield* setSynchronizing;
376
377 // Foreground resubscriptions on the same live session can resume from
378 // the in-memory cursor. A new session reloads the authoritative HTTP
379 // snapshot so a valid cursor cannot preserve incomplete cached data.
380 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
381 let canResume = hasAuthoritativeSnapshot;
382 let current = yield* SubscriptionRef.get(state);
383 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
384 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
385 Effect.flatMap(
386 Option.match({
387 onSome: Effect.succeed,
388 onNone: () =>
389 SubscriptionRef.changes(supervisor.prepared).pipe(
390 Stream.filter(Option.isSome),
391 Stream.map((value) => value.value),
392 Stream.runHead,
393 Effect.map(Option.getOrThrow),
394 ),
395 }),
396 ),
397 );
398 // HTTP and the socket must agree, or omitted children would return through the socket.
399 const httpSnapshot = yield* snapshotLoader.load(prepared, {
400 omitIdleSubagents,
401 omitOlderSettled,
402 });
403 if (Option.isSome(httpSnapshot)) {
404 yield* cancelActiveFill;
405 const previous = yield* SubscriptionRef.get(state);
406 const snapshot = reuseUnchangedThreadShells(
407 Option.getOrNull(previous.snapshot),
408 withoutDeferredPullRequests(httpSnapshot.value),
409 );
410 const pendingLinkIds = new Set(
411 httpSnapshot.value.loadPullRequests === undefined
412 ? []
413 : httpSnapshot.value.threads.map((thread) => thread.id),
414 );
415 yield* applyItems([{ kind: "snapshot", snapshot }], pendingLinkIds);
416 canResume = true;
417 current = yield* SubscriptionRef.get(state);
418 if (Option.isSome(current.snapshot)) {
419 yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value);
420 }
421 }
422 }
423
424 const omission = {
425 ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}),
426 ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}),
427 };
428 if (!canResume || Option.isNone(current.snapshot)) {
429 return { ...omission, requestCompletionMarker: true as const };
430 }
431 return {
432 afterSequence: current.snapshot.value.snapshotSequence,
433 ...omission,
434 requestCompletionMarker: true as const,
435 };
436 }),
437 {
438 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
439 retryExpectedFailureAfter: "250 millis",
440 resubscribe: foregroundResubscriptions,
441 },
442 ).pipe(Stream.runForEachArray((items) => applyItems(items))),
443 );
444 yield* SubscriptionRef.changes(supervisor.state).pipe(
445 Stream.runForEach((connectionState) => {
446 switch (connectionProjectionPhase(connectionState)) {
447 case "synchronizing":
448 return setSynchronizing;
449 case "disconnected":
450 return setDisconnected;
451 case "ready":
452 return setReady;
453 }
454 }),
455 Effect.forkScoped,
456 );
457
458 return state;
459});
460
461function shellStateChanges(environmentId: EnvironmentId) {
462 return followStreamInEnvironment(
463 environmentId,
464 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
465 );
466}
467
468export interface EnvironmentShellSummary {
469 readonly hasSnapshot: boolean;
470 readonly hasSynchronizingShell: boolean;
471 readonly firstError: string | null;
472}
473
474const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
475 hasSnapshot: false,
476 hasSynchronizingShell: false,
477 firstError: null,
478});
479
480const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
481
482function shellSummariesEqual(
483 left: EnvironmentShellSummary,
484 right: EnvironmentShellSummary,
485): boolean {
486 return (
487 left.hasSnapshot === right.hasSnapshot &&
488 left.hasSynchronizingShell === right.hasSynchronizingShell &&
489 left.firstError === right.firstError
490 );
491}
492
493function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
494 if (left.size !== right.size) {
495 return false;
496 }
497 for (const [key, value] of left) {
498 if (right.get(key) !== value) {
499 return false;
500 }
501 }
502 return true;
503}
504
505export function createEnvironmentShellSummaryAtom(input: {
506 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
507 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
508}) {
509 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
510 return Atom.make((get) => {
511 let hasSnapshot = false;
512 let hasSynchronizingShell = false;
513 let firstError: string | null = null;
514
515 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
516 const state = get(input.shellStateValueAtom(environmentId));
517 hasSynchronizingShell ||= state.status === "synchronizing";
518 if (firstError === null) {
519 firstError = Option.getOrNull(state.error);
520 }
521 if (Option.isNone(state.snapshot)) {
522 continue;
523 }
524 hasSnapshot = true;
525 }
526
527 const next: EnvironmentShellSummary = {
528 hasSnapshot,
529 hasSynchronizingShell,
530 firstError,
531 };
532 if (shellSummariesEqual(previousSummary, next)) {
533 return previousSummary;
534 }
535 previousSummary = next;
536 return previousSummary;
537 }).pipe(Atom.withLabel("environment-shell-summary"));
538}
539
540export function createEnvironmentServerConfigsAtom(input: {
541 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
542 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
543}) {
544 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
545 return Atom.make((get) => {
546 const next = new Map<EnvironmentId, ServerConfig>();
547 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
548 const config = get(input.serverConfigValueAtom(environmentId));
549 if (config !== null) {
550 next.set(environmentId, config);
551 }
552 }
553 if (mapsEqual(previousServerConfigs, next)) {
554 return previousServerConfigs;
555 }
556 previousServerConfigs = next;
557 return previousServerConfigs;
558 }).pipe(Atom.withLabel("environment-server-configs"));
559}
560
561/**
562 * Every shell push replaces the state, so views that gate on load progress read these
563 * primitives instead and stay put while threads stream.
564 */
565function createEnvironmentShellProgressAtoms(
566 stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,
567) {
568 return {
569 statusAtom: Atom.family((environmentId: EnvironmentId) =>
570 Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(
571 Atom.withLabel(`environment-shell-status:${environmentId}`),
572 ),
573 ),
574 hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>
575 Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(
576 Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),
577 ),
578 ),
579 };
580}
581
582export function createEnvironmentShellAtoms<R, E>(
583 runtime: Atom.AtomRuntime<
584 | EnvironmentRegistry.EnvironmentRegistry
585 | Persistence.EnvironmentCacheStore
586 | ShellSnapshotLoader.ShellSnapshotLoader
587 | R,
588 E
589 >,
590) {
591 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
592 runtime.atom(shellStateChanges(environmentId), {
593 initialValue: EMPTY_SHELL_STATE,
594 }),
595 );
596
597 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
598 Atom.make((get) =>
599 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
600 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
601 );
602
603 const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);
604
605 return {
606 stateAtom,
607 stateValueAtom,
608 statusAtom,
609 hasSnapshotAtom,
610 };
611}
612
613export * from "./models.ts";
614export * from "./shellCommands.ts";
615export * from "./shellReducer.ts";
616export * from "./shellPullRequests.ts";
617export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
618export * from "./snapshots.ts";