Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { M } from "gt-i18n";
3import {
4 ORCHESTRATION_V2_WS_METHODS,
5 type EnvironmentId,
6 type ExecutionEnvironmentDescriptor,
7 type OrchestrationV2ShellSnapshot,
8 type OrchestrationV2ShellStreamItem,
9 type OrchestrationV2ThreadShell,
10 type ServerConfig,
11 type ThreadId,
12 type ThreadPullRequestLink,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Clock from "effect/Clock";
16import * as DateTime from "effect/DateTime";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Fiber from "effect/Fiber";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Ref from "effect/Ref";
24import * as Semaphore from "effect/Semaphore";
25import * as Stream from "effect/Stream";
26import * as SubscriptionRef from "effect/SubscriptionRef";
27import * as SynchronizedRef from "effect/SynchronizedRef";
28import { AsyncResult, Atom } from "effect/reactivity";
29
30import { observeServerTime } from "../clock.ts";
31import * as EnvironmentRegistry from "../connection/registry.ts";
32import { connectionProjectionPhase, type PreparedConnection } from "../connection/model.ts";
33import * as EnvironmentSupervisor from "../connection/supervisor.ts";
34import * as ConnectionWakeups from "../connection/wakeups.ts";
35import { safeErrorLogAttributes } from "../errors/safeLog.ts";
36import * as Persistence from "../platform/persistence.ts";
37import { runCachePersistence } from "./cachePersistence.ts";
38import { subscribeDynamicWithSession, subscriptionRetryDelay } from "../rpc/client.ts";
39import type { RpcSession } from "../rpc/session.ts";
40import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
41import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
42import {
43 applyShellStreamEvents,
44 type ShellStreamEvent,
45 mergeShellSnapshotProjects,
46 reuseUnchangedThreadShells,
47 sameThreadPullRequests,
48} from "./shellReducer.ts";
49import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
50import { followStreamInEnvironment } from "./runtime.ts";
51
52export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
53
54export interface EnvironmentShellState {
55 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
56 readonly status: EnvironmentShellStatus;
57 readonly error: Option.Option<string>;
58 /**
59 * Changes with each authoritative snapshot (not enrichment refreshes); 0 until the first one.
60 * Thread families read for an older generation may miss changes from before the latest snapshot,
61 * so they are read again.
62 */
63 readonly generation: number;
64 readonly commandHistory?: {
65 readonly rewind?: {
66 readonly generation: number;
67 readonly session: RpcSession | undefined;
68 readonly bootstrap: boolean;
69 };
70 readonly synchronizedSession?: RpcSession;
71 };
72 /** Sequences of the thread removals applied since the latest authoritative snapshot. */
73 readonly removedAt: ReadonlyMap<ThreadId, number>;
74}
75
76interface ShellCommandDispatch {
77 readonly session: RpcSession;
78 readonly history: EnvironmentShellState["commandHistory"];
79}
80
81export interface ShellCommandReceipt {
82 readonly value: { readonly sequence: number };
83 readonly dispatched: ShellCommandDispatch | undefined;
84}
85
86export function shellCommandHistoryInvalidated(
87 dispatched: ShellCommandDispatch | undefined,
88 current: EnvironmentShellState["commandHistory"],
89): boolean {
90 if (dispatched === undefined || current === undefined) return false;
91 const { session, history } = dispatched;
92 const rewind = current.rewind;
93 return (
94 (rewind !== undefined &&
95 rewind !== history?.rewind &&
96 (!rewind.bootstrap || (rewind.session !== undefined && rewind.session !== session))) ||
97 (current.synchronizedSession !== undefined &&
98 current.synchronizedSession !== history?.synchronizedSession &&
99 current.synchronizedSession !== session)
100 );
101}
102
103const EMPTY_REMOVALS: ReadonlyMap<ThreadId, number> = new Map();
104// Shared by every shell state, so a rebuilt one never reuses a generation another already used.
105let lastShellGeneration = 0;
106
107export const EMPTY_SHELL_STATE: EnvironmentShellState = {
108 snapshot: Option.none(),
109 status: "empty",
110 error: Option.none(),
111 generation: 0,
112 removedAt: EMPTY_REMOVALS,
113};
114
115function shellStatusForSnapshot(
116 snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
117): EnvironmentShellStatus {
118 return Option.isSome(snapshot) ? "cached" : "empty";
119}
120
121function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
122 if (value.loadPullRequests === undefined) return value;
123 const { loadPullRequests: _deferred, ...snapshot } = value;
124 return snapshot;
125}
126
127const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = msg("Could not synchronize environment data.");
128
129/** @public The shell's sync error in the active language; other messages stay as they are. */
130export function shellErrorText(error: string, resolve: M = mFallback): string {
131 return error === SHELL_SYNCHRONIZATION_ERROR_MESSAGE ? resolve(error) : error;
132}
133
134/**
135 * Replay does not refresh the older-settled cut, rows that left the newest window, or
136 * projections the server rebuilt, so drift grows with the age of the last server snapshot.
137 */
138const CACHE_RESUME_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000;
139
140type ShellOriginIdentity = Omit<Persistence.ShellCacheOrigin, "snapshotAt">;
141
142type OpeningVerification =
143 | { readonly kind: "matched"; readonly identity: ShellOriginIdentity }
144 | { readonly kind: "mismatched"; readonly identity: ShellOriginIdentity | null }
145 | { readonly kind: "rejected" };
146
147const pollOpeningVerification = (verification: Deferred.Deferred<OpeningVerification>) =>
148 Deferred.poll(verification).pipe(
149 Effect.flatMap(
150 Option.match({
151 onNone: () => Effect.succeedNone,
152 onSome: Effect.asSome,
153 }),
154 ),
155 );
156
157interface ShellSubscription {
158 readonly session: RpcSession;
159 /** What a snapshot from this subscription descends from; null when the server did not say. */
160 readonly identity: ShellOriginIdentity | null;
161 /** Set on pipelined opening sessions until initialConfig validates environmentId and flags. */
162 readonly verification?: Deferred.Deferred<OpeningVerification>;
163}
164
165function shellIdentity(
166 environment: Pick<ExecutionEnvironmentDescriptor, "serverVersion" | "databaseMigration">,
167 flags: { readonly shellThreadFamilies?: boolean; readonly shellOlderSettled?: boolean },
168): ShellOriginIdentity {
169 const omitIdleSubagents = flags.shellThreadFamilies === true;
170 return {
171 serverVersion: environment.serverVersion,
172 // Migrations rewrite projections without events, so a migrated server reloads.
173 databaseMigration: environment.databaseMigration ?? null,
174 omitIdleSubagents,
175 omitOlderSettled: flags.shellOlderSettled === true && omitIdleSubagents,
176 };
177}
178
179function sameConnection(left: PreparedConnection, right: PreparedConnection): boolean {
180 const keys = Object.keys({ ...left, ...right }) as Array<keyof PreparedConnection>;
181 return keys.every((key) => key === "httpAuthorization" || left[key] === right[key]);
182}
183
184/** Null for a server whose descriptor does not name its shell flags; only its config does. */
185function descriptorShellIdentity(
186 descriptor: ExecutionEnvironmentDescriptor | undefined,
187): ShellOriginIdentity | null {
188 if (descriptor?.capabilities.shellThreadFamilies === undefined) return null;
189 return shellIdentity(descriptor, descriptor.capabilities);
190}
191
192function sameShellIdentity(left: ShellOriginIdentity, right: ShellOriginIdentity): boolean {
193 return (
194 left.serverVersion === right.serverVersion &&
195 left.databaseMigration === right.databaseMigration &&
196 left.omitIdleSubagents === right.omitIdleSubagents &&
197 left.omitOlderSettled === right.omitOlderSettled
198 );
199}
200
201function canResumeFrom(
202 origin: Persistence.ShellCacheOrigin | undefined,
203 identity: ShellOriginIdentity | null,
204 now: number,
205): boolean {
206 if (origin === undefined || identity === null) return false;
207 const age = now - origin.snapshotAt;
208 return sameShellIdentity(origin, identity) && age >= 0 && age < CACHE_RESUME_MAX_AGE_MILLIS;
209}
210
211type HttpShellOutcome =
212 | { readonly kind: "snapshot"; readonly projectIdentities: string | undefined }
213 /** The server can replay from the rows the client holds. */
214 | { readonly kind: "resumable" }
215 | { readonly kind: "failed" };
216
217interface EarlyShellLoad {
218 readonly prepared: PreparedConnection;
219 readonly identity: ShellOriginIdentity;
220 readonly fiber: Fiber.Fiber<HttpShellOutcome>;
221 // One subscription uses a load; a later one on the same connection decides again.
222 readonly session: Ref.Ref<RpcSession | undefined>;
223}
224
225interface LiveShell {
226 readonly snapshot: OrchestrationV2ShellSnapshot;
227 // Read together with the rows, so a save never pairs them with another snapshot's origin.
228 readonly origin: Persistence.ShellCacheOrigin | undefined;
229}
230
231export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
232 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
233 const cache = yield* Persistence.EnvironmentCacheStore;
234 const snapshotLoader = yield* ShellSnapshotLoader.ShellSnapshotLoader;
235 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
236 const environmentId = supervisor.target.environmentId;
237 const cached = yield* cache.loadShell(environmentId).pipe(
238 Effect.catch((error) =>
239 Effect.logWarning("Could not load cached environment shell.").pipe(
240 Effect.annotateLogs({
241 environmentId,
242 ...safeErrorLogAttributes(error),
243 }),
244 Effect.as(Option.none<Persistence.CachedShellSnapshot>()),
245 ),
246 ),
247 );
248 const cachedOrigin = Option.isSome(cached) ? cached.value.origin : undefined;
249 const cachedSnapshot = Option.map(cached, ({ origin: _origin, ...rows }) =>
250 withoutDeferredPullRequests(rows),
251 );
252 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
253 ...EMPTY_SHELL_STATE,
254 snapshot: cachedSnapshot,
255 status: shellStatusForSnapshot(cachedSnapshot),
256 });
257 const awaitingCompletion = yield* Ref.make(false);
258 const activeSubscription = yield* Ref.make<ShellSubscription | null>(null);
259 const replaceActiveSubscription = (next: ShellSubscription | null) =>
260 Ref.getAndSet(activeSubscription, next).pipe(
261 Effect.flatMap((previous) =>
262 previous?.verification === undefined || previous.verification === next?.verification
263 ? Effect.void
264 : Deferred.succeed(previous.verification, { kind: "rejected" }).pipe(Effect.asVoid),
265 ),
266 );
267 // The server snapshot the in-memory rows descend from, directly or through the cache.
268 // Only a server snapshot renews it; `snapshot-required` drops it.
269 const origin = yield* Ref.make(cachedOrigin);
270 const reloadRequests = yield* Queue.unbounded<void>();
271 let defectRetries = 0;
272 const latestLive = yield* Ref.make<Option.Option<LiveShell>>(Option.none());
273 const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
274
275 const persistenceLock = yield* Semaphore.make(1);
276 let lastPersisted: LiveShell | undefined =
277 Option.isSome(cachedSnapshot) &&
278 Option.isSome(cached) &&
279 cached.value.loadPullRequests === undefined
280 ? { snapshot: cachedSnapshot.value, origin: cachedOrigin }
281 : undefined;
282 // Rows still waiting for their deferred pull request links, which must not be saved:
283 // the cache would keep them without links until the next server refresh.
284 let pendingLinkRows: ReadonlySet<OrchestrationV2ThreadShell> = new Set();
285 const persistLatest = Effect.fn("EnvironmentShellState.persistLatest")(function* (
286 flush: boolean,
287 ) {
288 while (true) {
289 const latest = yield* Ref.get(latestLive);
290 if (Option.isNone(latest) || latest.value === lastPersisted) return;
291 const { snapshot, origin } = latest.value;
292 if (snapshot.threads.some((thread) => pendingLinkRows.has(thread))) return;
293 if (
294 lastPersisted !== undefined &&
295 origin === lastPersisted.origin &&
296 snapshot.snapshotSequence >= lastPersisted.snapshot.snapshotSequence &&
297 snapshot.schemaVersion === lastPersisted.snapshot.schemaVersion &&
298 snapshot.projects === lastPersisted.snapshot.projects &&
299 snapshot.threads === lastPersisted.snapshot.threads &&
300 snapshot.archivedThreads === lastPersisted.snapshot.archivedThreads
301 ) {
302 // Keep the live cursor without rewriting the rows. Remember it here too so a
303 // later authoritative reset to a lower sequence still reaches the cache.
304 lastPersisted = latest.value;
305 return;
306 }
307 const saved = yield* cache.saveShell(environmentId, snapshot, origin).pipe(
308 Effect.as(true),
309 Effect.catch((error) =>
310 Effect.logWarning("Could not persist environment shell cache.").pipe(
311 Effect.annotateLogs({ environmentId, ...safeErrorLogAttributes(error) }),
312 Effect.as(false),
313 ),
314 ),
315 );
316 if (!saved) return;
317 lastPersisted = latest.value;
318 if (!flush) return;
319 }
320 }, persistenceLock.withPermit);
321 const persist = () => persistLatest(false);
322 const flushLiveShellSnapshot = persistLatest(true);
323
324 // Register before scoped worker fibers so reverse finalizer order interrupts
325 // those fibers first and this flush sees a stable latestLiveSnapshot.
326 yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
327
328 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
329
330 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
331 Effect.andThen(
332 SubscriptionRef.update(state, (current) => ({
333 ...current,
334 status: shellStatusForSnapshot(current.snapshot),
335 })),
336 ),
337 Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
338 Effect.asVoid,
339 );
340 const synchronizing = (current: EnvironmentShellState): Option.Option<EnvironmentShellState> =>
341 current.status === "synchronizing" && Option.isNone(current.error)
342 ? Option.none()
343 : Option.some({ ...current, status: "synchronizing", error: Option.none() });
344 const setSynchronizing = SubscriptionRef.updateSome(state, synchronizing);
345 const setReady = SubscriptionRef.updateSome(state, (current) =>
346 current.status === "live" ? Option.none() : synchronizing(current),
347 );
348 const setStreamError = (error: unknown) =>
349 Ref.set(awaitingCompletion, false).pipe(
350 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
351 Effect.annotateLogs({
352 environmentId,
353 ...safeErrorLogAttributes(error),
354 }),
355 Effect.andThen(
356 SubscriptionRef.update(state, (current) => ({
357 ...current,
358 status: shellStatusForSnapshot(current.snapshot),
359 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
360 })),
361 ),
362 );
363
364 // Server items and deferred link fills both read the snapshot and write it back; one at a
365 // time, so neither can overwrite what the other wrote in between.
366 const snapshotWriteLock = yield* Semaphore.make(1);
367
368 const applyLocked = Effect.fnUntraced(function* (
369 items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
370 /** What an authoritative snapshot among the items descends from. */
371 identity: ShellOriginIdentity | null,
372 /** Set for an HTTP snapshot: the rows that still wait for their pull request links. */
373 pendingLinkIds?: ReadonlySet<ThreadId>,
374 session?: RpcSession,
375 ) {
376 const initial = yield* SubscriptionRef.get(state);
377 // No socket has confirmed an HTTP snapshot, so it never makes the shell live.
378 const fromHttp = pendingLinkIds !== undefined;
379 const disconnected = initial.status === "empty" || initial.status === "cached";
380 let waiting = yield* Ref.get(awaitingCompletion);
381 let next = initial;
382 let receivedAuthoritativeSnapshot = false;
383 let snapshotRequired = false;
384 let deltas: Array<ShellStreamEvent> = [];
385 const receivedAtMs = yield* Clock.currentTimeMillis;
386 const flushDeltas = () => {
387 if (deltas.length > 0 && Option.isSome(next.snapshot)) {
388 let sequence = next.snapshot.value.snapshotSequence;
389 let removedAt: Map<ThreadId, number> | undefined;
390 for (const delta of deltas) {
391 if (delta.sequence <= sequence) continue;
392 switch (delta.kind) {
393 case "thread.removed":
394 removedAt ??= new Map(next.removedAt);
395 removedAt.set(delta.threadId, delta.sequence);
396 break;
397 case "thread.updated":
398 // Replayed catch-up deltas may predate a backward host clock correction.
399 if (!waiting) {
400 observeServerTime(
401 environmentId,
402 DateTime.toEpochMillis(delta.thread.updatedAt),
403 receivedAtMs,
404 );
405 }
406 break;
407 case "project.updated":
408 case "project.removed":
409 break;
410 default:
411 continue;
412 }
413 sequence = delta.sequence;
414 }
415 next = {
416 ...next,
417 removedAt: removedAt ?? next.removedAt,
418 snapshot: Option.some(applyShellStreamEvents(next.snapshot.value, deltas)),
419 status: waiting ? "synchronizing" : "live",
420 error: Option.none(),
421 };
422 }
423 deltas = [];
424 };
425 for (const item of items) {
426 if (item.kind === "snapshot-required") {
427 snapshotRequired = true;
428 continue;
429 }
430 if (item.kind !== "snapshot" && item.kind !== "synchronized") {
431 deltas.push(item);
432 continue;
433 }
434 // Snapshots can reset the cursor; completion markers change the sync status.
435 flushDeltas();
436 if (item.kind === "synchronized") {
437 waiting = false;
438 if (Option.isSome(next.snapshot)) {
439 next = {
440 ...next,
441 status: "live",
442 error: Option.none(),
443 // A cache resume that caught up is as current as a snapshot for generation readers.
444 generation: next.generation === 0 ? ++lastShellGeneration : next.generation,
445 ...(session !== undefined && session !== next.commandHistory?.synchronizedSession
446 ? { commandHistory: { ...next.commandHistory, synchronizedSession: session } }
447 : {}),
448 };
449 }
450 continue;
451 }
452 const authoritative = item.resolvedRepositoryIdentityRoots === undefined;
453 const nextSnapshot = mergeShellSnapshotProjects(
454 Option.getOrNull(next.snapshot),
455 item.snapshot,
456 item.resolvedRepositoryIdentityRoots === undefined
457 ? undefined
458 : { resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots },
459 );
460 if (authoritative) receivedAuthoritativeSnapshot = true;
461 const generation = authoritative ? ++lastShellGeneration : next.generation;
462 // An early HTTP load may publish before a socket claims it. In that case the
463 // synchronization marker identifies the replacement session once it catches up.
464 const bootstrap =
465 (fromHttp && session === undefined) ||
466 ((waiting || fromHttp) && session !== next.commandHistory?.synchronizedSession);
467 const previousSequence = Option.getOrUndefined(next.snapshot)?.snapshotSequence;
468 // A refresh at the held cursor on the synchronized socket may predate its pending receipts.
469 const rewound =
470 authoritative &&
471 previousSequence !== undefined &&
472 (nextSnapshot.snapshotSequence < previousSequence ||
473 (bootstrap && nextSnapshot.snapshotSequence === previousSequence));
474 next = {
475 ...next,
476 ...(rewound
477 ? {
478 commandHistory: {
479 ...next.commandHistory,
480 rewind: {
481 generation,
482 session,
483 bootstrap,
484 },
485 },
486 }
487 : {}),
488 snapshot: Option.some(nextSnapshot),
489 status:
490 fromHttp && disconnected ? "cached" : waiting || fromHttp ? "synchronizing" : "live",
491 error: Option.none(),
492 generation,
493 removedAt: authoritative ? EMPTY_REMOVALS : next.removedAt,
494 };
495 }
496 flushDeltas();
497 yield* Ref.set(awaitingCompletion, waiting);
498 let nextOrigin = yield* Ref.get(origin);
499 if (snapshotRequired) {
500 // The rows stay on screen but reload before the next resume; the cache keeps the old
501 // origin until that reload saves, which costs at most one more refusal.
502 nextOrigin = undefined;
503 yield* Ref.set(origin, nextOrigin);
504 yield* Queue.offer(reloadRequests, undefined);
505 } else if (receivedAuthoritativeSnapshot) {
506 nextOrigin =
507 identity === null ? undefined : { ...identity, snapshotAt: yield* Clock.currentTimeMillis };
508 yield* Ref.set(origin, nextOrigin);
509 }
510 if (next === initial) return;
511 if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
512 pendingLinkRows =
513 pendingLinkIds.size === 0
514 ? new Set()
515 : new Set(next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)));
516 }
517 if (Option.isSome(next.snapshot)) {
518 yield* Ref.set(
519 latestLive,
520 Option.some({ snapshot: next.snapshot.value, origin: nextOrigin }),
521 );
522 }
523 yield* SubscriptionRef.set(state, next);
524 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
525 yield* Queue.offer(persistence, next.snapshot.value);
526 }
527 });
528
529 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
530 entries: ReadonlyArray<readonly [RpcSession, OrchestrationV2ShellStreamItem]>,
531 ) {
532 // Buffer opening-session items until initialConfig validates environmentId and shell flags
533 // so an unverified or wrong-environment socket cannot publish or cache rows under environmentId.
534 const pending = yield* Ref.get(activeSubscription);
535 if (
536 pending?.verification !== undefined &&
537 entries.some(([session]) => session === pending.session)
538 ) {
539 yield* Deferred.await(pending.verification);
540 }
541 yield* snapshotWriteLock.withPermit(
542 Effect.gen(function* () {
543 // Read under the lock: items buffered across a session change must not land on the
544 // rows the next session loaded.
545 const subscription = yield* Ref.get(activeSubscription);
546 if (subscription?.verification !== undefined) {
547 const settled = yield* pollOpeningVerification(subscription.verification);
548 if (Option.isNone(settled) || settled.value.kind !== "matched") return;
549 }
550 yield* applyLocked(
551 entries.flatMap(([session, item]) => (session === subscription?.session ? [item] : [])),
552 subscription?.identity ?? null,
553 undefined,
554 subscription?.session,
555 );
556 }),
557 );
558 });
559
560 const stateScope = yield* Effect.scope;
561 // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
562 // not land on rows a newer snapshot reused.
563
564 let activeFill: Fiber.Fiber<void> | undefined;
565 const cancelActiveFill = Effect.suspend(() => {
566 const fill = activeFill;
567 activeFill = undefined;
568 return fill === undefined ? Effect.void : Fiber.interrupt(fill);
569 });
570 const fillDeferredPullRequests = Effect.fnUntraced(function* (
571 source: DeferredShellSnapshot,
572 applied: OrchestrationV2ShellSnapshot,
573 ) {
574 yield* cancelActiveFill;
575 if (source.loadPullRequests === undefined) return;
576 const arrivedRows = new Set(applied.threads);
577 const arrivedIds = new Set(source.threads.map((thread) => thread.id));
578 pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
579 activeFill = yield* source.loadPullRequests.pipe(
580 Effect.flatMap((linksByThreadId) =>
581 writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
582 ),
583 Effect.forkIn(stateScope),
584 );
585 });
586 const writeFilledLinks = Effect.fnUntraced(
587 function* (
588 linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
589 arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
590 arrivedIds: ReadonlySet<ThreadId>,
591 ) {
592 const filled = yield* SubscriptionRef.modify(
593 state,
594 (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
595 if (Option.isNone(current.snapshot)) return [Option.none(), current];
596 const snapshot = current.snapshot.value;
597 let changed = false;
598 const threads = snapshot.threads.map((thread) => {
599 if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
600 const links = linksByThreadId.get(thread.id);
601 if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
602 changed = true;
603 if (links === undefined) {
604 const { pullRequests: _previous, ...row } = thread;
605 return row;
606 }
607 return { ...thread, pullRequests: links };
608 });
609 if (!changed) return [Option.none(), current];
610 const next = { ...snapshot, threads };
611 return [Option.some(next), { ...current, snapshot: Option.some(next) }];
612 },
613 );
614 pendingLinkRows = new Set();
615 const live = yield* Ref.get(latestLive);
616 if (Option.isNone(live)) return;
617 const latest = Option.isSome(filled) ? filled.value : live.value.snapshot;
618 yield* Ref.set(latestLive, Option.some({ snapshot: latest, origin: live.value.origin }));
619 yield* Queue.offer(persistence, latest);
620 },
621 (effect) => snapshotWriteLock.withPermit(effect),
622 );
623 if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
624 yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
625 }
626
627 const applyHttpSnapshot = Effect.fnUntraced(function* (
628 loaded: ShellSnapshotLoader.ShellHttpSnapshot,
629 identity: ShellOriginIdentity | null,
630 session: RpcSession | undefined,
631 ) {
632 const { projectIdentities: _identities, ...deferred } = loaded;
633 yield* cancelActiveFill;
634 const previous = yield* SubscriptionRef.get(state);
635 const snapshot = reuseUnchangedThreadShells(
636 Option.getOrNull(previous.snapshot),
637 withoutDeferredPullRequests(deferred),
638 );
639 const pendingLinkIds = new Set(
640 deferred.loadPullRequests === undefined ? [] : deferred.threads.map((thread) => thread.id),
641 );
642 yield* snapshotWriteLock.withPermit(
643 applyLocked([{ kind: "snapshot", snapshot }], identity, pendingLinkIds, session),
644 );
645 const current = yield* SubscriptionRef.get(state);
646 if (Option.isSome(current.snapshot)) {
647 yield* fillDeferredPullRequests(deferred, current.snapshot.value);
648 }
649 }, Effect.uninterruptible);
650
651 /**
652 * One request to the HTTP shell route. Held rows that may resume are named, so the server
653 * answers that they still can, in a few bytes, or sends the snapshot that replaces them.
654 */
655 const loadOverHttp = Effect.fn("EnvironmentShellState.loadOverHttp")(function* (
656 prepared: PreparedConnection,
657 identity: ShellOriginIdentity | null,
658 session: Effect.Effect<RpcSession | undefined>,
659 ) {
660 const held = yield* SubscriptionRef.get(state);
661 const resumeFrom =
662 Option.isSome(held.snapshot) &&
663 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis)
664 ? held.snapshot.value.snapshotSequence
665 : undefined;
666 // HTTP and the socket must agree, or omitted children would return through the socket.
667 const answer = yield* snapshotLoader.load(prepared, {
668 omitIdleSubagents: identity?.omitIdleSubagents === true,
669 omitOlderSettled: identity?.omitOlderSettled === true,
670 ...(resumeFrom === undefined ? {} : { resumeFrom }),
671 });
672 if (Option.isNone(answer)) return { kind: "failed" } satisfies HttpShellOutcome;
673 if ("resumable" in answer.value) return { kind: "resumable" } satisfies HttpShellOutcome;
674 yield* applyHttpSnapshot(answer.value, identity, yield* session);
675 return {
676 kind: "snapshot",
677 projectIdentities: answer.value.projectIdentities,
678 } satisfies HttpShellOutcome;
679 });
680
681 // A server whose descriptor names its shell flags is asked for the shell as soon as the
682 // connection is prepared, while the socket opens and the config downloads. When the supervisor
683 // exposes an opening socket on a direct route, the socket pipelines the shell subscription
684 // directly alongside initial config instead of racing a second HTTP snapshot on the same host.
685 const canPipelineDirectSocket = (prepared: PreparedConnection | null) =>
686 supervisor.openingSession !== undefined &&
687 prepared !== null &&
688 prepared.target._tag !== "RelayConnectionTarget" &&
689 descriptorShellIdentity(prepared.descriptor) !== null;
690 const earlyLoad = yield* SynchronizedRef.make<EarlyShellLoad | null>(null);
691 const useEarlyLoad = (prepared: PreparedConnection | null, claim?: RpcSession) =>
692 SynchronizedRef.modifyEffect(
693 earlyLoad,
694 Effect.fnUntraced(function* (current) {
695 // A rotated credential replaces the prepared connection of a session that stays up.
696 if (current !== null && prepared !== null && sameConnection(current.prepared, prepared)) {
697 const claimed = yield* Ref.get(current.session);
698 if (claim !== undefined) yield* Ref.set(current.session, claim);
699 const next = { ...current, prepared };
700 // A claimed load that still runs is handed out again. A second request could
701 // answer first, and this one would then replace its rows under a passed cursor.
702 const done = current.fiber.pollUnsafe() !== undefined;
703 return [claimed !== undefined && done ? null : current, next] as const;
704 }
705 if (current !== null) yield* Fiber.interrupt(current.fiber);
706 const identity = descriptorShellIdentity(prepared?.descriptor);
707 if (prepared === null || identity === null || canPipelineDirectSocket(prepared)) {
708 return [null, null] as const;
709 }
710 // Items a closed session still has in flight must not land on the rows this loads.
711 yield* replaceActiveSubscription(null);
712 const session = yield* Ref.make(claim);
713 const fiber = yield* loadOverHttp(prepared, identity, Ref.get(session)).pipe(
714 Effect.forkIn(stateScope),
715 );
716 const next: EarlyShellLoad = { prepared, identity, fiber, session };
717 return [next, next] as const;
718 }),
719 ).pipe(
720 // Covers the store too. A cancel that lands during the wait above would otherwise take
721 // effect before the store, and the load just started would run on with no record.
722 Effect.uninterruptible,
723 );
724 /**
725 * A ready socket can validate a held cursor itself. When it needs a full snapshot, give the
726 * already-started HTTP load a short head start before falling back to the socket snapshot.
727 */
728 const awaitEarlyLoad = Effect.fnUntraced(function* (
729 early: EarlyShellLoad,
730 identity: ShellOriginIdentity | null,
731 ) {
732 const resumable =
733 Option.isSome((yield* SubscriptionRef.get(state)).snapshot) &&
734 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis);
735 const answered = early.fiber.pollUnsafe();
736 if (answered !== undefined) return answered;
737 if (!resumable && identity !== null && sameShellIdentity(early.identity, identity)) {
738 const completed = yield* Fiber.await(early.fiber).pipe(Effect.timeoutOption("30 millis"));
739 if (Option.isSome(completed)) return completed.value;
740 }
741 // Returns after an answer that is being applied has finished, so the cursor below is read
742 // from rows that no longer change under it.
743 yield* Fiber.interrupt(early.fiber);
744 return yield* Fiber.await(early.fiber);
745 });
746
747 yield* SubscriptionRef.changes(supervisor.prepared).pipe(
748 // Reads the connection of this moment: a change handled late must not start a load for a
749 // connection that ended, which would also drop the items of the session that replaced it.
750 Stream.runForEach(() =>
751 SubscriptionRef.get(supervisor.prepared).pipe(
752 Effect.flatMap((prepared) => useEarlyLoad(Option.getOrNull(prepared))),
753 ),
754 ),
755 Effect.forkScoped,
756 );
757
758 const resubscriptions = Stream.merge(
759 Stream.fromQueue(reloadRequests),
760 Option.match(wakeups, {
761 onNone: () => Stream.never,
762 onSome: (service) =>
763 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
764 }),
765 );
766
767 const verifiedConfigIdentity = new WeakMap<RpcSession, ShellOriginIdentity | null>();
768
769 yield* setSynchronizing;
770 yield* Effect.forkScoped(
771 subscribeDynamicWithSession(
772 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
773 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
774 const previousSubscription = yield* Ref.get(activeSubscription);
775 if (
776 previousSubscription !== null &&
777 previousSubscription.session !== session &&
778 previousSubscription.verification !== undefined
779 ) {
780 yield* Deferred.succeed(previousSubscription.verification, { kind: "rejected" });
781 }
782 const currentPrepared = Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared));
783 const descriptorIdentity = descriptorShellIdentity(currentPrepared?.descriptor);
784 let identity: ShellOriginIdentity | null;
785 let verification: Deferred.Deferred<OpeningVerification> | undefined;
786 let reloadQueued = false;
787 const queueMismatchReload = Effect.suspend(() => {
788 if (reloadQueued) return Effect.void;
789 reloadQueued = true;
790 return Ref.set(origin, undefined).pipe(
791 Effect.andThen(Queue.offer(reloadRequests, undefined)),
792 );
793 });
794 if (verifiedConfigIdentity.has(session)) {
795 identity = verifiedConfigIdentity.get(session) ?? null;
796 } else if (descriptorIdentity !== null && supervisor.openingSession !== undefined) {
797 identity = descriptorIdentity;
798 verification = yield* Deferred.make<OpeningVerification>();
799 const currentVerification = verification;
800 const openingSessionRef = supervisor.openingSession;
801 const sessionSuperseded = SubscriptionRef.changes(openingSessionRef).pipe(
802 Stream.filter((opening) => Option.getOrNull(opening) !== session),
803 Stream.filterEffect(() =>
804 SubscriptionRef.get(supervisor.session).pipe(
805 Effect.map((active) => Option.getOrNull(active) !== session),
806 ),
807 ),
808 Stream.runHead,
809 Effect.andThen(Effect.fail(undefined)),
810 );
811 // Verify live config identity and flags in parallel; applyItems buffers until settled.
812 yield* Effect.raceFirst(
813 session.initialConfig,
814 Effect.raceFirst(session.closed, sessionSuperseded),
815 ).pipe(
816 Effect.matchEffect({
817 onFailure: () =>
818 Deferred.succeed(currentVerification, { kind: "rejected" }).pipe(Effect.asVoid),
819 onSuccess: (config) => {
820 if (config.environment.environmentId !== environmentId) {
821 return Deferred.succeed(currentVerification, { kind: "rejected" }).pipe(
822 Effect.asVoid,
823 );
824 }
825 const liveIdentity = shellIdentity(config.environment, config);
826 verifiedConfigIdentity.set(session, liveIdentity);
827 if (sameShellIdentity(descriptorIdentity, liveIdentity)) {
828 return Deferred.succeed(currentVerification, {
829 kind: "matched",
830 identity: liveIdentity,
831 }).pipe(Effect.asVoid);
832 }
833 return Deferred.succeed(currentVerification, {
834 kind: "mismatched",
835 identity: liveIdentity,
836 }).pipe(
837 Effect.andThen(
838 Effect.gen(function* () {
839 const active = yield* Ref.get(activeSubscription);
840 if (
841 active?.session !== session ||
842 active.verification !== currentVerification
843 ) {
844 return;
845 }
846 yield* queueMismatchReload;
847 }),
848 ),
849 );
850 },
851 }),
852 Effect.ensuring(
853 Deferred.succeed(currentVerification, { kind: "rejected" }).pipe(Effect.asVoid),
854 ),
855 Effect.forkIn(stateScope),
856 );
857 } else {
858 identity = yield* session.initialConfig.pipe(
859 Effect.map((config) => shellIdentity(config.environment, config)),
860 Effect.orElseSucceed(() => null),
861 );
862 verifiedConfigIdentity.set(session, identity);
863 }
864 const early = yield* useEarlyLoad(currentPrepared, session);
865 const earlyExit = early === null ? null : yield* awaitEarlyLoad(early, identity);
866 if (verification !== undefined) {
867 const settled = yield* pollOpeningVerification(verification);
868 if (Option.isSome(settled)) {
869 if (settled.value.kind === "matched") {
870 identity = settled.value.identity;
871 verification = undefined;
872 } else if (settled.value.kind === "mismatched") {
873 identity = settled.value.identity;
874 verification = undefined;
875 yield* Ref.set(origin, undefined);
876 }
877 }
878 }
879 const { omitIdleSubagents, omitOlderSettled } = identity ?? {
880 omitIdleSubagents: false,
881 omitOlderSettled: false,
882 };
883 // Rows the descriptor's flags or build loaded are not kept when the live config differs:
884 // their origin then cannot resume, so the load below replaces them.
885 let loaded =
886 early !== null &&
887 earlyExit !== null &&
888 identity !== null &&
889 sameShellIdentity(early.identity, identity)
890 ? Exit.isSuccess(earlyExit)
891 ? earlyExit.value
892 : ({ kind: "failed" } satisfies HttpShellOutcome)
893 : null;
894 yield* replaceActiveSubscription({
895 session,
896 identity,
897 ...(verification === undefined ? {} : { verification }),
898 });
899 if (verification !== undefined) {
900 const settled = yield* pollOpeningVerification(verification);
901 if (Option.isSome(settled) && settled.value.kind === "mismatched") {
902 yield* queueMismatchReload;
903 }
904 }
905 yield* Ref.set(awaitingCompletion, true);
906 yield* setSynchronizing;
907
908 // Rows from a recent server snapshot with the same omissions and server build resume
909 // from their cursor, in memory or from the cache. Anything else reloads the HTTP
910 // snapshot so a valid cursor cannot preserve stale or incomplete data. A `resumable`
911 // answer is checked again too: the rows can pass their age limit while the socket opens.
912 const resumingHeldRows =
913 loaded?.kind !== "snapshot" &&
914 Option.isSome((yield* SubscriptionRef.get(state)).snapshot) &&
915 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis);
916 if (!resumingHeldRows && loaded === null && !canPipelineDirectSocket(currentPrepared)) {
917 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
918 Effect.flatMap(
919 Option.match({
920 onSome: Effect.succeed,
921 onNone: () =>
922 SubscriptionRef.changes(supervisor.prepared).pipe(
923 Stream.filter(Option.isSome),
924 Stream.map((value) => value.value),
925 Stream.runHead,
926 Effect.map(Option.getOrThrow),
927 ),
928 }),
929 ),
930 );
931 loaded = yield* loadOverHttp(prepared, identity, Effect.succeed(session));
932 }
933
934 const current = yield* SubscriptionRef.get(state);
935 const omission = {
936 ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}),
937 ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}),
938 };
939 if (Option.isNone(current.snapshot) || !(resumingHeldRows || loaded?.kind === "snapshot")) {
940 return { ...omission, requestCompletionMarker: true as const };
941 }
942 return {
943 afterSequence: current.snapshot.value.snapshotSequence,
944 // Only rows the client already held may be refused; a cursor from the snapshot just
945 // loaded falls back to the socket snapshot, so a refusal cannot loop.
946 ...(resumingHeldRows ? { httpSnapshotFallback: true as const } : {}),
947 // No stream item has touched the snapshot just loaded, so its identities still hold.
948 ...(loaded?.kind === "snapshot" && loaded.projectIdentities !== undefined
949 ? { knownProjectIdentities: loaded.projectIdentities }
950 : {}),
951 ...omission,
952 requestCompletionMarker: true as const,
953 };
954 }),
955 {
956 // A defect parks the stream, so resubscribe after a backoff rather than wait for a wakeup.
957 onDefect: (cause) =>
958 setStreamError(Cause.squash(cause)).pipe(
959 Effect.andThen(Effect.sleep(subscriptionRetryDelay("250 millis", defectRetries++))),
960 Effect.andThen(Queue.offer(reloadRequests, undefined)),
961 ),
962 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
963 retryExpectedFailureAfter: "250 millis",
964 resubscribe: resubscriptions,
965 includeOpeningSession: true,
966 },
967 ).pipe(
968 Stream.runForEachArray((entries) =>
969 applyItems(entries).pipe(
970 Effect.andThen(
971 Effect.sync(() => {
972 defectRetries = 0;
973 }),
974 ),
975 ),
976 ),
977 ),
978 );
979 yield* SubscriptionRef.changes(supervisor.state).pipe(
980 Stream.runForEach((connectionState) => {
981 switch (connectionProjectionPhase(connectionState)) {
982 case "synchronizing":
983 return Effect.gen(function* () {
984 const [waiting, current, active] = yield* Effect.all([
985 Ref.get(awaitingCompletion),
986 SubscriptionRef.get(state),
987 Ref.get(activeSubscription),
988 ]);
989 if (
990 !waiting &&
991 active !== null &&
992 current.status === "live" &&
993 current.commandHistory?.synchronizedSession === active.session
994 ) {
995 return;
996 }
997 yield* setSynchronizing;
998 });
999 case "disconnected":
1000 return setDisconnected;
1001 case "ready":
1002 return setReady;
1003 }
1004 }),
1005 Effect.forkScoped,
1006 );
1007
1008 return state;
1009});
1010
1011function shellStateChanges(environmentId: EnvironmentId) {
1012 return followStreamInEnvironment(
1013 environmentId,
1014 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
1015 );
1016}
1017
1018export interface EnvironmentShellSummary {
1019 readonly hasSnapshot: boolean;
1020 readonly hasSynchronizingShell: boolean;
1021 readonly firstError: string | null;
1022}
1023
1024const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
1025 hasSnapshot: false,
1026 hasSynchronizingShell: false,
1027 firstError: null,
1028});
1029
1030const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
1031
1032function shellSummariesEqual(
1033 left: EnvironmentShellSummary,
1034 right: EnvironmentShellSummary,
1035): boolean {
1036 return (
1037 left.hasSnapshot === right.hasSnapshot &&
1038 left.hasSynchronizingShell === right.hasSynchronizingShell &&
1039 left.firstError === right.firstError
1040 );
1041}
1042
1043function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
1044 if (left.size !== right.size) {
1045 return false;
1046 }
1047 for (const [key, value] of left) {
1048 if (right.get(key) !== value) {
1049 return false;
1050 }
1051 }
1052 return true;
1053}
1054
1055export function createEnvironmentShellSummaryAtom(input: {
1056 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
1057 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
1058}) {
1059 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
1060 return Atom.make((get) => {
1061 let hasSnapshot = false;
1062 let hasSynchronizingShell = false;
1063 let firstError: string | null = null;
1064
1065 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
1066 const state = get(input.shellStateValueAtom(environmentId));
1067 hasSynchronizingShell ||= state.status === "synchronizing";
1068 if (firstError === null) {
1069 firstError = Option.getOrNull(state.error);
1070 }
1071 if (Option.isNone(state.snapshot)) {
1072 continue;
1073 }
1074 hasSnapshot = true;
1075 }
1076
1077 const next: EnvironmentShellSummary = {
1078 hasSnapshot,
1079 hasSynchronizingShell,
1080 firstError,
1081 };
1082 if (shellSummariesEqual(previousSummary, next)) {
1083 return previousSummary;
1084 }
1085 previousSummary = next;
1086 return previousSummary;
1087 }).pipe(Atom.withLabel("environment-shell-summary"));
1088}
1089
1090export function createEnvironmentServerConfigsAtom(input: {
1091 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
1092 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
1093}) {
1094 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
1095 return Atom.make((get) => {
1096 const next = new Map<EnvironmentId, ServerConfig>();
1097 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
1098 const config = get(input.serverConfigValueAtom(environmentId));
1099 if (config !== null) {
1100 next.set(environmentId, config);
1101 }
1102 }
1103 if (mapsEqual(previousServerConfigs, next)) {
1104 return previousServerConfigs;
1105 }
1106 previousServerConfigs = next;
1107 return previousServerConfigs;
1108 }).pipe(Atom.withLabel("environment-server-configs"));
1109}
1110
1111/**
1112 * Every shell push replaces the state, so views that gate on load progress read these
1113 * primitives instead and stay put while threads stream.
1114 */
1115function createEnvironmentShellProgressAtoms(
1116 stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,
1117) {
1118 return {
1119 statusAtom: Atom.family((environmentId: EnvironmentId) =>
1120 Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(
1121 Atom.withLabel(`environment-shell-status:${environmentId}`),
1122 ),
1123 ),
1124 hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>
1125 Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(
1126 Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),
1127 ),
1128 ),
1129 };
1130}
1131
1132export function createEnvironmentShellAtoms<R, E>(
1133 runtime: Atom.AtomRuntime<
1134 | EnvironmentRegistry.EnvironmentRegistry
1135 | Persistence.EnvironmentCacheStore
1136 | ShellSnapshotLoader.ShellSnapshotLoader
1137 | R,
1138 E
1139 >,
1140) {
1141 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
1142 runtime.atom(shellStateChanges(environmentId), {
1143 initialValue: EMPTY_SHELL_STATE,
1144 }),
1145 );
1146
1147 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
1148 Atom.make((get) =>
1149 AsyncResult.getOrElse(get(stateAtom(environmentId)), () => EMPTY_SHELL_STATE),
1150 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
1151 );
1152
1153 const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);
1154
1155 return {
1156 stateAtom,
1157 stateValueAtom,
1158 commandHistoryAtom: Atom.family((id: EnvironmentId) =>
1159 Atom.make((get) => get(stateValueAtom(id)).commandHistory),
1160 ),
1161 statusAtom,
1162 hasSnapshotAtom,
1163 };
1164}
1165
1166export * from "./models.ts";
1167export * from "./shellCommands.ts";
1168export * from "./shellReducer.ts";
1169export * from "./shellPullRequests.ts";
1170export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
1171export * from "./snapshots.ts";
1172export * from "./steadyShells.ts";