import { createCommandPermissions } from "./commandPermissions.ts";
import { RpcPermissionGuard } from "../rpc/client.ts";
import { vi } from "vite-plus/test";
import {
EnvironmentId,
AuthSourceControlWriteScope,
AuthOrchestrationOperateScope,
ProjectId,
PullRequestOperationError,
WS_METHODS,
type AuthSessionState,
type PullRequestListInput,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Schema from "effect/Schema";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Effect from "effect/Effect";
import * as Latch from "effect/Latch";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import {
AVAILABLE_CONNECTION_STATE,
ConnectionTransientError,
PrimaryConnectionTarget,
SshConnectionTarget,
type PreparedConnection,
type SupervisorConnectionState,
} from "../connection/model.ts";
import * as EnvironmentRegistry from "../connection/registry.ts";
import { SshConnectionProfile, type ConnectionCatalogEntry } from "../connection/catalog.ts";
import * as ConnectionProfileStore from "../connection/profileStore.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import type { RpcSession } from "../rpc/session.ts";
import {
createLinkedPullRequestSummaryAtomFamily,
createPullRequestEnvironmentAtoms,
} from "./pullRequests.ts";
import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
import { executeAtomQuery, queryPersistenceKey } from "./runtime.ts";
import { EnvironmentQueryStore } from "./queryPersistence.ts";
import { createPullRequestRouter } from "./pullRequestRouting.ts";
import { PullRequestRoutingPermissions } from "../connection/pullRequestRoutingPermissions.ts";
const trustedRouting = {
get: () => Effect.succeed("read-write" as const),
changes: Stream.empty,
set: () => Effect.void,
forget: () => Effect.void,
};
class MutationRefused extends Schema.TaggedError<MutationRefused>()("MutationRefused", {}) {}
for (const scenario of [
"prefers the local environment with the same github account",
"falls back before mutation when the local account differs",
"never retries an ambiguous mutation failure",
"returns a fast local source read without checking alternate identities",
"keeps single-environment requests free of identity lookups",
"keeps a local origin ahead of another local environment",
"keeps mutations on an old origin server without retrying them",
"skips an old alternate server before dispatching a mutation",
"returns a successful mutation when source invalidation stalls",
"does not dispatch after routing permission is revoked during the probe",
"keeps mutations on the origin when the alternate is disabled",
"does not dispatch after the alternate is disabled during the probe",
"preserves a local source account rejection when alternate accounts differ",
] as const) {
(scenario === "returns a successful mutation when source invalidation stalls"
? it.live
: it.effect)(scenario, () =>
Effect.scoped(
Effect.gen(function* () {
const calls: string[] = [];
const inputs: unknown[] = [];
let trusted = true;
let disableAlternate = Effect.void;
const switchedAccount =
scenario === "preserves a local source account rejection when alternate accounts differ";
const mismatch =
scenario === "falls back before mutation when the local account differs" ||
switchedAccount;
const ambiguous = scenario === "never retries an ambiguous mutation failure";
const reading =
scenario === "returns a fast local source read without checking alternate identities";
const single = scenario === "keeps single-environment requests free of identity lookups";
const localOrigin =
scenario === "keeps a local origin ahead of another local environment" ||
switchedAccount ||
reading;
const oldOrigin =
scenario === "keeps mutations on an old origin server without retrying them";
const oldAlternate =
scenario === "skips an old alternate server before dispatching a mutation";
const failure = new PullRequestOperationError({
operation: switchedAccount ? "routeIdentity" : "runAction",
detail: "connection lost after dispatch",
});
const clientFor = (local: boolean) => {
const name = local ? "local" : "origin";
return {
[local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: (
input: unknown,
) =>
Effect.gen(function* () {
if (local) expect(input).toEqual({ host: "github.com" });
calls.push(`${name}:identity`);
if (
local &&
scenario === "does not dispatch after the alternate is disabled during the probe"
)
yield* disableAlternate;
if (
local &&
scenario ===
"does not dispatch after routing permission is revoked during the probe"
)
trusted = false;
if ((!local && oldOrigin) || (local && oldAlternate)) {
return yield* Effect.die(
`Unknown request tag: ${WS_METHODS.pullRequestsRouting}`,
);
}
return {
host: "github.com",
provider: "github",
viewer: "maria-rcks",
accountId: local && mismatch ? "456" : "123",
};
}),
[WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
Effect.gen(function* () {
calls.push(`${name}:mutation`);
inputs.push(input);
if (
!local &&
switchedAccount &&
(input as { expectedAccountId?: string }).expectedAccountId === "123"
)
return yield* failure;
if (local && ambiguous) return yield* failure;
}),
[WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
Effect.gen(function* () {
calls.push(`${name}:read`);
expect(input.allowStale).toBe(false);
if (local) return yield* failure;
return null;
}),
[WS_METHODS.pullRequestsInvalidate]: () =>
Effect.gen(function* () {
calls.push(`${name}:invalidate`);
if (
!local &&
scenario === "returns a successful mutation when source invalidation stalls"
) {
return yield* Effect.never;
}
}),
} as unknown as WsRpcProtocolClient;
};
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
clientFor(false),
single ? undefined : clientFor(true),
localOrigin,
);
disableAlternate = SubscriptionRef.update(
environmentRegistry.entries,
(entries) =>
new Map(
[...entries].map(([id, entry]) => [
id,
id === TARGET.environmentId ? entry : { ...entry, enabled: false },
]),
),
);
const disabled =
scenario === "keeps mutations on the origin when the alternate is disabled";
const disabledDuringProbe =
scenario === "does not dispatch after the alternate is disabled during the probe";
if (disabled) yield* disableAlternate;
const input = {
projectId: ProjectId.make("project-1"),
host: "github.com",
repository: "acme/web",
number: 7,
action: "merge" as const,
};
const route = createPullRequestRouter();
const result = yield* (
reading
? route(WS_METHODS.pullRequestsSummary, input)
: route(WS_METHODS.pullRequestsRunAction, input)
).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(PullRequestRoutingPermissions, {
...trustedRouting,
get: () => Effect.succeed(trusted ? "read-write" : "off"),
}),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.result,
);
if (switchedAccount) {
expect(result).toMatchObject({ _tag: "Failure", failure });
expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
} else if (ambiguous) {
expect(result).toMatchObject({ _tag: "Failure", failure });
expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
} else {
expect(result._tag).toBe("Success");
if (single || disabled) {
expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual([
"origin:mutation",
]);
} else if (reading) expect(calls).toEqual(["origin:read"]);
else if (
mismatch ||
localOrigin ||
oldOrigin ||
oldAlternate ||
!trusted ||
disabledDuringProbe
)
expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
else {
expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
expect(calls).toContain("origin:invalidate");
expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
}
}
}),
),
);
}
it.effect.each([
{ probe: "origin", cancelled: "first" },
{ probe: "origin", cancelled: "waiter" },
{ probe: "alternate", cancelled: "first" },
{ probe: "alternate", cancelled: "waiter" },
] as const)(
"preserves a shared $probe probe's other reader when the $cancelled cancels",
({ probe, cancelled }) =>
Effect.scoped(
Effect.gen(function* () {
const started = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
let probes = 0;
const clientFor = (local: boolean) =>
({
[local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
Effect.gen(function* () {
if (local === (probe === "alternate")) {
probes++;
yield* Deferred.succeed(started, undefined);
yield* Deferred.await(release);
}
return {
host: "github.com",
provider: "github",
viewer: "maria",
accountId: "123",
};
}),
[WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null),
}) as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
clientFor(false),
clientFor(true),
);
const read = () =>
createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 7,
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
);
const first = yield* read().pipe(Effect.forkChild);
yield* Deferred.await(started);
const waiter = yield* read().pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* Fiber.interrupt(cancelled === "first" ? first : waiter);
yield* Deferred.succeed(release, undefined);
expect(yield* Fiber.join(cancelled === "first" ? waiter : first)).toBeNull();
expect(probes).toBe(cancelled === "first" ? 2 : 1);
yield* read();
expect(probes).toBe(cancelled === "first" ? 3 : 2);
}),
),
);
it.effect.each(["revoked", "disabled"] as const)(
"rechecks routing after an alternate with a shared probe is %s",
(change) =>
Effect.scoped(
Effect.gen(function* () {
const started = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const reads: string[] = [];
let trusted = true;
let probes = 0;
const clientFor = (local: boolean) =>
({
[local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
Effect.gen(function* () {
if (local) {
probes++;
yield* Deferred.succeed(started, undefined);
yield* Deferred.await(release);
}
return {
host: "github.com",
provider: "github",
viewer: "maria",
accountId: "123",
};
}),
[WS_METHODS.pullRequestsSummary]: () =>
Effect.sync(() => {
reads.push(local ? "local" : "origin");
return null;
}),
}) as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
clientFor(false),
clientFor(true),
);
const readers = yield* Effect.all(
Array.from({ length: 2 }, () =>
createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 7,
}),
),
{ concurrency: "unbounded" },
).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(PullRequestRoutingPermissions, {
...trustedRouting,
get: () => Effect.sync(() => (trusted ? "read-write" : "off")),
}),
Effect.forkChild,
);
yield* Deferred.await(started);
yield* Effect.yieldNow;
if (change === "revoked") trusted = false;
else
yield* SubscriptionRef.update(
environmentRegistry.entries,
(entries) =>
new Map(
[...entries].map(([id, entry]) => [
id,
id === TARGET.environmentId ? entry : { ...entry, enabled: false },
]),
),
);
yield* Deferred.succeed(release, undefined);
expect(yield* Fiber.join(readers)).toEqual([null, null]);
expect(probes).toBe(1);
expect(reads).toEqual(["origin", "origin"]);
}),
),
);
it.effect.each(["origin", "alternate"] as const)(
"keeps pending metadata from an old %s connection separate from its replacement",
(reconnected) =>
Effect.scoped(
Effect.gen(function* () {
const started = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const probes: string[] = [];
const clientFor = (local: boolean, replacement = false) =>
({
[local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
Effect.gen(function* () {
if (local === (reconnected === "alternate")) {
probes.push(replacement ? "new" : "old");
if (!replacement) {
yield* Deferred.succeed(started, undefined);
yield* Deferred.await(release);
}
}
return {
host: "github.com",
provider: "github",
viewer: "maria",
accountId: "123",
};
}),
[WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null),
}) as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime(
clientFor(false),
clientFor(true),
);
const read = () =>
createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 7,
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
);
const first = yield* read().pipe(Effect.forkChild);
yield* Deferred.await(started);
yield* SubscriptionRef.set(
(reconnected === "origin" ? supervisor : localSupervisor).session,
Option.some(session(clientFor(reconnected === "alternate", true))),
);
expect(yield* read()).toBeNull();
expect(probes).toEqual(["old", "new"]);
yield* Deferred.succeed(release, undefined);
expect(yield* Fiber.join(first)).toBeNull();
}),
),
);
it.effect("forgets routed viewed marks when a viewed-files batch fails", () =>
Effect.scoped(
Effect.gen(function* () {
const reference = {
projectId: ProjectId.make("project-1"),
host: "github.com",
repository: "acme/web",
number: 7,
};
const invalidations: { environment: string; input: unknown }[] = [];
const identity = () =>
Effect.succeed({
host: reference.host,
provider: "github",
accountId: "123",
viewer: "maria-rcks",
});
const clientFor = (environment: string) =>
({
[WS_METHODS.pullRequestsRouting]: identity,
[WS_METHODS.pullRequestsRoutingIdentity]: identity,
[WS_METHODS.pullRequestsFilesViewed]: () =>
Effect.succeed({ files: [{ path: "a.ts", state: "unviewed" }], truncated: false }),
// The host may have applied part of the batch before refusing the rest.
[WS_METHODS.pullRequestsSetFilesViewed]: () => Effect.fail("second path refused"),
[WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
Effect.sync(() => {
invalidations.push({ environment, input });
}),
}) as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
clientFor("origin"),
clientFor("local"),
);
const route = createPullRequestRouter();
const write = yield* Effect.gen(function* () {
yield* route(WS_METHODS.pullRequestsFilesViewed, reference);
return yield* Effect.exit(
route(WS_METHODS.pullRequestsSetFilesViewed, {
...reference,
files: [
{ path: "a.ts", viewed: true },
{ path: "b.ts", viewed: true },
],
}),
);
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
expect(write._tag).toBe("Failure");
expect(invalidations).toContainEqual({
environment: "local",
input: { reference: expect.objectContaining(reference), filesViewedOnly: true },
});
for (const call of invalidations) {
expect(call.input).toMatchObject({ filesViewedOnly: true });
}
}),
),
);
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
label: "Test environment",
httpBaseUrl: "https://environment.example.test",
wsBaseUrl: "wss://environment.example.test",
});
function session(client: WsRpcProtocolClient): RpcSession {
return {
client: {
...client,
[WS_METHODS.pullRequestsInvalidate]:
client[WS_METHODS.pullRequestsInvalidate] ?? (() => Effect.void),
},
initialConfig: client[WS_METHODS.serverGetConfig]?.({}).pipe(Effect.orDie) ?? Effect.never,
subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
inboundFrames: Effect.succeed(0),
closed: Effect.never,
};
}
const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
client: WsRpcProtocolClient,
localClient?: WsRpcProtocolClient,
localOrigin = false,
onAnswer: Parameters<typeof createPullRequestEnvironmentAtoms>[1] = {},
queryStore: typeof EnvironmentQueryStore.Service = null,
) {
const originTarget = localOrigin
? new PrimaryConnectionTarget({
...TARGET,
httpBaseUrl: "http://localhost:3774",
wsBaseUrl: "ws://localhost:3774",
})
: TARGET;
const connectionState: SupervisorConnectionState = {
...AVAILABLE_CONNECTION_STATE,
desired: true,
network: "online",
phase: "connected",
attempt: 1,
generation: 1,
};
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: originTarget,
state: yield* SubscriptionRef.make(connectionState),
session: yield* SubscriptionRef.make(Option.some(session(client))),
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const localTarget = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("local-environment"),
label: "Local environment",
httpBaseUrl: "http://localhost:3773",
wsBaseUrl: "ws://localhost:3773",
});
const localSupervisor = {
...supervisor,
target: localTarget,
session: yield* SubscriptionRef.make(Option.some(session(localClient ?? client))),
};
const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
new Map([
[
originTarget.environmentId,
{ target: originTarget, profile: Option.none(), enabled: true },
],
...(localClient === undefined
? []
: [
[
localTarget.environmentId,
{ target: localTarget, profile: Option.none(), enabled: true },
] as const,
]),
]),
),
run: (environmentId, effect) =>
Effect.provideService(
effect,
EnvironmentSupervisor.EnvironmentSupervisor,
environmentId === localTarget.environmentId ? localSupervisor : supervisor,
),
runStream: (_environmentId, stream) =>
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
followStream: (_environmentId, stream) =>
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
} as EnvironmentRegistry.EnvironmentRegistry["Service"]);
const runtime = Atom.runtime(
Layer.mergeAll(
Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Layer.succeed(
PullRequestDiffLoader.PullRequestDiffLoader,
PullRequestDiffLoader.PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
),
Layer.succeed(EnvironmentQueryStore, queryStore),
),
);
const atoms = createPullRequestEnvironmentAtoms(runtime, onAnswer);
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
Effect.sync(() => registry.dispose()),
);
return { runtime, atoms, registry, environmentRegistry, supervisor, localSupervisor };
});
it.effect.each([
"default",
"origin-off",
"destination-off",
"read-only",
"destination-disabled",
"destination-unsupported",
] as const)(
"preserves source requests when routing to another environment is blocked by %s",
(permission) =>
Effect.scoped(
Effect.gen(function* () {
const calls: string[] = [];
const failure = new PullRequestOperationError({
operation: "summary",
detail: "source failed",
});
const client = {
[WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
Effect.suspend(() => {
calls.push("source-read");
expect(input.allowStale).toBeUndefined();
return Effect.fail(failure);
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.sync(() => {
calls.push("source-write");
}),
} as unknown as WsRpcProtocolClient;
const alternate = {
[WS_METHODS.pullRequestsRoutingIdentity]: () =>
Effect.die("untrusted environment was contacted"),
} as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime(
client,
alternate,
);
if (permission === "destination-disabled" || permission === "destination-unsupported") {
yield* SubscriptionRef.update(
environmentRegistry.entries,
(entries) =>
new Map(
[...entries].map(([id, entry]) => [
id,
id === TARGET.environmentId
? entry
: {
...entry,
enabled: permission !== "destination-disabled",
...(permission === "destination-unsupported"
? { unsupportedReason: "Protocol version mismatch" }
: {}),
},
]),
),
);
yield* SubscriptionRef.set(localSupervisor.session, Option.none());
}
const ref = {
projectId: ProjectId.make("project-1"),
repository: "private/repo",
number: 7,
};
const request = Effect.gen(function* () {
const route = createPullRequestRouter();
if (permission !== "read-only")
yield* route(WS_METHODS.pullRequestsSummary, ref).pipe(Effect.flip);
yield* route(WS_METHODS.pullRequestsRunAction, { ...ref, action: "merge" });
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
);
yield* permission === "default"
? request
: request.pipe(
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(PullRequestRoutingPermissions, {
...trustedRouting,
get: (entry) =>
Effect.succeed(
permission === "read-only"
? "read"
: permission === "destination-disabled" ||
permission === "destination-unsupported"
? "read-write"
: (entry.target.environmentId === TARGET.environmentId) ===
(permission === "origin-off")
? "off"
: "read-write",
),
}),
);
expect(calls).toEqual(
permission === "read-only" ? ["source-write"] : ["source-read", "source-write"],
);
}),
),
);
it.effect.each(
(["origin", "destination"] as const).flatMap((side) =>
(["matching", "changed", "missing", "unavailable", "failed"] as const).map((stored) => ({
side,
stored,
})),
),
)("checks the current $side SSH profile before routing with $stored storage", ({ side, stored }) =>
Effect.scoped(
Effect.gen(function* () {
const calls: string[] = [];
const identity = {
host: "github.com",
provider: "github",
viewer: "maria",
accountId: "123",
};
const client = {
[WS_METHODS.pullRequestsRouting]: () =>
Effect.sync(() => {
calls.push("source-probe");
return identity;
}),
[WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
Effect.gen(function* () {
if (input.expectedAccountId !== undefined) {
return yield* new PullRequestOperationError({
operation: "routeIdentity",
detail: "Source guard refused.",
});
}
calls.push("source-write");
}),
[WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
} as unknown as WsRpcProtocolClient;
const alternate = {
[WS_METHODS.pullRequestsRoutingIdentity]: () =>
Effect.sync(() => {
calls.push("alternate-probe");
return identity;
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.sync(() => {
calls.push("alternate-write");
}),
[WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
} as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
const environmentId =
side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
const profile = new SshConnectionProfile({
connectionId: "ssh-1",
environmentId,
label: "SSH",
target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
});
yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
new Map(entries).set(environmentId, {
target: new SshConnectionTarget({
environmentId,
connectionId: profile.connectionId,
label: "SSH",
}),
profile: Option.some(profile),
enabled: true,
}),
);
const read = Effect.suspend(() =>
stored === "failed"
? Effect.fail(
new ConnectionTransientError({
reason: "remote-unavailable",
detail: "Profile storage unavailable.",
}),
)
: Effect.succeed(
stored === "missing"
? Option.none()
: Option.some(
stored === "changed"
? new SshConnectionProfile({
...profile,
target: { ...profile.target, hostname: "replacement.example.test" },
})
: profile,
),
),
);
const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
projectId: ProjectId.make("project-1"),
repository: "private/repo",
number: 7,
action: "merge",
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
);
yield* stored === "unavailable"
? route
: route.pipe(
Effect.provideService(ConnectionProfileStore.ConnectionProfileStore, {
get: () => read,
put: () => Effect.die("unused"),
remove: () => Effect.die("unused"),
}),
);
expect(calls).toEqual(
stored === "matching"
? ["source-probe", "alternate-probe", "alternate-write"]
: ["source-write"],
);
}),
),
);
it.live.each([undefined, true, false])(
"keeps source workspace metadata and reports draft %s when an alternate answers a detail read",
(isDraft) =>
Effect.scoped(
Effect.gen(function* () {
const noted = yield* Deferred.make<unknown>();
const clientFor = (local: boolean) =>
({
[local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
Effect.succeed({
host: "github.com",
provider: "github",
viewer: "maria-rcks",
accountId: "123",
projectTitle: local ? "local project" : "source project",
workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
}),
[WS_METHODS.pullRequestsDetail]: () =>
local
? Effect.succeed({
projectId: "local-project",
projectTitle: "local project",
workspaceRoot: "/Users/local/repo",
title: "github title",
state: "closed",
...(isDraft === undefined ? {} : { isDraft }),
updatedAt: "2026-10-10T01:52:36Z",
})
: Effect.never,
[WS_METHODS.pullRequestsReportState]: (input: unknown) =>
Deferred.succeed(noted, input).pipe(Effect.asVoid),
}) as unknown as WsRpcProtocolClient;
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
clientFor(false),
clientFor(true),
);
const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 7,
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
expect(result).toEqual({
projectId: "project-1",
projectTitle: "source project",
workspaceRoot: "/srv/source/repo",
title: "github title",
state: "closed",
...(isDraft === undefined ? {} : { isDraft }),
updatedAt: "2026-10-10T01:52:36Z",
});
expect(yield* Deferred.await(noted)).toEqual({
reference: { projectId: "project-1", repository: "acme/web", number: 7 },
state: "closed",
...(isDraft === undefined ? {} : { isDraft }),
});
}),
),
);
it.live(
"refreshes identity before writes and invalidates prior readers across router instances",
() =>
Effect.scoped(
Effect.gen(function* () {
let originAccountId = "123";
const mutations: { environment: string; expectedAccountId: string }[] = [];
const invalidations: { environment: string; input: unknown }[] = [];
const identities: string[] = [];
const clientFor = (local: boolean) => {
const environment = local ? "local" : "origin";
return {
[local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
Effect.sync(() => {
identities.push(environment);
return {
host: "github.com",
provider: "github",
viewer: "maria-rcks",
accountId: local ? "123" : originAccountId,
};
}),
[WS_METHODS.pullRequestsSummary]: () => (local ? Effect.succeed(null) : Effect.never),
[WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId: string }) =>
Effect.sync(() => {
mutations.push({ environment, expectedAccountId: input.expectedAccountId });
}),
[WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
Effect.sync(() => {
invalidations.push({ environment, input });
}),
} as unknown as WsRpcProtocolClient;
};
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
clientFor(false),
clientFor(true),
);
const reference = {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 7,
};
const hostedReference = { ...reference, host: "github.com", allowStale: false };
const route = createPullRequestRouter();
yield* Effect.gen(function* () {
yield* route(WS_METHODS.pullRequestsSummary, reference);
originAccountId = "456";
yield* route(WS_METHODS.pullRequestsRunAction, { ...reference, action: "merge" });
expect(identities.filter((environment) => environment === "origin")).toHaveLength(2);
expect(mutations).toEqual([{ environment: "origin", expectedAccountId: "456" }]);
expect(invalidations).toEqual(
expect.arrayContaining([
{ environment: "origin", input: { reference: expect.objectContaining(reference) } },
{ environment: "origin", input: { reference: hostedReference } },
{ environment: "local", input: { reference: hostedReference } },
{ environment: "origin", input: {} },
{ environment: "local", input: {} },
]),
);
invalidations.length = 0;
const refresh = createPullRequestRouter();
yield* refresh(WS_METHODS.pullRequestsInvalidate, { reference });
expect(invalidations).toContainEqual({
environment: "local",
input: { reference: hostedReference },
});
invalidations.length = 0;
yield* refresh(WS_METHODS.pullRequestsInvalidate, {});
expect(invalidations).toContainEqual({ environment: "local", input: {} });
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
}),
),
);
it.effect("keeps concurrent diff file reads on different hosts separate", () =>
Effect.scoped(
Effect.gen(function* () {
const release = yield* Latch.make();
const started = yield* Latch.make();
const calls: string[] = [];
const client = {
[WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
Effect.gen(function* () {
calls.push(input.host);
yield* started.open;
yield* release.await;
return { oldContents: "", newContents: input.host };
}),
} as unknown as WsRpcProtocolClient;
const { atoms, registry } = yield* makeTestRuntime(client);
const input = {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number: 1,
changeType: "change",
oldPath: "src/app.ts",
newPath: "src/app.ts",
} as const;
const first = atoms.diffFileContents.run(registry, {
environmentId: TARGET.environmentId,
input: { ...input, host: "github.com" },
});
yield* started.await;
const second = atoms.diffFileContents.run(registry, {
environmentId: TARGET.environmentId,
input: { ...input, host: "github.example.com" },
});
yield* release.open;
const results = yield* Effect.promise(() => Promise.all([first, second]));
expect(results).toMatchObject([
{ _tag: "Success", value: { newContents: "github.com" } },
{ _tag: "Success", value: { newContents: "github.example.com" } },
]);
expect(calls).toEqual(["github.com", "github.example.com"]);
}),
),
);
it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)(
"rejects an unsafe quick merge with %s and keeps later actions running",
(reason) =>
Effect.scoped(
Effect.gen(function* () {
const calls: string[] = [];
const client = {
[WS_METHODS.pullRequestsDetail]: () =>
Effect.succeed({
state: reason === "closed" ? "closed" : "open",
isDraft: reason === "draft",
capabilities: { actions: ["merge"], stackActions: true },
viewerPermissions: { actions: reason === "permission" ? [] : ["merge"] },
}),
[WS_METHODS.pullRequestsStack]: () => Effect.succeed(reason === "stack" ? {} : null),
[WS_METHODS.pullRequestsRunAction]: (input: { action: string }) =>
Effect.sync(() => calls.push(input.action)),
} as unknown as WsRpcProtocolClient;
const { atoms, registry } = yield* makeTestRuntime(client);
const target = {
environmentId: TARGET.environmentId,
input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
};
const merge = atoms.runAction.run(registry, {
...target,
input: {
...target.input,
action: "merge",
resolveMergeMethod: () => {
if (reason === "method") throw new Error("No merge method is available.");
return "squash";
},
},
});
const close = atoms.runAction.run(registry, {
...target,
input: { ...target.input, action: "close" },
});
const results = yield* Effect.promise(() => Promise.all([merge, close]));
expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]);
expect(calls).toEqual(["close"]);
}),
),
);
it.effect("keeps a close batch ordered and continues after a refused close", () =>
Effect.scoped(
Effect.gen(function* () {
const calls: number[] = [];
const started = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const client = {
[WS_METHODS.pullRequestsRunAction]: (input: { number: number; action: string }) =>
Effect.gen(function* () {
expect(input.action).toBe("close");
calls.push(input.number);
if (input.number === 6) {
yield* Deferred.succeed(started, undefined);
yield* Deferred.await(release);
}
if (input.number === 5)
return yield* new PullRequestOperationError({
operation: "runAction",
detail: "You cannot close this pull request.",
});
}),
} as unknown as WsRpcProtocolClient;
const { atoms, registry } = yield* makeTestRuntime(client);
const batch = [6, 5, 4].map((number) =>
atoms.runAction.run(registry, {
environmentId: TARGET.environmentId,
input: {
projectId: ProjectId.make("project-1"),
repository: "acme/web",
number,
action: "close",
},
}),
);
yield* Deferred.await(started);
expect(calls).toEqual([6]);
yield* Deferred.succeed(release, undefined);
const results = yield* Effect.promise(() => Promise.all(batch));
expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]);
expect(calls).toEqual([6, 5, 4]);
}),
),
);
const actionReference = {
projectId: ProjectId.make("project-1"),
host: "github.example.com",
repository: "acme/web",
number: 1,
};
const actionReply = {
...actionReference,
provider: "github",
title: "Ship it",
url: "https://github.example.com/acme/web/pull/1",
headBranch: "feature",
baseBranch: "main",
state: "merged" as const,
isDraft: false,
updatedAt: "2026-10-27T10:00:00Z",
observedAt: 200,
};
function actionReplyClient(overrides: Record<string, unknown> = {}) {
return {
[WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
[WS_METHODS.pullRequestsRunAction]: () => Effect.succeed(actionReply),
...overrides,
} as unknown as WsRpcProtocolClient;
}
it.effect("shows an action's reply in loaded readers and moves list rows without reads", () =>
Effect.scoped(
Effect.gen(function* () {
const reads: string[] = [];
const open = { ...actionReference, state: "open", isDraft: true, observedAt: 100 };
const read = (name: string) => () =>
Effect.sync(() => {
reads.push(name);
return open;
});
const replies: unknown[] = [];
const listAnswers: unknown[] = [];
const client = actionReplyClient({
[WS_METHODS.pullRequestsDetail]: read("detail"),
[WS_METHODS.pullRequestsPreview]: read("preview"),
[WS_METHODS.pullRequestsSummary]: read("summary"),
[WS_METHODS.pullRequestsList]: (input: { readonly state: string }) =>
Effect.sync(() => {
reads.push(`list:${input.state}`);
return {
entries: input.state === "merged" ? [] : [open],
viewers: {},
providers: [],
errors: [],
truncated: false,
nextCursors: {},
};
}),
});
const saved = new Map<string, string>();
const { atoms, registry, runtime } = yield* makeTestRuntime(
client,
undefined,
false,
{
actionReply: (target, reply) => Effect.sync(() => replies.push({ target, reply })),
list: (_target, value) => Effect.sync(() => listAnswers.push(value.entries)),
},
{
load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))),
save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)),
},
);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const list = (input: PullRequestListInput) =>
atoms.list({ environmentId: target.environmentId, input });
const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
atoms.detail(target),
atoms.preview(target),
createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
];
const all = list({ state: "all" });
const openDrafts = list({ state: "open", filters: { draft: "only" } });
const merged = list({ state: "merged" });
for (const atom of [...readers, all, openDrafts, merged]) {
registry.mount(atom);
yield* Effect.promise(() => executeAtomQuery(registry, atom));
}
reads.length = 0;
const answer = yield* Effect.promise(() =>
atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }),
);
expect(answer).toMatchObject({ _tag: "Success", value: actionReply });
for (const atom of readers) {
expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
state: "merged",
isDraft: false,
title: "Ship it",
});
}
expect(Option.getOrThrow(AsyncResult.value(registry.get(all))).entries).toMatchObject([
// The row keeps its own read time: the reply does not carry its checks or labels.
{ state: "merged", isDraft: false, observedAt: 100 },
]);
expect(Option.getOrThrow(AsyncResult.value(registry.get(openDrafts))).entries).toEqual([]);
expect(replies).toEqual([{ target, reply: actionReply }]);
// A cold start paints the saved copy, so the patch must replace the saved answer.
const summaryKey = queryPersistenceKey(
"environment-data:pull-requests:linked-summary",
actionReference,
);
expect(JSON.parse(saved.get(summaryKey) ?? "null")).toMatchObject({ state: "merged" });
// Snapshot writers see the patched rows the way they see an answer.
expect(listAnswers).toContainEqual([expect.objectContaining({ state: "merged" })]);
// Only a read can place a row the listing did not hold.
yield* AtomRegistry.getResult(registry, merged, { suspendOnWaiting: true });
expect(reads).toEqual(["list:merged"]);
}),
),
);
it.effect("keeps an action's reply when a refresh started before the action answers late", () =>
Effect.scoped(
Effect.gen(function* () {
let state: "open" | "merged" = "open";
let reads = 0;
const started = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const settled = yield* Deferred.make<void>();
const client = actionReplyClient({
[WS_METHODS.pullRequestsDetail]: () =>
Effect.gen(function* () {
reads++;
const snapshot = { ...actionReference, state, isDraft: false, observedAt: 100 };
if (reads === 2) {
yield* Deferred.succeed(started, undefined);
yield* Deferred.await(release).pipe(
Effect.onExit(() => Deferred.succeed(settled, undefined)),
);
}
return snapshot;
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.sync(() => {
state = "merged";
return actionReply;
}),
});
const { atoms, registry } = yield* makeTestRuntime(client);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const detail = atoms.detail(target);
registry.mount(detail);
yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
registry.refresh(detail);
yield* Deferred.await(started);
yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "merge" },
}),
);
yield* Deferred.succeed(release, undefined);
yield* Deferred.await(settled);
expect(
(yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).state,
).toBe("merged");
expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("merged");
}),
),
);
it.effect("keeps a list read the server's refresh started before the action replied", () =>
Effect.scoped(
Effect.gen(function* () {
const refreshEvents = yield* PubSub.unbounded<number>();
let state: "open" | "merged" = "open";
let reads = 0;
const actionInputs: unknown[] = [];
const listWaiting = Latch.makeUnsafe();
const release = yield* Deferred.make<void>();
const client = actionReplyClient({
[WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
[WS_METHODS.pullRequestsList]: () =>
Effect.gen(function* () {
reads++;
const entries = [
{ ...actionReference, state, isDraft: false, updatedAt: actionReply.updatedAt },
];
if (reads === 2) yield* Deferred.await(release);
return {
entries,
viewers: {},
providers: [],
errors: [],
truncated: false,
nextCursors: {},
};
}),
[WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
Effect.gen(function* () {
actionInputs.push(input);
state = "merged";
// The server announces its refresh before it replies.
yield* PubSub.publish(refreshEvents, 1);
yield* listWaiting.await;
return actionReply;
}),
});
const { atoms, registry } = yield* makeTestRuntime(client);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
const unmount = registry.mount(list);
yield* Effect.addFinalizer(() => Effect.sync(unmount));
yield* Effect.promise(() => executeAtomQuery(registry, list));
const stop = registry.subscribe(list, (result) => {
if (result.waiting) listWaiting.openUnsafe();
});
yield* Effect.addFinalizer(() => Effect.sync(stop));
yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "merge" },
}),
);
yield* Deferred.succeed(release, undefined);
expect(
(yield* AtomRegistry.getResult(registry, list, { suspendOnWaiting: true })).entries,
).toMatchObject([{ state: "merged" }]);
expect(reads).toBe(2);
expect(actionInputs).toEqual([expect.objectContaining({ replyWithSummary: true })]);
}),
),
);
it.effect("restarts a list page read sent while the action was in flight", () =>
Effect.scoped(
Effect.gen(function* () {
const refreshEvents = yield* PubSub.unbounded<number>();
let state: "open" | "closed" = "open";
let pageReads = 0;
const actionSent = yield* Deferred.make<void>();
const pageStarted = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const settled = yield* Deferred.make<void>();
const listResult = (entries: ReadonlyArray<object>) => ({
entries,
viewers: {},
providers: [],
errors: [],
truncated: false,
nextCursors: {},
});
const client = actionReplyClient({
[WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
[WS_METHODS.pullRequestsList]: (input: PullRequestListInput) =>
Effect.gen(function* () {
const entries =
state === "open"
? [{ ...actionReference, state, isDraft: false, updatedAt: "2026-10-27T09:00:00Z" }]
: [];
if (input.cursors !== undefined && ++pageReads === 2) {
yield* Deferred.succeed(pageStarted, undefined);
yield* Deferred.await(release).pipe(
Effect.onExit(() => Deferred.succeed(settled, undefined)),
);
}
return listResult(input.cursors === undefined ? [] : entries);
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.gen(function* () {
yield* Deferred.succeed(actionSent, undefined);
yield* Deferred.await(pageStarted);
state = "closed";
yield* PubSub.publish(refreshEvents, 1);
return { ...actionReply, state: "closed" };
}),
});
const { atoms, registry } = yield* makeTestRuntime(client);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const listInput = { state: "open" } as const;
const head = atoms.list({ environmentId: target.environmentId, input: listInput });
const page = atoms.list({
environmentId: target.environmentId,
input: { ...listInput, cursors: { "github.example.com": "page-2" } },
});
for (const atom of [head, page]) {
const unmount = registry.mount(atom);
yield* Effect.addFinalizer(() => Effect.sync(unmount));
yield* Effect.promise(() => executeAtomQuery(registry, atom));
}
const action = yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "close" },
}),
).pipe(Effect.forkScoped);
yield* Deferred.await(actionSent);
// Loading more rows re-reads a page while the close is on the wire.
registry.refresh(page);
yield* Fiber.join(action);
yield* Deferred.succeed(release, undefined);
yield* Deferred.await(settled);
expect(
(yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true })).entries,
).toEqual([]);
}),
),
);
it.effect("shows a reopen reply at once and re-reads the fields it lacks", () =>
Effect.scoped(
Effect.gen(function* () {
let reads = 0;
const release = yield* Deferred.make<void>();
const client = actionReplyClient({
[WS_METHODS.pullRequestsDetail]: () =>
Effect.gen(function* () {
reads++;
if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
yield* Deferred.await(release);
return { ...actionReference, state: "open", observedAt: 300 };
}),
[WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
});
const { atoms, registry } = yield* makeTestRuntime(client);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const detail = atoms.detail(target);
registry.mount(detail);
yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "reopen" },
}),
);
expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
expect(reads).toBe(2);
yield* Deferred.succeed(release, undefined);
expect(
(yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
).toBe(300);
}),
),
);
it.effect("keeps each reader's read time when a reply leaves its checks as they were", () =>
Effect.scoped(
Effect.gen(function* () {
const shown = {
...actionReference,
state: "open",
isDraft: true,
updatedAt: "2026-10-27T09:00:00Z",
observedAt: 100,
checks: [{ status: "success" }],
checksState: "passing",
};
const client = actionReplyClient({
[WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
[WS_METHODS.pullRequestsSummary]: () => Effect.succeed(shown),
[WS_METHODS.pullRequestsList]: () =>
Effect.succeed({
entries: [shown],
viewers: {},
providers: [],
errors: [],
truncated: false,
nextCursors: {},
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.succeed({ ...actionReply, state: "open", observedAt: 300 }),
});
const answeredAt: Array<number | undefined> = [];
const { atoms, registry, runtime } = yield* makeTestRuntime(client, undefined, false, {
detail: (_target, value) => Effect.sync(() => answeredAt.push(value.observedAt)),
});
const target = { environmentId: TARGET.environmentId, input: actionReference };
const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
atoms.detail(target),
createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
];
const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
for (const atom of [...readers, list]) {
registry.mount(atom);
yield* Effect.promise(() => executeAtomQuery(registry, atom));
}
yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "ready" },
}),
);
// Checks read at 100 must not pass for a read at 300 against a newer checks read.
for (const atom of readers) {
expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
isDraft: false,
observedAt: 100,
});
}
expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([
{ isDraft: false, checksState: "passing", observedAt: 100 },
]);
expect(answeredAt).toEqual([100, 100]);
}),
),
);
it.effect("re-reads an unstamped preview rather than order a reply against it", () =>
Effect.scoped(
Effect.gen(function* () {
let reads = 0;
const client = actionReplyClient({
// Previews from servers before action replies carry neither update nor read time.
[WS_METHODS.pullRequestsPreview]: () =>
Effect.sync(() => {
reads++;
return {
...actionReference,
title: "Reopened elsewhere",
url: actionReply.url,
author: null,
state: "open",
isDraft: false,
createdAt: "2026-10-27T08:00:00Z",
};
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.succeed({ ...actionReply, state: "closed" }),
});
const { atoms, registry } = yield* makeTestRuntime(client);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const preview = atoms.preview(target);
registry.mount(preview);
yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true });
yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "close" },
}),
);
expect(Option.getOrThrow(AsyncResult.value(registry.get(preview))).state).toBe("open");
expect(
(yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).state,
).toBe("open");
expect(reads).toBe(2);
}),
),
);
it.effect("leaves a loaded list page alone when the reply concerns none of its rows", () =>
Effect.scoped(
Effect.gen(function* () {
let pageReads = 0;
const client = actionReplyClient({
[WS_METHODS.pullRequestsList]: () =>
Effect.sync(() => {
pageReads++;
return {
entries: [
{
...actionReference,
number: 2,
state: "open",
isDraft: false,
updatedAt: "2026-10-27T09:00:00Z",
},
],
viewers: {},
providers: [],
errors: [],
truncated: false,
nextCursors: {},
};
}),
[WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
});
const { atoms, registry } = yield* makeTestRuntime(client);
const target = { environmentId: TARGET.environmentId, input: actionReference };
const page = atoms.list({
environmentId: target.environmentId,
input: { state: "open", cursors: { "github.example.com": "page-2" } },
});
const unmount = registry.mount(page);
yield* Effect.addFinalizer(() => Effect.sync(unmount));
yield* Effect.promise(() => executeAtomQuery(registry, page));
yield* Effect.promise(() =>
atoms.runAction.run(registry, {
...target,
input: { ...actionReference, action: "ready" },
}),
);
yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true });
expect(pageReads).toBe(1);
}),
),
);
it.effect("keeps the server's post-commit read when a reopen reply lacks fields", () =>
Effect.scoped(
Effect.gen(function* () {
const refreshEvents = yield* PubSub.unbounded<number>();
let reads = 0;
const detailWaiting = Latch.makeUnsafe();
const release = yield* Deferred.make<void>();
const client = actionReplyClient({
[WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
[WS_METHODS.pullRequestsDetail]: () =>
Effect.gen(function* () {
reads++;
if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
yield* Deferred.await(release);
return { ...actionReference, state: "open", observedAt: 300 };
}),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.gen(function* () {
// The server announces its refresh before it replies.
yield* PubSub.publish(refreshEvents, 1);
yield* detailWaiting.await;
return { ...actionReply, state: "open" };
}),
});