fix(orchestrator): hydrate shell cache and group multi-environment projects (#3640)

Restore versioned shell-cache hydration, reconcile repository enrichment across multiple environments, and decode non-null settled shell timestamps correctly.
This commit is contained in:
Mike Olson authored and GitHub committed 2026-07-24 16:49:21 +02:00
1 parent c6b0ceba5d
commit aee7ff39d7
17 files changed
+1558 -62

No files matched your search

@@ -1,5 +1,11 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import {
EnvironmentId,
MessageId,
RuntimeRequestId,
type OrchestrationV2ShellSnapshot,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -10,28 +16,91 @@ import {
StoredOrchestrationThreadSnapshot,
decodeOrDiscardOrchestrationCache,
} from "./orchestrationCache.ts";
import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
import {
v2Now,
v2Projection,
v2ShellSnapshot,
v2ThreadShell,
v2ThreadId,
} from "../state/orchestrationV2TestFixtures.ts";
const environmentId = EnvironmentId.make("environment-cache-test");
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredOrchestrationShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredOrchestrationThreadSnapshot);
const StoredShellSnapshotJson = Schema.fromJsonString(StoredOrchestrationShellSnapshot);
const StoredThreadSnapshotJson = Schema.fromJsonString(StoredOrchestrationThreadSnapshot);
const encodeStoredShellSnapshot = Schema.encodeSync(StoredOrchestrationShellSnapshot);
const decodeStoredShellSnapshotSync = Schema.decodeUnknownSync(StoredOrchestrationShellSnapshot);
const encodeStoredShellSnapshotJson = Schema.encodeSync(StoredShellSnapshotJson);
const decodeStoredShellSnapshotJson = Schema.decodeUnknownSync(StoredShellSnapshotJson);
const encodeStoredThreadSnapshotJson = Schema.encodeSync(StoredThreadSnapshotJson);
const decodeStoredThreadSnapshotJson = Schema.decodeUnknownSync(StoredThreadSnapshotJson);
class TestCacheDecodeError extends Schema.TaggedErrorClass<TestCacheDecodeError>()(
"TestCacheDecodeError",
{
message: Schema.String,
},
) {}
const shellSnapshotWithSummaries: OrchestrationV2ShellSnapshot = {
...v2ShellSnapshot,
threads: [
{
...v2ThreadShell,
pendingRuntimeRequest: {
id: RuntimeRequestId.make("runtime-request-v2"),
kind: "command",
createdAt: v2Now,
},
latestVisibleMessage: {
id: MessageId.make("message-v2"),
role: "assistant",
text: "Done",
updatedAt: v2Now,
},
latestUserMessageAt: v2Now,
settledAt: v2Now,
},
],
};
describe("orchestration cache envelopes", () => {
it.effect("accepts V2 shell and thread cache envelopes", () =>
Effect.gen(function* () {
const shell = yield* decodeStoredShellSnapshot({
it.effect("round-trips V2 shell and thread cache envelopes as JSON", () =>
Effect.sync(() => {
const encodedShell = encodeStoredShellSnapshotJson({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
snapshot: v2ShellSnapshot,
snapshot: shellSnapshotWithSummaries,
});
const thread = yield* decodeStoredThreadSnapshot({
const shell = decodeStoredShellSnapshotJson(encodedShell);
const encodedThread = encodeStoredThreadSnapshotJson({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
threadId: v2ThreadId,
snapshot: { snapshotSequence: 4, projection: v2Projection },
});
const thread = decodeStoredThreadSnapshotJson(encodedThread);
const [threadShell] = shell.snapshot.threads;
expect(shell.snapshot).toEqual(v2ShellSnapshot);
expect(threadShell?.latestVisibleMessage?.text).toBe("Done");
expect(
threadShell?.latestVisibleMessage === null ||
threadShell?.latestVisibleMessage === undefined
? null
: DateTime.formatIso(threadShell.latestVisibleMessage.updatedAt),
).toBe("2026-06-20T00:00:00.000Z");
expect(
threadShell?.latestUserMessageAt === null || threadShell?.latestUserMessageAt === undefined
? null
: DateTime.formatIso(threadShell.latestUserMessageAt),
).toBe("2026-06-20T00:00:00.000Z");
expect(
threadShell?.settledAt === null || threadShell?.settledAt === undefined
? null
: DateTime.formatIso(threadShell.settledAt),
).toBe("2026-06-20T00:00:00.000Z");
expect(DateTime.formatIso(thread.snapshot.projection.thread.updatedAt)).toBe(
"2026-06-20T00:00:00.000Z",
);
expect(thread.snapshot.projection).toEqual(v2Projection);
expect(thread.snapshot.snapshotSequence).toBe(4);
}),
@@ -40,10 +109,14 @@ describe("orchestration cache envelopes", () => {
it.effect("discards V1-versioned cache envelopes after a decode failure", () =>
Effect.gen(function* () {
let discardCount = 0;
const decoded = decodeStoredShellSnapshot({
schemaVersion: 1,
const encodedShell = encodeStoredShellSnapshot({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
snapshot: v2ShellSnapshot,
});
const decoded = Effect.try({
try: () => decodeStoredShellSnapshotSync({ ...encodedShell, schemaVersion: 1 }),
catch: (cause) => new TestCacheDecodeError({ message: String(cause) }),
}).pipe(Effect.map(Option.some));
const result = yield* decodeOrDiscardOrchestrationCache(
@@ -1,7 +1,8 @@
import {
EnvironmentId,
OrchestrationV2ShellSnapshot,
OrchestrationV2ShellSnapshotJson,
OrchestrationV2ThreadDetailSnapshot,
OrchestrationV2ThreadProjectionJson,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -13,14 +14,17 @@ export const ORCHESTRATION_CACHE_SCHEMA_VERSION = 3 as const;
export const StoredOrchestrationShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationV2ShellSnapshot,
snapshot: OrchestrationV2ShellSnapshotJson,
});
export const StoredOrchestrationThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
snapshot: OrchestrationV2ThreadDetailSnapshot,
snapshot: OrchestrationV2ThreadDetailSnapshot.mapFields((fields) => ({
...fields,
projection: OrchestrationV2ThreadProjectionJson,
})),
});
/** Invalid orchestration caches are disposable and must never block live synchronization. */
@@ -5,10 +5,14 @@ import {
type OrchestrationV2ShellStreamItem,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
@@ -23,7 +27,7 @@ import * as Persistence from "../platform/persistence.ts";
import * as RpcSession from "../rpc/session.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
import { v2Project, v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -78,7 +82,7 @@ describe("environment shell synchronization", () => {
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: () => Effect.never,
saveShell: () => Effect.void,
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
@@ -320,4 +324,415 @@ describe("environment shell synchronization", () => {
expect(yield* Ref.get(subscriptionCount)).toBe(2);
}),
);
it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
Effect.gen(function* () {
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
const saveStarted = yield* Deferred.make<void>();
const releaseSave = yield* Deferred.make<void>();
const client = {
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(session(client)),
);
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: activeSession,
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: (_environmentId, snapshot) =>
Deferred.succeed(saveStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseSave)),
Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
),
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const snapshotLoader = ShellSnapshotLoader.of({
load: () => Effect.succeed(Option.none()),
});
const shellState = yield* makeEnvironmentShellState().pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ShellSnapshotLoader, snapshotLoader),
);
yield* SubscriptionRef.set(supervisorState, {
desired: true,
network: "online",
phase: "connecting",
stage: "synchronizing",
attempt: 1,
generation: 0,
lastFailure: null,
retryAt: null,
});
yield* Queue.offer(events, {
kind: "snapshot",
snapshot: LIVE_SHELL_SNAPSHOT,
});
yield* Queue.offer(events, { kind: "synchronized" });
yield* SubscriptionRef.changes(shellState).pipe(
Stream.filter((state) => state.status === "live"),
Stream.runHead,
);
yield* SubscriptionRef.set(supervisorState, {
desired: true,
network: "online",
phase: "connecting",
stage: "synchronizing",
attempt: 2,
generation: 1,
lastFailure: null,
retryAt: null,
});
yield* SubscriptionRef.set(supervisorState, {
desired: false,
network: "online",
phase: "available",
stage: null,
attempt: 2,
generation: 2,
lastFailure: null,
retryAt: null,
});
yield* Deferred.await(saveStarted);
yield* SubscriptionRef.set(supervisorState, {
desired: true,
network: "online",
phase: "connecting",
stage: "synchronizing",
attempt: 3,
generation: 3,
lastFailure: null,
retryAt: null,
});
for (let index = 0; index < 100; index += 1) {
if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
yield* Effect.yieldNow;
}
expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
expect(yield* Ref.get(saved)).toEqual([]);
yield* Deferred.succeed(releaseSave, undefined);
for (let index = 0; index < 100; index += 1) {
if ((yield* Ref.get(saved)).length > 0) break;
yield* Effect.yieldNow;
}
expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
}),
);
it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
Effect.gen(function* () {
const repositoryIdentity = {
canonicalKey: "github.com/example/repo",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://github.com/example/repo.git",
},
};
const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
...LIVE_SHELL_SNAPSHOT,
snapshotSequence: 1,
projects: [{ ...v2Project, repositoryIdentity: null }],
};
const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
...LIVE_SHELL_SNAPSHOT,
snapshotSequence: 1,
projects: [{ ...v2Project, repositoryIdentity }],
};
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
const unenrichedSaveStarted = yield* Deferred.make<void>();
const releaseUnenrichedSave = yield* Deferred.make<void>();
const client = {
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(session(client)),
);
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: activeSession,
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: (_environmentId, snapshot) =>
Effect.gen(function* () {
if (snapshot.projects[0]?.repositoryIdentity == null) {
yield* Deferred.succeed(unenrichedSaveStarted, undefined);
yield* Deferred.await(releaseUnenrichedSave);
}
yield* Ref.update(saved, (values) => [...values, snapshot]);
}),
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const snapshotLoader = ShellSnapshotLoader.of({
load: () => Effect.succeed(Option.none()),
});
const shellState = yield* makeEnvironmentShellState().pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ShellSnapshotLoader, snapshotLoader),
);
yield* SubscriptionRef.set(supervisorState, {
desired: true,
network: "online",
phase: "connecting",
stage: "synchronizing",
attempt: 1,
generation: 0,
lastFailure: null,
retryAt: null,
});
yield* Queue.offer(events, {
kind: "snapshot",
snapshot: unenrichedSnapshot,
});
yield* Queue.offer(events, { kind: "synchronized" });
yield* SubscriptionRef.changes(shellState).pipe(
Stream.filter((state) => state.status === "live"),
Stream.runHead,
);
// Disconnect flush starts an immediate persist of the unenriched snapshot
// (debounced path needs TestClock advancement; flush does not).
yield* SubscriptionRef.set(supervisorState, {
desired: false,
network: "online",
phase: "available",
stage: null,
attempt: 1,
generation: 1,
lastFailure: null,
retryAt: null,
});
yield* Deferred.await(unenrichedSaveStarted);
// Same sequence, different content. Session stays open so the stream can
// still apply enrichment while the older save is in flight.
yield* Queue.offer(events, {
kind: "snapshot",
snapshot: enrichedSnapshot,
});
yield* SubscriptionRef.changes(shellState).pipe(
Stream.filter(
(state) =>
Option.isSome(state.snapshot) &&
state.snapshot.value.projects[0]?.repositoryIdentity != null,
),
Stream.runHead,
);
// Completing the older same-sequence save must re-persist the latest object.
yield* Deferred.succeed(releaseUnenrichedSave, undefined);
for (let index = 0; index < 100; index += 1) {
const values = yield* Ref.get(saved);
if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
break;
}
yield* Effect.yieldNow;
}
const finalSaved = (yield* Ref.get(saved)).at(-1);
expect(finalSaved?.snapshotSequence).toBe(1);
expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
}),
);
it.effect("scope teardown flush stays stable while a save is blocked", () =>
Effect.gen(function* () {
const lateSnapshot: OrchestrationV2ShellSnapshot = {
...LIVE_SHELL_SNAPSHOT,
snapshotSequence: 2,
projects: [{ ...v2Project, title: "Late stream event" }],
};
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
const saveStarted = yield* Deferred.make<void>();
const releaseSave = yield* Deferred.make<void>();
const client = {
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(session(client)),
);
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: activeSession,
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: (_environmentId, snapshot) =>
Deferred.succeed(saveStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseSave)),
Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
),
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const snapshotLoader = ShellSnapshotLoader.of({
load: () => Effect.succeed(Option.none()),
});
const scope = yield* Scope.make();
const shellState = yield* makeEnvironmentShellState().pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ShellSnapshotLoader, snapshotLoader),
Scope.provide(scope),
);
yield* SubscriptionRef.set(supervisorState, {
desired: true,
network: "online",
phase: "connecting",
stage: "synchronizing",
attempt: 1,
generation: 0,
lastFailure: null,
retryAt: null,
});
yield* Queue.offer(events, {
kind: "snapshot",
snapshot: LIVE_SHELL_SNAPSHOT,
});
yield* Queue.offer(events, { kind: "synchronized" });
yield* SubscriptionRef.changes(shellState).pipe(
Stream.filter((state) => state.status === "live"),
Stream.runHead,
);
// Close scope so the finalizer flush blocks on save. Workers must be
// interrupted before that flush; late stream events must not extend it.
const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
yield* Deferred.await(saveStarted);
yield* Queue.offer(events, {
kind: "snapshot",
snapshot: lateSnapshot,
});
for (let index = 0; index < 50; index += 1) {
yield* Effect.yieldNow;
}
yield* Deferred.succeed(releaseSave, undefined);
yield* Fiber.join(closeFiber);
const values = yield* Ref.get(saved);
expect(values.length).toBeGreaterThan(0);
expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
true,
);
}),
);
it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
Effect.gen(function* () {
const cachedSnapshot: OrchestrationV2ShellSnapshot = {
...v2ShellSnapshot,
snapshotSequence: 20,
projects: [{ ...v2Project, title: "Client ahead" }],
};
const httpSnapshot: OrchestrationV2ShellSnapshot = {
...v2ShellSnapshot,
snapshotSequence: 4,
projects: [{ ...v2Project, title: "Server reset" }],
};
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
const client = {
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: yield* SubscriptionRef.make(Option.some(session(client))),
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
saveShell: () => Effect.void,
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const snapshotLoader = ShellSnapshotLoader.of({
load: () => Effect.succeed(Option.some(httpSnapshot)),
});
const shellState = yield* makeEnvironmentShellState().pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ShellSnapshotLoader, snapshotLoader),
);
yield* SubscriptionRef.changes(shellState).pipe(
Stream.filter(
(state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
),
Stream.runHead,
);
const state = yield* SubscriptionRef.get(shellState);
expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
}),
);
});
+47 -11
View File
@@ -23,7 +23,7 @@ import { safeErrorLogAttributes } from "../errors/safeLog.ts";
import { EnvironmentCacheStore } from "../platform/persistence.ts";
import { subscribeDynamic } from "../rpc/client.ts";
import { ShellSnapshotLoader } from "./shellSnapshotHttp.ts";
import { applyShellStreamEvent } from "./shellReducer.ts";
import { applyShellStreamEvent, mergeShellSnapshotProjects } from "./shellReducer.ts";
import type { EnvironmentCatalogState } from "./connections.ts";
import { followStreamInEnvironment } from "./runtime.ts";
@@ -72,23 +72,48 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
error: Option.none(),
});
const awaitingCompletion = yield* Ref.make(false);
const latestLiveSnapshot = yield* Ref.make<Option.Option<OrchestrationV2ShellSnapshot>>(
Option.none(),
);
const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
const persist = Effect.fn("EnvironmentShellState.persist")(function* (
snapshot: OrchestrationV2ShellSnapshot,
) {
yield* cache.saveShell(environmentId, snapshot).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not persist environment shell cache.").pipe(
Effect.annotateLogs({
environmentId,
...safeErrorLogAttributes(error),
}),
let nextSnapshot = snapshot;
while (true) {
yield* cache.saveShell(environmentId, nextSnapshot).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not persist environment shell cache.").pipe(
Effect.annotateLogs({
environmentId,
...safeErrorLogAttributes(error),
}),
),
),
),
);
);
const latestSnapshot = yield* Ref.get(latestLiveSnapshot);
// Same sequence can still mean newer content (e.g. repository enrichment).
if (Option.isNone(latestSnapshot) || latestSnapshot.value === nextSnapshot) {
return;
}
nextSnapshot = latestSnapshot.value;
}
});
const flushLiveShellSnapshot = Effect.gen(function* () {
const snapshot = yield* Ref.get(latestLiveSnapshot);
if (Option.isNone(snapshot)) {
return;
}
yield* persist(snapshot.value);
});
// Register before scoped worker fibers so reverse finalizer order interrupts
// those fibers first and this flush sees a stable latestLiveSnapshot.
yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
yield* Stream.fromQueue(persistence).pipe(
Stream.debounce("500 millis"),
Stream.runForEach(persist),
@@ -102,6 +127,8 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
status: shellStatusForSnapshot(current.snapshot),
})),
),
Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
Effect.asVoid,
);
const setSynchronizing = SubscriptionRef.update(state, (current) => ({
...current,
@@ -149,7 +176,15 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
const current = yield* SubscriptionRef.get(state);
const nextSnapshot =
item.kind === "snapshot"
? item.snapshot
? mergeShellSnapshotProjects(
Option.getOrNull(current.snapshot),
item.snapshot,
item.resolvedRepositoryIdentityRoots === undefined
? undefined
: {
resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,
},
)
: Option.match(current.snapshot, {
onNone: () => null,
onSome: (snapshot) =>
@@ -161,6 +196,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
return;
}
yield* Ref.set(latestLiveSnapshot, Option.some(nextSnapshot));
const waiting = yield* Ref.get(awaitingCompletion);
yield* SubscriptionRef.set(state, {
snapshot: Option.some(nextSnapshot),
@@ -2,7 +2,25 @@ import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
import { applyShellStreamEvent } from "./shellReducer.ts";
import { applyShellStreamEvent, mergeShellSnapshotProjects } from "./shellReducer.ts";
const repositoryIdentity = {
canonicalKey: "github.com/example/repo",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://github.com/example/repo.git",
},
};
const otherIdentity = {
canonicalKey: "github.com/example/other",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://github.com/example/other.git",
},
};
describe("applyShellStreamEvent", () => {
it("ignores stale project updates without mutating the snapshot", () => {
@@ -42,6 +60,312 @@ describe("applyShellStreamEvent", () => {
expect(removed.projects).toEqual([]);
});
it("keeps prior repositoryIdentity when a delta arrives with null identity", () => {
const withIdentity = applyShellStreamEvent(v2ShellSnapshot, {
kind: "project.updated",
sequence: 1,
project: { ...v2Project, repositoryIdentity },
});
expect(withIdentity.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
const withoutIdentity = applyShellStreamEvent(withIdentity, {
kind: "project.updated",
sequence: 2,
project: { ...v2Project, title: "Still same root", repositoryIdentity: null },
});
expect(withoutIdentity.projects[0]?.title).toBe("Still same root");
expect(withoutIdentity.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
});
it("does not keep prior repositoryIdentity after a workspace root move", () => {
const withIdentity = applyShellStreamEvent(v2ShellSnapshot, {
kind: "project.updated",
sequence: 1,
project: { ...v2Project, repositoryIdentity },
});
const moved = applyShellStreamEvent(withIdentity, {
kind: "project.updated",
sequence: 2,
project: {
...v2Project,
workspaceRoot: "/tmp/other-root",
repositoryIdentity: null,
},
});
expect(moved.projects[0]?.workspaceRoot).toBe("/tmp/other-root");
expect(moved.projects[0]?.repositoryIdentity).toBeNull();
});
it("merges full snapshot projects without dropping known repositoryIdentity", () => {
const previous = {
...v2ShellSnapshot,
projects: [{ ...v2Project, repositoryIdentity }],
};
const next = mergeShellSnapshotProjects(previous, {
...v2ShellSnapshot,
snapshotSequence: 2,
projects: [{ ...v2Project, title: "Refreshed", repositoryIdentity: null }],
});
expect(next.projects[0]?.title).toBe("Refreshed");
expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
});
it("authoritative lower-sequence reset replaces client-ahead structural state", () => {
const previous = {
...v2ShellSnapshot,
snapshotSequence: 9,
projects: [{ ...v2Project, title: "Client ahead", repositoryIdentity }],
threads: [{ ...v2ThreadShell, title: "Local-only thread" }],
};
const next = mergeShellSnapshotProjects(previous, {
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [{ ...v2Project, title: "Server reset", repositoryIdentity: null }],
threads: [{ ...v2ThreadShell, title: "Server thread" }],
});
expect(next.snapshotSequence).toBe(3);
expect(next.projects[0]?.title).toBe("Server reset");
expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
expect(next.threads[0]?.title).toBe("Server thread");
});
it("client-ahead survives lower marked enrichment then still resets on unmarked authoritative", () => {
const previous = {
...v2ShellSnapshot,
snapshotSequence: 20,
projects: [{ ...v2Project, title: "Client ahead", repositoryIdentity }],
threads: [{ ...v2ThreadShell, title: "Local-only thread" }],
};
const serverSnapshot = {
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [{ ...v2Project, title: "Server reset", repositoryIdentity: null }],
threads: [{ ...v2ThreadShell, title: "Server thread" }],
};
// Lower-sequence marked enrichment is identity-only and must not replace structure.
const afterEnrichment = mergeShellSnapshotProjects(previous, serverSnapshot, {
resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot],
});
expect(afterEnrichment.snapshotSequence).toBe(20);
expect(afterEnrichment.projects[0]?.title).toBe("Client ahead");
expect(afterEnrichment.projects[0]?.repositoryIdentity).toBeNull();
expect(afterEnrichment.threads[0]?.title).toBe("Local-only thread");
// Unmarked authoritative at the same lower sequence still performs the reset.
const afterAuthoritative = mergeShellSnapshotProjects(afterEnrichment, serverSnapshot);
expect(afterAuthoritative.snapshotSequence).toBe(3);
expect(afterAuthoritative.projects[0]?.title).toBe("Server reset");
expect(afterAuthoritative.projects[0]?.repositoryIdentity).toBeNull();
expect(afterAuthoritative.threads[0]?.title).toBe("Server thread");
});
it("authoritative null retains identity then same-sequence marked enrichment clears it", () => {
const previous = {
...v2ShellSnapshot,
snapshotSequence: 9,
projects: [{ ...v2Project, title: "Client ahead", repositoryIdentity }],
threads: [{ ...v2ThreadShell, title: "Local-only thread" }],
};
const serverSnapshot = {
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [{ ...v2Project, title: "Server reset", repositoryIdentity: null }],
threads: [{ ...v2ThreadShell, title: "Server thread" }],
};
const afterAuthoritative = mergeShellSnapshotProjects(previous, serverSnapshot);
expect(afterAuthoritative.snapshotSequence).toBe(3);
expect(afterAuthoritative.projects[0]?.title).toBe("Server reset");
expect(afterAuthoritative.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
expect(afterAuthoritative.threads[0]?.title).toBe("Server thread");
const afterEnrichment = mergeShellSnapshotProjects(afterAuthoritative, serverSnapshot, {
resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot],
});
expect(afterEnrichment.snapshotSequence).toBe(3);
expect(afterEnrichment.projects[0]?.title).toBe("Server reset");
expect(afterEnrichment.projects[0]?.repositoryIdentity).toBeNull();
expect(afterEnrichment.threads[0]?.title).toBe("Server thread");
});
it("takes identity from a lower-sequence enrichment without reverting live thread state", () => {
const previous = {
...v2ShellSnapshot,
snapshotSequence: 5,
projects: [{ ...v2Project, repositoryIdentity: null }],
threads: [{ ...v2ThreadShell, title: "Newest title" }],
};
const next = mergeShellSnapshotProjects(
previous,
{
...v2ShellSnapshot,
snapshotSequence: 4,
projects: [{ ...v2Project, repositoryIdentity }],
threads: [{ ...v2ThreadShell, title: "Stale title" }],
},
{ resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot] },
);
expect(next.snapshotSequence).toBe(5);
expect(next.threads[0]?.title).toBe("Newest title");
expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
});
it("lower-sequence enrichment cannot resurrect empty structural state", () => {
const previous = {
...v2ShellSnapshot,
snapshotSequence: 7,
projects: [],
threads: [],
archivedThreads: [],
};
const next = mergeShellSnapshotProjects(
previous,
{
...v2ShellSnapshot,
snapshotSequence: 4,
projects: [{ ...v2Project, repositoryIdentity }],
threads: [v2ThreadShell],
},
{ resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot] },
);
expect(next.snapshotSequence).toBe(7);
expect(next.projects).toEqual([]);
expect(next.threads).toEqual([]);
});
it("resolved null clears identity only for the marked root", () => {
const otherProject = {
...v2Project,
id: ProjectId.make("project-other"),
workspaceRoot: "/workspace/other",
repositoryIdentity: otherIdentity,
};
const previous = {
...v2ShellSnapshot,
snapshotSequence: 5,
projects: [{ ...v2Project, repositoryIdentity }, otherProject],
};
const next = mergeShellSnapshotProjects(
previous,
{
...v2ShellSnapshot,
snapshotSequence: 4,
projects: [
{ ...v2Project, repositoryIdentity: null },
{ ...otherProject, repositoryIdentity: null },
],
},
{ resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot] },
);
expect(next.snapshotSequence).toBe(5);
expect(next.projects).toHaveLength(2);
expect(next.projects[0]?.repositoryIdentity).toBeNull();
expect(next.projects[1]?.repositoryIdentity).toEqual(otherIdentity);
});
it("unrelated unresolved roots retain identity in the same enrichment snapshot", () => {
const otherProject = {
...v2Project,
id: ProjectId.make("project-other"),
workspaceRoot: "/workspace/other",
repositoryIdentity: otherIdentity,
};
const previous = {
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [{ ...v2Project, repositoryIdentity }, otherProject],
threads: [{ ...v2ThreadShell, title: "Current thread" }],
};
const next = mergeShellSnapshotProjects(
previous,
{
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [
{ ...v2Project, repositoryIdentity },
{ ...otherProject, repositoryIdentity: null },
],
threads: [{ ...v2ThreadShell, title: "Stale thread" }],
},
{ resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot] },
);
expect(next.threads[0]?.title).toBe("Current thread");
expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
expect(next.projects[1]?.repositoryIdentity).toEqual(otherIdentity);
});
it("clears identity for multiple roots resolved in one enrichment batch", () => {
const otherProject = {
...v2Project,
id: ProjectId.make("project-other"),
workspaceRoot: "/workspace/other",
repositoryIdentity: otherIdentity,
};
const previous = {
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [{ ...v2Project, repositoryIdentity }, otherProject],
};
const next = mergeShellSnapshotProjects(
previous,
{
...v2ShellSnapshot,
snapshotSequence: 3,
projects: [
{ ...v2Project, repositoryIdentity: null },
{ ...otherProject, repositoryIdentity: null },
],
},
{
resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot, otherProject.workspaceRoot],
},
);
expect(next.projects.map((project) => project.repositoryIdentity)).toEqual([null, null]);
});
it("does not replace a live identity with one from an unmarked lower-sequence enrichment", () => {
const liveIdentity = {
canonicalKey: "github.com/example/live",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://github.com/example/live.git",
},
};
const staleIdentity = {
canonicalKey: "github.com/example/stale",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "https://github.com/example/stale.git",
},
};
const next = mergeShellSnapshotProjects(
{
...v2ShellSnapshot,
snapshotSequence: 5,
projects: [{ ...v2Project, repositoryIdentity: liveIdentity }],
},
{
...v2ShellSnapshot,
snapshotSequence: 4,
projects: [{ ...v2Project, repositoryIdentity: staleIdentity }],
},
{ resolvedRepositoryIdentityRoots: [] },
);
expect(next.snapshotSequence).toBe(5);
expect(next.projects[0]?.repositoryIdentity).toEqual(liveIdentity);
});
it("moves a thread between active and archive without duplicating it", () => {
const archived = applyShellStreamEvent(v2ShellSnapshot, {
kind: "thread.updated",
@@ -1,4 +1,5 @@
import type {
OrchestrationProjectShell,
OrchestrationV2ShellSnapshot,
OrchestrationV2ShellStreamItem,
} from "@t3tools/contracts";
@@ -12,6 +13,85 @@ function upsertById<T extends { readonly id: unknown }>(
return items.map((candidate, candidateIndex) => (candidateIndex === index ? item : candidate));
}
function retainRepositoryIdentity(
previous: OrchestrationProjectShell | undefined,
next: OrchestrationProjectShell,
): OrchestrationProjectShell {
if (
next.repositoryIdentity == null &&
previous?.repositoryIdentity != null &&
previous.workspaceRoot === next.workspaceRoot
) {
return { ...next, repositoryIdentity: previous.repositoryIdentity };
}
return next;
}
export interface MergeShellSnapshotOptions {
/**
* Enrichment refresh: structure and sequence must not roll back when at or
* below cache; listed roots accept identity exactly (including null).
* Omit this options object for authoritative HTTP/initial WebSocket snapshots.
*/
readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
}
/**
* Merge an incoming full shell snapshot into prior client state.
*
* Authoritative snapshots (no options) replace structure and sequence even when
* lower than cache, while retaining a prior non-null identity when the candidate
* is still unresolved/null for the same root.
*
* Enrichment snapshots (options present) never resurrect or roll back
* projects/threads/archives/sequence when at or below cache; they only patch
* repository identity for matching current projects.
*/
export function mergeShellSnapshotProjects(
previous: OrchestrationV2ShellSnapshot | null | undefined,
next: OrchestrationV2ShellSnapshot,
options?: MergeShellSnapshotOptions,
): OrchestrationV2ShellSnapshot {
if (previous === null || previous === undefined) {
return next;
}
const isEnrichment = options !== undefined;
const resolvedRootSet = isEnrichment ? new Set(options.resolvedRepositoryIdentityRoots) : null;
if (isEnrichment && next.snapshotSequence <= previous.snapshotSequence) {
const nextById = new Map(next.projects.map((project) => [project.id, project] as const));
return {
...previous,
projects: previous.projects.map((project) => {
const candidate = nextById.get(project.id);
if (candidate === undefined || candidate.workspaceRoot !== project.workspaceRoot) {
return project;
}
if (resolvedRootSet?.has(project.workspaceRoot) === true) {
return { ...project, repositoryIdentity: candidate.repositoryIdentity };
}
if (project.repositoryIdentity == null && candidate.repositoryIdentity != null) {
return { ...project, repositoryIdentity: candidate.repositoryIdentity };
}
return project;
}),
};
}
const previousById = new Map(previous.projects.map((project) => [project.id, project] as const));
return {
...next,
projects: next.projects.map((project) => {
const prior = previousById.get(project.id);
if (resolvedRootSet?.has(project.workspaceRoot) === true) {
return project;
}
return retainRepositoryIdentity(prior, project);
}),
};
}
/** Applies one committed V2 shell delta while preserving active/archive exclusivity. */
export function applyShellStreamEvent(
snapshot: OrchestrationV2ShellSnapshot,
@@ -23,12 +103,19 @@ export function applyShellStreamEvent(
if (event.sequence <= snapshot.snapshotSequence) return snapshot;
switch (event.kind) {
case "project.updated":
case "project.updated": {
// Enrichment is async. A project mutation can land with null
// repositoryIdentity while an earlier snapshot already resolved it.
// Keep the prior identity for the same workspace root so multi-env
// grouping does not split until a full snapshot refresh arrives.
const previous = snapshot.projects.find((project) => project.id === event.project.id);
const project = retainRepositoryIdentity(previous, event.project);
return {
...snapshot,
projects: upsertById(snapshot.projects, event.project),
projects: upsertById(snapshot.projects, project),
snapshotSequence: event.sequence,
};
}
case "project.removed":
return {
...snapshot,