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:
1 parent
c6b0ceba5d
commit
aee7ff39d7
17 files changed
+1558
-62
No files matched your search
@@ -1,7 +1,14 @@
|
||||
import type { ApplicationStoredEvent } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type { ApplicationStoredEvent, OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { coalesceShellApplicationEvents } from "./ShellStream.ts";
|
||||
import {
|
||||
coalesceShellApplicationEvents,
|
||||
composeShellStreamWithEnrichment,
|
||||
shellStreamItemFromEnrichmentRefresh,
|
||||
shellStreamItemsFromInitialSnapshot,
|
||||
} from "./ShellStream.ts";
|
||||
|
||||
function project(sequence: number, id: string): ApplicationStoredEvent {
|
||||
return {
|
||||
@@ -18,6 +25,14 @@ function thread(sequence: number, id: string): ApplicationStoredEvent {
|
||||
} as ApplicationStoredEvent;
|
||||
}
|
||||
|
||||
const emptyShellSnapshot = {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
archivedThreads: [],
|
||||
} as OrchestrationV2ShellSnapshot;
|
||||
|
||||
describe("coalesceShellApplicationEvents", () => {
|
||||
it("keeps the newest event per aggregate and preserves sequence order", () => {
|
||||
expect(
|
||||
@@ -31,3 +46,131 @@ describe("coalesceShellApplicationEvents", () => {
|
||||
).toEqual([4, 5, 6]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shellStreamItemFromEnrichmentRefresh", () => {
|
||||
it("batches nearby completion roots onto one snapshot item", () => {
|
||||
expect(
|
||||
shellStreamItemFromEnrichmentRefresh({
|
||||
snapshot: emptyShellSnapshot,
|
||||
changes: [
|
||||
{ workspaceRoot: "/workspace/a" },
|
||||
{ workspaceRoot: "/workspace/b" },
|
||||
{ workspaceRoot: "/workspace/a" },
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "snapshot",
|
||||
snapshot: emptyShellSnapshot,
|
||||
resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/b"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("shellStreamItemsFromInitialSnapshot", () => {
|
||||
it("emits unmarked authoritative then same-sequence marked enrichment when roots resolved", () => {
|
||||
const snapshot = {
|
||||
...emptyShellSnapshot,
|
||||
snapshotSequence: 7,
|
||||
} as OrchestrationV2ShellSnapshot;
|
||||
|
||||
expect(
|
||||
shellStreamItemsFromInitialSnapshot({
|
||||
snapshot,
|
||||
resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/a"],
|
||||
}),
|
||||
).toEqual([
|
||||
{ kind: "snapshot", snapshot },
|
||||
{
|
||||
kind: "snapshot",
|
||||
snapshot,
|
||||
resolvedRepositoryIdentityRoots: ["/workspace/a"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits only the unmarked authoritative snapshot when no roots resolved", () => {
|
||||
expect(
|
||||
shellStreamItemsFromInitialSnapshot({
|
||||
snapshot: emptyShellSnapshot,
|
||||
resolvedRepositoryIdentityRoots: [],
|
||||
}),
|
||||
).toEqual([{ kind: "snapshot", snapshot: emptyShellSnapshot }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composeShellStreamWithEnrichment", () => {
|
||||
it.effect(
|
||||
"emits every initial item before enrichment even when enrichment is already ready",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const initialSnapshot = {
|
||||
...emptyShellSnapshot,
|
||||
snapshotSequence: 5,
|
||||
} as OrchestrationV2ShellSnapshot;
|
||||
const enrichmentSnapshot = {
|
||||
...emptyShellSnapshot,
|
||||
snapshotSequence: 10,
|
||||
} as OrchestrationV2ShellSnapshot;
|
||||
|
||||
const initialItems = shellStreamItemsFromInitialSnapshot({
|
||||
snapshot: initialSnapshot,
|
||||
resolvedRepositoryIdentityRoots: ["/workspace/a"],
|
||||
});
|
||||
// Enrichment stream is fully ready before the composed stream is pulled.
|
||||
const enrichment = Stream.make(
|
||||
shellStreamItemFromEnrichmentRefresh({
|
||||
snapshot: enrichmentSnapshot,
|
||||
changes: [{ workspaceRoot: "/workspace/b" }],
|
||||
}),
|
||||
);
|
||||
const tail = Stream.make(
|
||||
{ kind: "synchronized" as const },
|
||||
{
|
||||
kind: "project.removed" as const,
|
||||
sequence: 6,
|
||||
projectId: "project-a",
|
||||
},
|
||||
);
|
||||
|
||||
const items = Array.from(
|
||||
yield* composeShellStreamWithEnrichment({
|
||||
initial: Stream.fromIterable(initialItems),
|
||||
tail,
|
||||
enrichment,
|
||||
}).pipe(Stream.runCollect),
|
||||
);
|
||||
|
||||
expect(items.slice(0, initialItems.length)).toEqual(initialItems);
|
||||
|
||||
const enrichmentIndex = items.findIndex(
|
||||
(item) =>
|
||||
item.kind === "snapshot" &&
|
||||
"resolvedRepositoryIdentityRoots" in item &&
|
||||
item.resolvedRepositoryIdentityRoots?.includes("/workspace/b"),
|
||||
);
|
||||
expect(enrichmentIndex).toBeGreaterThanOrEqual(initialItems.length);
|
||||
|
||||
for (let index = 0; index < initialItems.length; index++) {
|
||||
expect(items[index]).toEqual(initialItems[index]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("still interleaves enrichment with the post-prefix tail after initials drain", () =>
|
||||
Effect.gen(function* () {
|
||||
const items = Array.from(
|
||||
yield* composeShellStreamWithEnrichment({
|
||||
initial: Stream.make("initial-unmarked", "initial-marked"),
|
||||
tail: Stream.make("tail-a", "tail-b"),
|
||||
enrichment: Stream.make("enrichment"),
|
||||
}).pipe(Stream.runCollect),
|
||||
);
|
||||
|
||||
expect(items.slice(0, 2)).toEqual(["initial-unmarked", "initial-marked"]);
|
||||
expect(items).toContain("enrichment");
|
||||
expect(items).toContain("tail-a");
|
||||
expect(items).toContain("tail-b");
|
||||
expect(items.indexOf("enrichment")).toBeGreaterThanOrEqual(2);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,12 @@
|
||||
import type {
|
||||
ApplicationStoredEvent,
|
||||
OrchestrationV2ArchivedShellStreamItem,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestrationV2ShellStreamItem,
|
||||
OrchestrationV2StoredEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
/** Keep only the newest shell-relevant event per project/thread aggregate. */
|
||||
export function coalesceShellApplicationEvents(
|
||||
@@ -23,6 +25,58 @@ export function coalesceShellApplicationEvents(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit the initial shell prefix strictly first, then merge the post-prefix
|
||||
* tail with enrichment refreshes. Prevents a newer marked enrichment from
|
||||
* landing before the unmarked authoritative initial snapshot.
|
||||
*/
|
||||
export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
|
||||
readonly initial: Stream.Stream<A, E, R>;
|
||||
readonly tail: Stream.Stream<A2, E2, R2>;
|
||||
readonly enrichment: Stream.Stream<A3, E3, R3>;
|
||||
}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
|
||||
return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
|
||||
}
|
||||
|
||||
/** Build a shell snapshot stream item for a batched enrichment completion. */
|
||||
export function shellStreamItemFromEnrichmentRefresh(input: {
|
||||
readonly snapshot: OrchestrationV2ShellSnapshot;
|
||||
readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
|
||||
}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
|
||||
return {
|
||||
kind: "snapshot",
|
||||
snapshot: input.snapshot,
|
||||
resolvedRepositoryIdentityRoots: [
|
||||
...new Set(input.changes.map((change) => change.workspaceRoot)),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initial subscribe frames: always emit the unmarked authoritative snapshot,
|
||||
* then a same-sequence enrichment frame only when some roots already resolved.
|
||||
*/
|
||||
export function shellStreamItemsFromInitialSnapshot(input: {
|
||||
readonly snapshot: OrchestrationV2ShellSnapshot;
|
||||
readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
|
||||
}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
|
||||
const authoritative = {
|
||||
kind: "snapshot" as const,
|
||||
snapshot: input.snapshot,
|
||||
};
|
||||
if (input.resolvedRepositoryIdentityRoots.length === 0) {
|
||||
return [authoritative];
|
||||
}
|
||||
return [
|
||||
authoritative,
|
||||
{
|
||||
kind: "snapshot" as const,
|
||||
snapshot: input.snapshot,
|
||||
resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Converts a committed event and its resulting shell snapshot into one delta. */
|
||||
export function shellStreamItemFromSnapshot(input: {
|
||||
readonly stored: OrchestrationV2StoredEvent;
|
||||
|
||||
@@ -48,6 +48,10 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
Effect.forEach(
|
||||
projects,
|
||||
(project) =>
|
||||
// Use immediately available enrichment only. Awaiting git-backed
|
||||
// identity resolution can exceed the client shell-snapshot budget
|
||||
// (ProcessRunner allows probes up to one minute). Background workers
|
||||
// plus the WS enrichment subscription fill in repositoryIdentity.
|
||||
projectEnrichment.getAvailable(project.workspaceRoot).pipe(
|
||||
Effect.map((enrichment) => ({
|
||||
...project,
|
||||
|
||||
@@ -104,9 +104,19 @@ const SharedApplicationDataPlaneTestLayer = Layer.merge(
|
||||
).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectEnrichmentService, {
|
||||
peek: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }),
|
||||
peek: () =>
|
||||
Effect.succeed({
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
repositoryIdentityResolved: false,
|
||||
}),
|
||||
request: () => Effect.void,
|
||||
getAvailable: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }),
|
||||
getAvailable: () =>
|
||||
Effect.succeed({
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
repositoryIdentityResolved: false,
|
||||
}),
|
||||
invalidate: () => Effect.void,
|
||||
subscribeChanges: Effect.never,
|
||||
}),
|
||||
|
||||
@@ -168,6 +168,110 @@ it.effect("keeps repository workers available when every favicon worker is hung"
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("getAvailable returns immediately while repository identity is still unresolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryStarted = yield* Deferred.make<void>();
|
||||
const releaseRepository = yield* Deferred.make<void>();
|
||||
const metadataLayer = Layer.merge(
|
||||
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
|
||||
resolve: (workspaceRoot) =>
|
||||
Deferred.succeed(repositoryStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseRepository)),
|
||||
Effect.as(identity(workspaceRoot)),
|
||||
),
|
||||
}),
|
||||
Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
|
||||
resolvePath: (workspaceRoot) => Effect.succeed(`${workspaceRoot}/favicon.svg`),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* ProjectEnrichment.ProjectEnrichmentService;
|
||||
|
||||
// Non-blocking path must not wait on hung git/identity resolution.
|
||||
const immediate = yield* service.getAvailable("/pending-identity");
|
||||
assert.isNull(immediate.repositoryIdentity);
|
||||
assert.isNull(immediate.faviconPath);
|
||||
assert.isFalse(immediate.repositoryIdentityResolved);
|
||||
|
||||
yield* Deferred.await(repositoryStarted);
|
||||
|
||||
// Background lane still resolves after the snapshot path has returned.
|
||||
yield* Deferred.succeed(releaseRepository, undefined);
|
||||
const resolved = yield* waitForAvailable(
|
||||
service,
|
||||
"/pending-identity",
|
||||
(value) => value.repositoryIdentity !== null,
|
||||
);
|
||||
assert.equal(resolved.repositoryIdentity?.canonicalKey, "example.test/v1/pending-identity");
|
||||
assert.isTrue(resolved.repositoryIdentityResolved);
|
||||
}).pipe(Effect.provide(makeLayer(metadataLayer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"reports successful cached null as resolved while cold and failed lookups stay unresolved",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryStarted = yield* Deferred.make<void>();
|
||||
const releaseRepository = yield* Deferred.make<void>();
|
||||
const metadataLayer = Layer.merge(
|
||||
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
|
||||
resolve: (workspaceRoot) => {
|
||||
if (workspaceRoot === "/no-remote") {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
if (workspaceRoot === "/fails") {
|
||||
return Effect.die("repository resolver failed");
|
||||
}
|
||||
return Deferred.succeed(repositoryStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseRepository)),
|
||||
Effect.as(identity(workspaceRoot)),
|
||||
);
|
||||
},
|
||||
}),
|
||||
Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
|
||||
resolvePath: () => Effect.succeed(null),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* ProjectEnrichment.ProjectEnrichmentService;
|
||||
const changes = yield* service.subscribeChanges;
|
||||
|
||||
const cold = yield* service.peek("/never-requested");
|
||||
assert.isNull(cold.repositoryIdentity);
|
||||
assert.isFalse(cold.repositoryIdentityResolved);
|
||||
|
||||
const inFlight = yield* service.getAvailable("/in-flight");
|
||||
assert.isNull(inFlight.repositoryIdentity);
|
||||
assert.isFalse(inFlight.repositoryIdentityResolved);
|
||||
yield* Deferred.await(repositoryStarted);
|
||||
assert.isFalse((yield* service.peek("/in-flight")).repositoryIdentityResolved);
|
||||
|
||||
yield* service.request("/no-remote");
|
||||
const nullChange = yield* PubSub.take(changes);
|
||||
assert.equal(nullChange.workspaceRoot, "/no-remote");
|
||||
assert.isTrue(nullChange.repositoryIdentityResolved);
|
||||
assert.isNull(nullChange.enrichment.repositoryIdentity);
|
||||
assert.isTrue(nullChange.enrichment.repositoryIdentityResolved);
|
||||
|
||||
// Warm success null stays resolved and does not republish.
|
||||
const warmNull = yield* service.getAvailable("/no-remote");
|
||||
assert.isNull(warmNull.repositoryIdentity);
|
||||
assert.isTrue(warmNull.repositoryIdentityResolved);
|
||||
|
||||
yield* service.request("/fails");
|
||||
const failChange = yield* PubSub.take(changes);
|
||||
assert.equal(failChange.workspaceRoot, "/fails");
|
||||
assert.isFalse(failChange.repositoryIdentityResolved);
|
||||
const failed = yield* service.peek("/fails");
|
||||
assert.isNull(failed.repositoryIdentity);
|
||||
assert.isFalse(failed.repositoryIdentityResolved);
|
||||
}).pipe(Effect.provide(makeLayer(metadataLayer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates requests, bounds pending work, and reloads invalidated roots", () =>
|
||||
Effect.gen(function* () {
|
||||
const firstStarted = yield* Deferred.make<void>();
|
||||
|
||||
@@ -24,6 +24,8 @@ const DEFAULT_FAILURE_TTL = Duration.seconds(5);
|
||||
export interface ProjectEnrichment {
|
||||
readonly repositoryIdentity: RepositoryIdentity | null;
|
||||
readonly faviconPath: string | null;
|
||||
/** True when identity resolution completed successfully, including cached null. */
|
||||
readonly repositoryIdentityResolved: boolean;
|
||||
}
|
||||
|
||||
export interface ProjectEnrichmentChange {
|
||||
@@ -73,6 +75,13 @@ function availableValue<A, E>(cached: Option.Option<Exit.Exit<A, E>>): A | null
|
||||
});
|
||||
}
|
||||
|
||||
function isSuccessfullyResolved<A, E>(cached: Option.Option<Exit.Exit<A, E>>): boolean {
|
||||
return Option.match(cached, {
|
||||
onNone: () => false,
|
||||
onSome: (exit) => Exit.isSuccess(exit),
|
||||
});
|
||||
}
|
||||
|
||||
interface EnrichmentWorkLane {
|
||||
readonly pendingRoots: Ref.Ref<ReadonlySet<string>>;
|
||||
readonly queue: Queue.Queue<string>;
|
||||
@@ -159,12 +168,14 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
|
||||
const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
|
||||
yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
|
||||
const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
|
||||
const repositoryIdentityResolved = Exit.isSuccess(repositoryIdentity);
|
||||
yield* PubSub.publish(changes, {
|
||||
workspaceRoot,
|
||||
repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity),
|
||||
repositoryIdentityResolved,
|
||||
enrichment: {
|
||||
repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
|
||||
faviconPath: availableValue(faviconPath),
|
||||
repositoryIdentityResolved,
|
||||
},
|
||||
});
|
||||
},
|
||||
@@ -227,6 +238,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
|
||||
return {
|
||||
repositoryIdentity: availableValue(repositoryIdentity),
|
||||
faviconPath: availableValue(faviconPath),
|
||||
repositoryIdentityResolved: isSuccessfullyResolved(repositoryIdentity),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
+85
-23
@@ -77,7 +77,10 @@ import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
|
||||
import {
|
||||
archivedShellStreamItemFromSnapshot,
|
||||
coalesceShellApplicationEvents,
|
||||
composeShellStreamWithEnrichment,
|
||||
shellStreamItemFromEnrichmentRefresh,
|
||||
shellStreamItemFromSnapshot,
|
||||
shellStreamItemsFromInitialSnapshot,
|
||||
} from "./orchestration-v2/ShellStream.ts";
|
||||
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as OrchestrationEventStore from "./persistence/Services/OrchestrationEventStore.ts";
|
||||
@@ -449,13 +452,28 @@ const makeWsRpcLayer = (
|
||||
Effect.forEach(
|
||||
projects,
|
||||
(project) =>
|
||||
// Non-blocking: emit with cached identity (or null) and schedule
|
||||
// background resolution. subscribeChanges is attached before
|
||||
// loadSnapshot, so later identity completions push refreshed
|
||||
// shells for multi-env grouping without blocking the initial
|
||||
// snapshot or completion marker on slow git probes.
|
||||
projectEnrichment.getAvailable(project.workspaceRoot).pipe(
|
||||
Effect.map((enrichment) => ({
|
||||
...project,
|
||||
repositoryIdentity: enrichment.repositoryIdentity,
|
||||
project: {
|
||||
...project,
|
||||
repositoryIdentity: enrichment.repositoryIdentity,
|
||||
},
|
||||
repositoryIdentityResolved: enrichment.repositoryIdentityResolved,
|
||||
})),
|
||||
),
|
||||
{ concurrency: 16 },
|
||||
).pipe(
|
||||
Effect.map((enriched) => ({
|
||||
projects: enriched.map((entry) => entry.project),
|
||||
resolvedRepositoryIdentityRoots: enriched
|
||||
.filter((entry) => entry.repositoryIdentityResolved)
|
||||
.map((entry) => entry.project.workspaceRoot),
|
||||
})),
|
||||
),
|
||||
);
|
||||
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
|
||||
@@ -740,8 +758,11 @@ const makeWsRpcLayer = (
|
||||
} as const;
|
||||
}),
|
||||
);
|
||||
const projects = yield* enrichProjectShells(base.projects);
|
||||
return { ...base, projects };
|
||||
const enriched = yield* enrichProjectShells(base.projects);
|
||||
return {
|
||||
snapshot: { ...base, projects: enriched.projects } as OrchestrationV2ShellSnapshot,
|
||||
resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots,
|
||||
};
|
||||
});
|
||||
const projectItem = Effect.fn("ws.orchestrationV2.projectShellItem")(function* (
|
||||
stored: Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
|
||||
@@ -805,37 +826,74 @@ const makeWsRpcLayer = (
|
||||
|
||||
const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe(
|
||||
Stream.filter((change) => change.repositoryIdentityResolved),
|
||||
Stream.debounce("25 millis"),
|
||||
Stream.mapEffect(() => loadSnapshot()),
|
||||
Stream.map((snapshot) => ({ kind: "snapshot" as const, snapshot })),
|
||||
Stream.groupedWithin(64, Duration.millis(25)),
|
||||
Stream.mapEffect((changes) =>
|
||||
loadSnapshot().pipe(
|
||||
Effect.map(({ snapshot }) =>
|
||||
shellStreamItemFromEnrichmentRefresh({
|
||||
snapshot,
|
||||
changes: Array.from(changes),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Always attach the enrichment subscription before the first load so
|
||||
// completions that race HTTP snapshot fetch still push a refresh.
|
||||
// When the client already holds a shell snapshot (cached, or loaded
|
||||
// over HTTP) it passes that snapshot's sequence, and we resume by
|
||||
// replaying application events after it instead of re-sending the
|
||||
// whole projects/threads list over the socket. The event store
|
||||
// subscribes to live events before reading the persisted tail, so no
|
||||
// event published during the replay window is lost; overlapping events
|
||||
// are deduped by sequence on the client.
|
||||
// over HTTP) it passes that snapshot's sequence. We still emit one
|
||||
// enriched snapshot up front: getAvailable may have been cold on the
|
||||
// HTTP path (null identity), and enrichment PubSub events published
|
||||
// before this subscribe attached are dropped. Rehydrating here fills
|
||||
// repositoryIdentity for cross-environment project grouping even on
|
||||
// afterSequence resumes. Application events after the sequence still
|
||||
// stream as deltas; overlapping events are deduped by sequence on the
|
||||
// client.
|
||||
//
|
||||
// After the unmarked authoritative frame, emit a same-sequence
|
||||
// metadata-only frame for roots that already resolved successfully
|
||||
// (including cached null). Cold/failed roots stay unmarked and use
|
||||
// the PubSub enrichment path when they complete later.
|
||||
const completionMarker =
|
||||
input.requestCompletionMarker === true
|
||||
? Stream.make({ kind: "synchronized" as const })
|
||||
: Stream.empty;
|
||||
const snapshotThenLive = (snapshot: OrchestrationV2ShellSnapshot) =>
|
||||
Stream.concat(
|
||||
Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), completionMarker),
|
||||
liveFrom(snapshot.snapshotSequence),
|
||||
const initialSnapshotItems = (loaded: {
|
||||
readonly snapshot: OrchestrationV2ShellSnapshot;
|
||||
readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
|
||||
}) =>
|
||||
Stream.fromIterable(
|
||||
shellStreamItemsFromInitialSnapshot({
|
||||
snapshot: loaded.snapshot,
|
||||
resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots,
|
||||
}),
|
||||
);
|
||||
// Initial unmarked (+ optional same-load marked) always drains first.
|
||||
// Enrichment merges only with the post-prefix tail so a ready marked
|
||||
// refresh cannot interleave before the authoritative initial frame.
|
||||
const completionThenLive = (afterSequence: number) =>
|
||||
Stream.concat(completionMarker, liveFrom(afterSequence));
|
||||
|
||||
const base = yield* Effect.gen(function* () {
|
||||
const stream = yield* Effect.gen(function* () {
|
||||
const loaded = yield* loadSnapshot();
|
||||
const initial = initialSnapshotItems(loaded);
|
||||
if (input.afterSequence === undefined) {
|
||||
return snapshotThenLive(yield* loadSnapshot());
|
||||
return composeShellStreamWithEnrichment({
|
||||
initial,
|
||||
tail: completionThenLive(loaded.snapshot.snapshotSequence),
|
||||
enrichment: enrichmentRefreshes,
|
||||
});
|
||||
}
|
||||
|
||||
const highWater = yield* applicationEvents.latestApplicationSequence;
|
||||
const replayGap = highWater - input.afterSequence;
|
||||
if (replayGap < 0 || replayGap > 1_000) {
|
||||
return snapshotThenLive(yield* loadSnapshot());
|
||||
return composeShellStreamWithEnrichment({
|
||||
initial,
|
||||
tail: completionThenLive(loaded.snapshot.snapshotSequence),
|
||||
enrichment: enrichmentRefreshes,
|
||||
});
|
||||
}
|
||||
|
||||
const replay = toShellStream(
|
||||
@@ -844,7 +902,11 @@ const makeWsRpcLayer = (
|
||||
throughSequence: highWater,
|
||||
}),
|
||||
);
|
||||
return Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater));
|
||||
return composeShellStreamWithEnrichment({
|
||||
initial,
|
||||
tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)),
|
||||
enrichment: enrichmentRefreshes,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -855,7 +917,7 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
);
|
||||
|
||||
return Stream.merge(base, enrichmentRefreshes).pipe(
|
||||
return stream.pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
@@ -883,7 +945,7 @@ const makeWsRpcLayer = (
|
||||
.pipe(
|
||||
Effect.flatMap((snapshot) =>
|
||||
enrichProjectShells(snapshot.projects).pipe(
|
||||
Effect.map((projects) => ({ ...snapshot, projects })),
|
||||
Effect.map(({ projects }) => ({ ...snapshot, projects })),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -24,16 +24,42 @@ import {
|
||||
OrchestrationV2CheckpointScope,
|
||||
OrchestrationV2Command,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2Subagent,
|
||||
OrchestrationV2ThreadProjection,
|
||||
OrchestrationV2TurnItem,
|
||||
} from "./orchestrationV2.ts";
|
||||
|
||||
const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
|
||||
const LegacyShellStreamItem = Schema.Union([
|
||||
Schema.Struct({ kind: Schema.Literal("synchronized") }),
|
||||
Schema.Struct({
|
||||
kind: Schema.Literal("snapshot"),
|
||||
snapshot: OrchestrationV2ShellSnapshot,
|
||||
}),
|
||||
]);
|
||||
const decodeLegacyShellStreamItem = Schema.decodeUnknownSync(LegacyShellStreamItem);
|
||||
const decodeOrchestrationV2Command = Schema.decodeUnknownSync(OrchestrationV2Command);
|
||||
const decodeOrchestrationV2TurnItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem);
|
||||
|
||||
describe("orchestration V2 contracts", () => {
|
||||
it("lets legacy snapshot decoders ignore enrichment metadata", () => {
|
||||
const decoded = decodeLegacyShellStreamItem({
|
||||
kind: "snapshot",
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
archivedThreads: [],
|
||||
},
|
||||
resolvedRepositoryIdentityRoots: ["/workspace/project"],
|
||||
});
|
||||
|
||||
expect(decoded.kind).toBe("snapshot");
|
||||
expect("resolvedRepositoryIdentityRoots" in decoded).toBe(false);
|
||||
});
|
||||
|
||||
it("decodes nested checkpoint scopes without making child scopes advance app run count", () => {
|
||||
const rootScope = Schema.decodeUnknownSync(OrchestrationV2CheckpointScope)({
|
||||
id: "scope-root-1",
|
||||
|
||||
@@ -1198,6 +1198,12 @@ export const OrchestrationV2ShellStreamItem = Schema.Union([
|
||||
Schema.Struct({
|
||||
kind: Schema.Literal("snapshot"),
|
||||
snapshot: OrchestrationV2ShellSnapshot,
|
||||
/**
|
||||
* Workspace roots whose repository-identity resolution completed for this
|
||||
* enrichment refresh. Omitted on authoritative HTTP/initial WebSocket
|
||||
* snapshots. Older clients ignore the field.
|
||||
*/
|
||||
resolvedRepositoryIdentityRoots: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
}),
|
||||
Schema.Struct({
|
||||
kind: Schema.Literal("project.updated"),
|
||||
@@ -1544,6 +1550,77 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
|
||||
]);
|
||||
export type OrchestrationV2TurnItemJson = typeof OrchestrationV2TurnItemJson.Type;
|
||||
|
||||
export const OrchestrationV2ProjectedTurnItemJson = OrchestrationV2ProjectedTurnItem.mapFields(
|
||||
(fields) => ({
|
||||
...fields,
|
||||
item: OrchestrationV2TurnItemJson,
|
||||
}),
|
||||
);
|
||||
export type OrchestrationV2ProjectedTurnItemJson = typeof OrchestrationV2ProjectedTurnItemJson.Type;
|
||||
|
||||
export const OrchestrationV2ThreadProjectionJson = OrchestrationV2ThreadProjection.mapFields(
|
||||
(fields) => ({
|
||||
...fields,
|
||||
thread: OrchestrationV2AppThreadJson,
|
||||
runs: Schema.Array(OrchestrationV2RunJson),
|
||||
attempts: Schema.Array(OrchestrationV2RunAttemptJson),
|
||||
nodes: Schema.Array(OrchestrationV2ExecutionNodeJson),
|
||||
subagents: Schema.Array(OrchestrationV2SubagentJson),
|
||||
providerSessions: Schema.Array(OrchestrationV2ProviderSessionJson),
|
||||
providerThreads: Schema.Array(OrchestrationV2ProviderThreadJson),
|
||||
providerTurns: Schema.Array(OrchestrationV2ProviderTurnJson),
|
||||
runtimeRequests: Schema.Array(OrchestrationV2RuntimeRequestJson),
|
||||
messages: Schema.Array(OrchestrationV2ConversationMessageJson),
|
||||
plans: Schema.Array(OrchestrationV2PlanArtifact),
|
||||
turnItems: Schema.Array(OrchestrationV2TurnItemJson),
|
||||
checkpointScopes: Schema.Array(OrchestrationV2CheckpointScopeJson),
|
||||
checkpoints: Schema.Array(OrchestrationV2CheckpointJson),
|
||||
contextHandoffs: Schema.Array(OrchestrationV2ContextHandoffJson),
|
||||
contextTransfers: Schema.Array(OrchestrationV2ContextTransferJson),
|
||||
visibleTurnItems: Schema.Array(OrchestrationV2ProjectedTurnItemJson),
|
||||
updatedAt: Schema.DateTimeUtcFromString,
|
||||
}),
|
||||
);
|
||||
export type OrchestrationV2ThreadProjectionJson = typeof OrchestrationV2ThreadProjectionJson.Type;
|
||||
|
||||
export const OrchestrationV2PendingRuntimeRequestSummaryJson =
|
||||
OrchestrationV2PendingRuntimeRequestSummary.mapFields((fields) => ({
|
||||
...fields,
|
||||
createdAt: Schema.DateTimeUtcFromString,
|
||||
}));
|
||||
export type OrchestrationV2PendingRuntimeRequestSummaryJson =
|
||||
typeof OrchestrationV2PendingRuntimeRequestSummaryJson.Type;
|
||||
|
||||
export const OrchestrationV2LatestVisibleMessageSummaryJson =
|
||||
OrchestrationV2LatestVisibleMessageSummary.mapFields((fields) => ({
|
||||
...fields,
|
||||
updatedAt: Schema.DateTimeUtcFromString,
|
||||
}));
|
||||
export type OrchestrationV2LatestVisibleMessageSummaryJson =
|
||||
typeof OrchestrationV2LatestVisibleMessageSummaryJson.Type;
|
||||
|
||||
export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFields((fields) => ({
|
||||
...fields,
|
||||
pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummaryJson),
|
||||
latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummaryJson),
|
||||
latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
createdAt: Schema.DateTimeUtcFromString,
|
||||
updatedAt: Schema.DateTimeUtcFromString,
|
||||
archivedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
settledAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
deletedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
}));
|
||||
export type OrchestrationV2ThreadShellJson = typeof OrchestrationV2ThreadShellJson.Type;
|
||||
|
||||
export const OrchestrationV2ShellSnapshotJson = OrchestrationV2ShellSnapshot.mapFields(
|
||||
(fields) => ({
|
||||
...fields,
|
||||
threads: Schema.Array(OrchestrationV2ThreadShellJson),
|
||||
archivedThreads: Schema.Array(OrchestrationV2ThreadShellJson),
|
||||
}),
|
||||
);
|
||||
export type OrchestrationV2ShellSnapshotJson = typeof OrchestrationV2ShellSnapshotJson.Type;
|
||||
|
||||
const OrchestrationV2JsonEventBaseFields = {
|
||||
...OrchestrationV2EventBase.fields,
|
||||
occurredAt: Schema.DateTimeUtcFromString,
|
||||
|
||||
@@ -632,6 +632,61 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input } = yield* makeInMemoryStdio();
|
||||
const notifications =
|
||||
yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
|
||||
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
||||
stdio,
|
||||
serverRequestMethods: new Set(),
|
||||
});
|
||||
|
||||
yield* transport.incoming.pipe(
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encoder.encode(
|
||||
`${encodeUnknownJsonString({
|
||||
jsonrpc: "2.0",
|
||||
id: "skills-reload",
|
||||
result: {
|
||||
reloaded: true,
|
||||
},
|
||||
})}\n`,
|
||||
),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
yield* encodeJsonl(SessionUpdateNotification, {
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Reload skills",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const [update] = yield* Deferred.await(notifications);
|
||||
assert.equal(update?._tag, "SessionUpdate");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("cleans up interrupted extension requests before a late response arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input, output } = yield* makeInMemoryStdio();
|
||||
|
||||
@@ -106,6 +106,9 @@ const decodeElicitationComplete = Schema.decodeUnknownEffect(
|
||||
);
|
||||
const parserFactory = RpcSerialization.ndJsonRpc();
|
||||
|
||||
const isEffectRpcRequestId = (requestId: string): boolean =>
|
||||
requestId !== "" && /^-?\d+$/.test(requestId);
|
||||
|
||||
export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
|
||||
options: AcpPatchedProtocolOptions,
|
||||
): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
|
||||
@@ -432,12 +435,19 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
return observeIncoming.pipe(Effect.andThen(Queue.offer(serverQueue, message)), Effect.asVoid);
|
||||
};
|
||||
|
||||
const forwardToRpcClient = (
|
||||
message: RpcMessage.ResponseChunkEncoded | RpcMessage.ResponseExitEncoded,
|
||||
) =>
|
||||
isEffectRpcRequestId(message.requestId)
|
||||
? Queue.offer(clientQueue, message).pipe(Effect.asVoid)
|
||||
: Effect.void;
|
||||
|
||||
const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
|
||||
Ref.get(extPending).pipe(
|
||||
Effect.flatMap((pending) => {
|
||||
const pendingRequest = pending.get(message.requestId);
|
||||
if (!pendingRequest) {
|
||||
return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
|
||||
return forwardToRpcClient(message);
|
||||
}
|
||||
if (message.exit._tag === "Success") {
|
||||
return completeExtPendingSuccess(message.requestId, message.exit.value);
|
||||
@@ -484,7 +494,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
|
||||
message.requestId,
|
||||
),
|
||||
)
|
||||
: Queue.offer(clientQueue, message).pipe(Effect.asVoid);
|
||||
: forwardToRpcClient(message);
|
||||
}),
|
||||
);
|
||||
case "Defect":
|
||||
|
||||
Reference in new issue
Block a user