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 { supportsCompletionMarker, omitIdleSubagents, omitOlderSettled } =
367 yield* session.initialConfig.pipe(
368 Effect.map((config) => ({
369 supportsCompletionMarker: config.shellResumeCompletionMarker === true,
370 omitIdleSubagents: config.shellThreadFamilies === true,
371 omitOlderSettled:
372 config.shellOlderSettled === true && config.shellThreadFamilies === true,
373 })),
374 Effect.orElseSucceed(() => ({
375 supportsCompletionMarker: false,
376 omitIdleSubagents: false,
377 omitOlderSettled: false,
378 })),
379 );
380 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
381 yield* setSynchronizing;
382
383 // Foreground resubscriptions on the same live session can resume from
384 // the in-memory cursor. A new session reloads the authoritative HTTP
385 // snapshot so a valid cursor cannot preserve incomplete cached data.
386 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
387 let canResume = hasAuthoritativeSnapshot;
388 let current = yield* SubscriptionRef.get(state);
389 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
390 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
391 Effect.flatMap(
392 Option.match({
393 onSome: Effect.succeed,
394 onNone: () =>
395 SubscriptionRef.changes(supervisor.prepared).pipe(
396 Stream.filter(Option.isSome),
397 Stream.map((value) => value.value),
398 Stream.runHead,
399 Effect.map(Option.getOrThrow),
400 ),
401 }),
402 ),
403 );
404 // HTTP and the socket must agree, or omitted children would return through the socket.
405 const httpSnapshot = yield* snapshotLoader.load(prepared, {
406 omitIdleSubagents,
407 omitOlderSettled,
408 });
409 if (Option.isSome(httpSnapshot)) {
410 yield* cancelActiveFill;
411 const previous = yield* SubscriptionRef.get(state);
412 const snapshot = reuseUnchangedThreadShells(
413 Option.getOrNull(previous.snapshot),
414 withoutDeferredPullRequests(httpSnapshot.value),
415 );
416 const pendingLinkIds = new Set(
417 httpSnapshot.value.loadPullRequests === undefined
418 ? []
419 : httpSnapshot.value.threads.map((thread) => thread.id),
420 );
421 yield* applyItems([{ kind: "snapshot", snapshot }], pendingLinkIds);
422 canResume = true;
423 current = yield* SubscriptionRef.get(state);
424 if (Option.isSome(current.snapshot)) {
425 yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value);
426 }
427 }
428 }
429
430 const omission = {
431 ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}),
432 ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}),
433 };
434 if (!canResume || Option.isNone(current.snapshot)) {
435 return {
436 ...omission,
437 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
438 };
439 }
440 if (!supportsCompletionMarker) {
441 yield* SubscriptionRef.update(state, (value) => ({
442 ...value,
443 status: "live" as const,
444 error: Option.none(),
445 }));
446 }
447 return {
448 afterSequence: current.snapshot.value.snapshotSequence,
449 ...omission,
450 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
451 };
452 }),
453 {
454 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
455 retryExpectedFailureAfter: "250 millis",
456 resubscribe: foregroundResubscriptions,
457 },
458 ).pipe(Stream.runForEachArray((items) => applyItems(items))),
459 );
460 yield* SubscriptionRef.changes(supervisor.state).pipe(
461 Stream.runForEach((connectionState) => {
462 switch (connectionProjectionPhase(connectionState)) {
463 case "synchronizing":
464 return setSynchronizing;
465 case "disconnected":
466 return setDisconnected;
467 case "ready":
468 return setReady;
469 }
470 }),
471 Effect.forkScoped,
472 );
473
474 return state;
475});
476
477function shellStateChanges(environmentId: EnvironmentId) {
478 return followStreamInEnvironment(
479 environmentId,
480 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
481 );
482}
483
484export interface EnvironmentShellSummary {
485 readonly hasSnapshot: boolean;
486 readonly hasSynchronizingShell: boolean;
487 readonly hasCachedShell: boolean;
488 readonly hasLiveShell: boolean;
489 readonly firstError: string | null;
490}
491
492const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
493 hasSnapshot: false,
494 hasSynchronizingShell: false,
495 hasCachedShell: false,
496 hasLiveShell: false,
497 firstError: null,
498});
499
500const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
501
502function shellSummariesEqual(
503 left: EnvironmentShellSummary,
504 right: EnvironmentShellSummary,
505): boolean {
506 return (
507 left.hasSnapshot === right.hasSnapshot &&
508 left.hasSynchronizingShell === right.hasSynchronizingShell &&
509 left.hasCachedShell === right.hasCachedShell &&
510 left.hasLiveShell === right.hasLiveShell &&
511 left.firstError === right.firstError
512 );
513}
514
515function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
516 if (left.size !== right.size) {
517 return false;
518 }
519 for (const [key, value] of left) {
520 if (right.get(key) !== value) {
521 return false;
522 }
523 }
524 return true;
525}
526
527export function createEnvironmentShellSummaryAtom(input: {
528 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
529 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
530}) {
531 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
532 return Atom.make((get) => {
533 let hasSnapshot = false;
534 let hasSynchronizingShell = false;
535 let hasCachedShell = false;
536 let hasLiveShell = false;
537 let firstError: string | null = null;
538
539 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
540 const state = get(input.shellStateValueAtom(environmentId));
541 hasSynchronizingShell ||= state.status === "synchronizing";
542 hasCachedShell ||= state.status === "cached";
543 hasLiveShell ||= state.status === "live";
544 if (firstError === null) {
545 firstError = Option.getOrNull(state.error);
546 }
547 if (Option.isNone(state.snapshot)) {
548 continue;
549 }
550 hasSnapshot = true;
551 }
552
553 const next: EnvironmentShellSummary = {
554 hasSnapshot,
555 hasSynchronizingShell,
556 hasCachedShell,
557 hasLiveShell,
558 firstError,
559 };
560 if (shellSummariesEqual(previousSummary, next)) {
561 return previousSummary;
562 }
563 previousSummary = next;
564 return previousSummary;
565 }).pipe(Atom.withLabel("environment-shell-summary"));
566}
567
568export function createEnvironmentServerConfigsAtom(input: {
569 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
570 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
571}) {
572 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
573 return Atom.make((get) => {
574 const next = new Map<EnvironmentId, ServerConfig>();
575 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
576 const config = get(input.serverConfigValueAtom(environmentId));
577 if (config !== null) {
578 next.set(environmentId, config);
579 }
580 }
581 if (mapsEqual(previousServerConfigs, next)) {
582 return previousServerConfigs;
583 }
584 previousServerConfigs = next;
585 return previousServerConfigs;
586 }).pipe(Atom.withLabel("environment-server-configs"));
587}
588
589/**
590 * Every shell push replaces the state, so views that gate on load progress read these
591 * primitives instead and stay put while threads stream.
592 */
593function createEnvironmentShellProgressAtoms(
594 stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,
595) {
596 return {
597 statusAtom: Atom.family((environmentId: EnvironmentId) =>
598 Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(
599 Atom.withLabel(`environment-shell-status:${environmentId}`),
600 ),
601 ),
602 hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>
603 Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(
604 Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),
605 ),
606 ),
607 };
608}
609
610export function createEnvironmentShellAtoms<R, E>(
611 runtime: Atom.AtomRuntime<
612 | EnvironmentRegistry.EnvironmentRegistry
613 | Persistence.EnvironmentCacheStore
614 | ShellSnapshotLoader.ShellSnapshotLoader
615 | R,
616 E
617 >,
618) {
619 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
620 runtime.atom(shellStateChanges(environmentId), {
621 initialValue: EMPTY_SHELL_STATE,
622 }),
623 );
624
625 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
626 Atom.make((get) =>
627 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
628 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
629 );
630
631 const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);
632
633 return {
634 stateAtom,
635 stateValueAtom,
636 statusAtom,
637 hasSnapshotAtom,
638 };
639}
640
641export * from "./models.ts";
642export * from "./shellCommands.ts";
643export * from "./shellReducer.ts";
644export * from "./shellPullRequests.ts";
645export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
646export * from "./snapshots.ts";