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

shell.ts

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