The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { createCommandPermissions } from "./commandPermissions.ts"; |
| 2 | import { RpcPermissionGuard } from "../rpc/client.ts"; |
| 3 | import { vi } from "vite-plus/test"; |
| 4 | import { |
| 5 | EnvironmentId, |
| 6 | AuthSourceControlWriteScope, |
| 7 | AuthOrchestrationOperateScope, |
| 8 | ProjectId, |
| 9 | PullRequestOperationError, |
| 10 | SourceControlProviderKind, |
| 11 | WS_METHODS, |
| 12 | type AuthSessionState, |
| 13 | type PullRequestListInput, |
| 14 | type PullRequestListEntry, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { expect, it } from "@effect/vitest"; |
| 17 | import * as Schema from "effect/Schema"; |
| 18 | import * as Deferred from "effect/Deferred"; |
| 19 | import * as Exit from "effect/Exit"; |
| 20 | import * as Fiber from "effect/Fiber"; |
| 21 | import * as TestClock from "effect/testing/TestClock"; |
| 22 | import * as Effect from "effect/Effect"; |
| 23 | import * as Latch from "effect/Latch"; |
| 24 | import * as Layer from "effect/Layer"; |
| 25 | import * as Option from "effect/Option"; |
| 26 | import * as PubSub from "effect/PubSub"; |
| 27 | import * as Stream from "effect/Stream"; |
| 28 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 29 | import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 30 | |
| 31 | import { |
| 32 | AVAILABLE_CONNECTION_STATE, |
| 33 | ConnectionTransientError, |
| 34 | PrimaryConnectionTarget, |
| 35 | SshConnectionTarget, |
| 36 | type PreparedConnection, |
| 37 | type SupervisorConnectionState, |
| 38 | } from "../connection/model.ts"; |
| 39 | import * as EnvironmentRegistry from "../connection/registry.ts"; |
| 40 | import { SshConnectionProfile, type ConnectionCatalogEntry } from "../connection/catalog.ts"; |
| 41 | import * as ConnectionProfileStore from "../connection/profileStore.ts"; |
| 42 | import * as EnvironmentSupervisor from "../connection/supervisor.ts"; |
| 43 | import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; |
| 44 | import type { RpcSession } from "../rpc/session.ts"; |
| 45 | import { |
| 46 | applyPullRequestSummaryEdits, |
| 47 | createLinkedPullRequestSummaryAtomFamily, |
| 48 | createPullRequestEnvironmentAtoms, |
| 49 | createPullRequestStackAtomFamily, |
| 50 | editHeldPullRequestListEntries, |
| 51 | heldPullRequestListEntriesAtom, |
| 52 | pullRequestHostAnswer, |
| 53 | pullRequestPendingEditsAtom, |
| 54 | pullRequestPendingEditsFor, |
| 55 | } from "./pullRequests.ts"; |
| 56 | import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts"; |
| 57 | import { executeAtomQuery, queryPersistenceKey } from "./runtime.ts"; |
| 58 | import { EnvironmentQueryStore } from "./queryPersistence.ts"; |
| 59 | import { createPullRequestRouter } from "./pullRequestRouting.ts"; |
| 60 | import { PullRequestRoutingPermissions } from "../connection/pullRequestRoutingPermissions.ts"; |
| 61 | |
| 62 | const trustedRouting = { |
| 63 | get: () => Effect.succeed("read-write" as const), |
| 64 | changes: Stream.empty, |
| 65 | set: () => Effect.void, |
| 66 | forget: () => Effect.void, |
| 67 | }; |
| 68 | |
| 69 | class MutationRefused extends Schema.TaggedError<MutationRefused>()("MutationRefused", {}) {} |
| 70 | |
| 71 | it.effect.each([ |
| 72 | "prefers the local environment with the same github account", |
| 73 | "falls back before mutation when the local account differs", |
| 74 | "never retries an ambiguous mutation failure", |
| 75 | "returns a fast local source read without checking alternate identities", |
| 76 | "keeps single-environment requests free of identity lookups", |
| 77 | "keeps a local origin ahead of another local environment", |
| 78 | "keeps mutations on an old origin server without retrying them", |
| 79 | "skips an old alternate server before dispatching a mutation", |
| 80 | "returns a successful mutation when source invalidation stalls", |
| 81 | "does not dispatch after routing permission is revoked during the probe", |
| 82 | "keeps mutations on the origin when the alternate is disabled", |
| 83 | "does not dispatch after the alternate is disabled during the probe", |
| 84 | "preserves a local source account rejection when alternate accounts differ", |
| 85 | ] as const)("%s", (scenario) => |
| 86 | Effect.gen(function* () { |
| 87 | const stalls = scenario === "returns a successful mutation when source invalidation stalls"; |
| 88 | const invalidationStalled = yield* Deferred.make<void>(); |
| 89 | const calls: string[] = []; |
| 90 | const inputs: unknown[] = []; |
| 91 | let trusted = true; |
| 92 | let disableAlternate = Effect.void; |
| 93 | const switchedAccount = |
| 94 | scenario === "preserves a local source account rejection when alternate accounts differ"; |
| 95 | const mismatch = |
| 96 | scenario === "falls back before mutation when the local account differs" || switchedAccount; |
| 97 | const ambiguous = scenario === "never retries an ambiguous mutation failure"; |
| 98 | const reading = |
| 99 | scenario === "returns a fast local source read without checking alternate identities"; |
| 100 | const single = scenario === "keeps single-environment requests free of identity lookups"; |
| 101 | const localOrigin = |
| 102 | scenario === "keeps a local origin ahead of another local environment" || |
| 103 | switchedAccount || |
| 104 | reading; |
| 105 | const oldOrigin = scenario === "keeps mutations on an old origin server without retrying them"; |
| 106 | const oldAlternate = scenario === "skips an old alternate server before dispatching a mutation"; |
| 107 | const failure = new PullRequestOperationError({ |
| 108 | operation: switchedAccount ? "routeIdentity" : "runAction", |
| 109 | detail: "connection lost after dispatch", |
| 110 | }); |
| 111 | const clientFor = (local: boolean) => { |
| 112 | const name = local ? "local" : "origin"; |
| 113 | return { |
| 114 | [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: ( |
| 115 | input: unknown, |
| 116 | ) => |
| 117 | Effect.gen(function* () { |
| 118 | if (local) expect(input).toEqual({ host: "github.com" }); |
| 119 | calls.push(`${name}:identity`); |
| 120 | if ( |
| 121 | local && |
| 122 | scenario === "does not dispatch after the alternate is disabled during the probe" |
| 123 | ) |
| 124 | yield* disableAlternate; |
| 125 | if ( |
| 126 | local && |
| 127 | scenario === "does not dispatch after routing permission is revoked during the probe" |
| 128 | ) |
| 129 | trusted = false; |
| 130 | if ((!local && oldOrigin) || (local && oldAlternate)) { |
| 131 | return yield* Effect.die(`Unknown request tag: ${WS_METHODS.pullRequestsRouting}`); |
| 132 | } |
| 133 | return { |
| 134 | host: "github.com", |
| 135 | provider: "github", |
| 136 | viewer: "maria-rcks", |
| 137 | accountId: local && mismatch ? "456" : "123", |
| 138 | }; |
| 139 | }), |
| 140 | [WS_METHODS.pullRequestsRunAction]: (input: unknown) => |
| 141 | Effect.gen(function* () { |
| 142 | calls.push(`${name}:mutation`); |
| 143 | inputs.push(input); |
| 144 | if ( |
| 145 | !local && |
| 146 | switchedAccount && |
| 147 | (input as { expectedAccountId?: string }).expectedAccountId === "123" |
| 148 | ) |
| 149 | return yield* failure; |
| 150 | if (local && ambiguous) return yield* failure; |
| 151 | }), |
| 152 | [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) => |
| 153 | Effect.gen(function* () { |
| 154 | calls.push(`${name}:read`); |
| 155 | expect(input.allowStale).toBe(false); |
| 156 | if (local) return yield* failure; |
| 157 | return null; |
| 158 | }), |
| 159 | [WS_METHODS.pullRequestsInvalidate]: () => |
| 160 | Effect.gen(function* () { |
| 161 | calls.push(`${name}:invalidate`); |
| 162 | if (!local && stalls) { |
| 163 | yield* Deferred.succeed(invalidationStalled, undefined); |
| 164 | return yield* Effect.never; |
| 165 | } |
| 166 | }), |
| 167 | } as unknown as WsRpcProtocolClient; |
| 168 | }; |
| 169 | const { environmentRegistry, supervisor } = yield* makeTestRuntime( |
| 170 | clientFor(false), |
| 171 | single ? undefined : clientFor(true), |
| 172 | localOrigin, |
| 173 | ); |
| 174 | disableAlternate = SubscriptionRef.update( |
| 175 | environmentRegistry.entries, |
| 176 | (entries) => |
| 177 | new Map( |
| 178 | [...entries].map(([id, entry]) => [ |
| 179 | id, |
| 180 | id === TARGET.environmentId ? entry : { ...entry, enabled: false }, |
| 181 | ]), |
| 182 | ), |
| 183 | ); |
| 184 | const disabled = scenario === "keeps mutations on the origin when the alternate is disabled"; |
| 185 | const disabledDuringProbe = |
| 186 | scenario === "does not dispatch after the alternate is disabled during the probe"; |
| 187 | if (disabled) yield* disableAlternate; |
| 188 | const input = { |
| 189 | projectId: ProjectId.make("project-1"), |
| 190 | host: "github.com", |
| 191 | repository: "acme/web", |
| 192 | number: 7, |
| 193 | action: "merge" as const, |
| 194 | }; |
| 195 | const route = createPullRequestRouter(); |
| 196 | const routed = ( |
| 197 | reading |
| 198 | ? route(WS_METHODS.pullRequestsSummary, input) |
| 199 | : route(WS_METHODS.pullRequestsRunAction, input) |
| 200 | ).pipe( |
| 201 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 202 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 203 | Effect.provideService(PullRequestRoutingPermissions, { |
| 204 | ...trustedRouting, |
| 205 | get: () => Effect.succeed(trusted ? "read-write" : "off"), |
| 206 | }), |
| 207 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 208 | Effect.result, |
| 209 | ); |
| 210 | const result = stalls |
| 211 | ? yield* Effect.gen(function* () { |
| 212 | const fiber = yield* Effect.forkChild(routed); |
| 213 | yield* Deferred.await(invalidationStalled); |
| 214 | yield* TestClock.adjust("1 second"); |
| 215 | return yield* Fiber.join(fiber); |
| 216 | }) |
| 217 | : yield* routed; |
| 218 | |
| 219 | if (switchedAccount) { |
| 220 | expect(result).toMatchObject({ _tag: "Failure", failure }); |
| 221 | expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]); |
| 222 | expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]); |
| 223 | } else if (ambiguous) { |
| 224 | expect(result).toMatchObject({ _tag: "Failure", failure }); |
| 225 | expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]); |
| 226 | } else { |
| 227 | expect(result._tag).toBe("Success"); |
| 228 | if (single || disabled) { |
| 229 | expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual(["origin:mutation"]); |
| 230 | } else if (reading) expect(calls).toEqual(["origin:read"]); |
| 231 | else if ( |
| 232 | mismatch || |
| 233 | localOrigin || |
| 234 | oldOrigin || |
| 235 | oldAlternate || |
| 236 | !trusted || |
| 237 | disabledDuringProbe |
| 238 | ) |
| 239 | expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]); |
| 240 | else { |
| 241 | expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]); |
| 242 | expect(calls).toContain("origin:invalidate"); |
| 243 | expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]); |
| 244 | } |
| 245 | } |
| 246 | }), |
| 247 | ); |
| 248 | |
| 249 | it.effect.each([ |
| 250 | { probe: "origin", cancelled: "first" }, |
| 251 | { probe: "origin", cancelled: "waiter" }, |
| 252 | { probe: "alternate", cancelled: "first" }, |
| 253 | { probe: "alternate", cancelled: "waiter" }, |
| 254 | ] as const)( |
| 255 | "preserves a shared $probe probe's other reader when the $cancelled cancels", |
| 256 | ({ probe, cancelled }) => |
| 257 | Effect.gen(function* () { |
| 258 | const started = yield* Deferred.make<void>(); |
| 259 | const release = yield* Deferred.make<void>(); |
| 260 | let probes = 0; |
| 261 | const clientFor = (local: boolean) => |
| 262 | ({ |
| 263 | [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () => |
| 264 | Effect.gen(function* () { |
| 265 | if (local === (probe === "alternate")) { |
| 266 | probes++; |
| 267 | yield* Deferred.succeed(started, undefined); |
| 268 | yield* Deferred.await(release); |
| 269 | } |
| 270 | return { |
| 271 | host: "github.com", |
| 272 | provider: "github", |
| 273 | viewer: "maria", |
| 274 | accountId: "123", |
| 275 | }; |
| 276 | }), |
| 277 | [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null), |
| 278 | }) as unknown as WsRpcProtocolClient; |
| 279 | const { environmentRegistry, supervisor } = yield* makeTestRuntime( |
| 280 | clientFor(false), |
| 281 | clientFor(true), |
| 282 | ); |
| 283 | const read = () => |
| 284 | createPullRequestRouter()(WS_METHODS.pullRequestsSummary, { |
| 285 | projectId: ProjectId.make("project-1"), |
| 286 | repository: "acme/web", |
| 287 | number: 7, |
| 288 | }).pipe( |
| 289 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 290 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 291 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 292 | ); |
| 293 | const first = yield* read().pipe(Effect.forkChild); |
| 294 | yield* Deferred.await(started); |
| 295 | const waiter = yield* read().pipe(Effect.forkChild); |
| 296 | yield* Effect.yieldNow; |
| 297 | yield* Fiber.interrupt(cancelled === "first" ? first : waiter); |
| 298 | yield* Deferred.succeed(release, undefined); |
| 299 | expect(yield* Fiber.join(cancelled === "first" ? waiter : first)).toBeNull(); |
| 300 | expect(probes).toBe(cancelled === "first" ? 2 : 1); |
| 301 | yield* read(); |
| 302 | expect(probes).toBe(cancelled === "first" ? 3 : 2); |
| 303 | }), |
| 304 | ); |
| 305 | |
| 306 | it.effect.each(["revoked", "disabled"] as const)( |
| 307 | "rechecks routing after an alternate with a shared probe is %s", |
| 308 | (change) => |
| 309 | Effect.gen(function* () { |
| 310 | const started = yield* Deferred.make<void>(); |
| 311 | const release = yield* Deferred.make<void>(); |
| 312 | const reads: string[] = []; |
| 313 | let trusted = true; |
| 314 | let probes = 0; |
| 315 | const clientFor = (local: boolean) => |
| 316 | ({ |
| 317 | [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () => |
| 318 | Effect.gen(function* () { |
| 319 | if (local) { |
| 320 | probes++; |
| 321 | yield* Deferred.succeed(started, undefined); |
| 322 | yield* Deferred.await(release); |
| 323 | } |
| 324 | return { |
| 325 | host: "github.com", |
| 326 | provider: "github", |
| 327 | viewer: "maria", |
| 328 | accountId: "123", |
| 329 | }; |
| 330 | }), |
| 331 | [WS_METHODS.pullRequestsSummary]: () => |
| 332 | Effect.sync(() => { |
| 333 | reads.push(local ? "local" : "origin"); |
| 334 | return null; |
| 335 | }), |
| 336 | }) as unknown as WsRpcProtocolClient; |
| 337 | const { environmentRegistry, supervisor } = yield* makeTestRuntime( |
| 338 | clientFor(false), |
| 339 | clientFor(true), |
| 340 | ); |
| 341 | const readers = yield* Effect.all( |
| 342 | Array.from({ length: 2 }, () => |
| 343 | createPullRequestRouter()(WS_METHODS.pullRequestsSummary, { |
| 344 | projectId: ProjectId.make("project-1"), |
| 345 | repository: "acme/web", |
| 346 | number: 7, |
| 347 | }), |
| 348 | ), |
| 349 | { concurrency: "unbounded" }, |
| 350 | ).pipe( |
| 351 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 352 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 353 | Effect.provideService(PullRequestRoutingPermissions, { |
| 354 | ...trustedRouting, |
| 355 | get: () => Effect.sync(() => (trusted ? "read-write" : "off")), |
| 356 | }), |
| 357 | Effect.forkChild, |
| 358 | ); |
| 359 | yield* Deferred.await(started); |
| 360 | yield* Effect.yieldNow; |
| 361 | if (change === "revoked") trusted = false; |
| 362 | else |
| 363 | yield* SubscriptionRef.update( |
| 364 | environmentRegistry.entries, |
| 365 | (entries) => |
| 366 | new Map( |
| 367 | [...entries].map(([id, entry]) => [ |
| 368 | id, |
| 369 | id === TARGET.environmentId ? entry : { ...entry, enabled: false }, |
| 370 | ]), |
| 371 | ), |
| 372 | ); |
| 373 | yield* Deferred.succeed(release, undefined); |
| 374 | expect(yield* Fiber.join(readers)).toEqual([null, null]); |
| 375 | expect(probes).toBe(1); |
| 376 | expect(reads).toEqual(["origin", "origin"]); |
| 377 | }), |
| 378 | ); |
| 379 | |
| 380 | it.effect.each(["origin", "alternate"] as const)( |
| 381 | "keeps pending metadata from an old %s connection separate from its replacement", |
| 382 | (reconnected) => |
| 383 | Effect.gen(function* () { |
| 384 | const started = yield* Deferred.make<void>(); |
| 385 | const release = yield* Deferred.make<void>(); |
| 386 | const probes: string[] = []; |
| 387 | const clientFor = (local: boolean, replacement = false) => |
| 388 | ({ |
| 389 | [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () => |
| 390 | Effect.gen(function* () { |
| 391 | if (local === (reconnected === "alternate")) { |
| 392 | probes.push(replacement ? "new" : "old"); |
| 393 | if (!replacement) { |
| 394 | yield* Deferred.succeed(started, undefined); |
| 395 | yield* Deferred.await(release); |
| 396 | } |
| 397 | } |
| 398 | return { |
| 399 | host: "github.com", |
| 400 | provider: "github", |
| 401 | viewer: "maria", |
| 402 | accountId: "123", |
| 403 | }; |
| 404 | }), |
| 405 | [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null), |
| 406 | }) as unknown as WsRpcProtocolClient; |
| 407 | const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime( |
| 408 | clientFor(false), |
| 409 | clientFor(true), |
| 410 | ); |
| 411 | const read = () => |
| 412 | createPullRequestRouter()(WS_METHODS.pullRequestsSummary, { |
| 413 | projectId: ProjectId.make("project-1"), |
| 414 | repository: "acme/web", |
| 415 | number: 7, |
| 416 | }).pipe( |
| 417 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 418 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 419 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 420 | ); |
| 421 | const first = yield* read().pipe(Effect.forkChild); |
| 422 | yield* Deferred.await(started); |
| 423 | yield* SubscriptionRef.set( |
| 424 | (reconnected === "origin" ? supervisor : localSupervisor).session, |
| 425 | Option.some(session(clientFor(reconnected === "alternate", true))), |
| 426 | ); |
| 427 | expect(yield* read()).toBeNull(); |
| 428 | expect(probes).toEqual(["old", "new"]); |
| 429 | yield* Deferred.succeed(release, undefined); |
| 430 | expect(yield* Fiber.join(first)).toBeNull(); |
| 431 | }), |
| 432 | ); |
| 433 | |
| 434 | it.effect("forgets routed viewed marks when a viewed-files batch fails", () => |
| 435 | Effect.gen(function* () { |
| 436 | const reference = { |
| 437 | projectId: ProjectId.make("project-1"), |
| 438 | host: "github.com", |
| 439 | repository: "acme/web", |
| 440 | number: 7, |
| 441 | }; |
| 442 | const invalidations: { environment: string; input: unknown }[] = []; |
| 443 | const identity = () => |
| 444 | Effect.succeed({ |
| 445 | host: reference.host, |
| 446 | provider: "github", |
| 447 | accountId: "123", |
| 448 | viewer: "maria-rcks", |
| 449 | }); |
| 450 | const clientFor = (environment: string) => |
| 451 | ({ |
| 452 | [WS_METHODS.pullRequestsRouting]: identity, |
| 453 | [WS_METHODS.pullRequestsRoutingIdentity]: identity, |
| 454 | [WS_METHODS.pullRequestsFilesViewed]: () => |
| 455 | Effect.succeed({ files: [{ path: "a.ts", state: "unviewed" }], truncated: false }), |
| 456 | // The host may have applied part of the batch before refusing the rest. |
| 457 | [WS_METHODS.pullRequestsSetFilesViewed]: () => Effect.fail("second path refused"), |
| 458 | [WS_METHODS.pullRequestsInvalidate]: (input: unknown) => |
| 459 | Effect.sync(() => { |
| 460 | invalidations.push({ environment, input }); |
| 461 | }), |
| 462 | }) as unknown as WsRpcProtocolClient; |
| 463 | const { environmentRegistry, supervisor } = yield* makeTestRuntime( |
| 464 | clientFor("origin"), |
| 465 | clientFor("local"), |
| 466 | ); |
| 467 | const route = createPullRequestRouter(); |
| 468 | const write = yield* Effect.gen(function* () { |
| 469 | yield* route(WS_METHODS.pullRequestsFilesViewed, reference); |
| 470 | return yield* Effect.exit( |
| 471 | route(WS_METHODS.pullRequestsSetFilesViewed, { |
| 472 | ...reference, |
| 473 | files: [ |
| 474 | { path: "a.ts", viewed: true }, |
| 475 | { path: "b.ts", viewed: true }, |
| 476 | ], |
| 477 | }), |
| 478 | ); |
| 479 | }).pipe( |
| 480 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 481 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 482 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 483 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 484 | ); |
| 485 | expect(write._tag).toBe("Failure"); |
| 486 | expect(invalidations).toContainEqual({ |
| 487 | environment: "local", |
| 488 | input: { reference: expect.objectContaining(reference), filesViewedOnly: true }, |
| 489 | }); |
| 490 | for (const call of invalidations) { |
| 491 | expect(call.input).toMatchObject({ filesViewedOnly: true }); |
| 492 | } |
| 493 | }), |
| 494 | ); |
| 495 | |
| 496 | const TARGET = new PrimaryConnectionTarget({ |
| 497 | environmentId: EnvironmentId.make("environment-1"), |
| 498 | label: "Test environment", |
| 499 | httpBaseUrl: "https://environment.example.test", |
| 500 | wsBaseUrl: "wss://environment.example.test", |
| 501 | }); |
| 502 | |
| 503 | function session(client: WsRpcProtocolClient): RpcSession { |
| 504 | return { |
| 505 | client: { |
| 506 | ...client, |
| 507 | [WS_METHODS.pullRequestsInvalidate]: |
| 508 | client[WS_METHODS.pullRequestsInvalidate] ?? (() => Effect.void), |
| 509 | }, |
| 510 | initialConfig: client[WS_METHODS.serverGetConfig]?.({}).pipe(Effect.orDie) ?? Effect.never, |
| 511 | subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input), |
| 512 | ready: Effect.void, |
| 513 | probe: Effect.void, |
| 514 | inboundFrames: Effect.succeed(0), |
| 515 | closed: Effect.never, |
| 516 | }; |
| 517 | } |
| 518 | |
| 519 | const makeTestRuntime = Effect.fn("makeTestRuntime")(function* ( |
| 520 | client: WsRpcProtocolClient, |
| 521 | localClient?: WsRpcProtocolClient, |
| 522 | localOrigin = false, |
| 523 | onAnswer: Parameters<typeof createPullRequestEnvironmentAtoms>[1] = {}, |
| 524 | queryStore: typeof EnvironmentQueryStore.Service = null, |
| 525 | diffLoader: PullRequestDiffLoader.PullRequestDiffLoader["Service"] = { |
| 526 | load: () => Effect.die("unused"), |
| 527 | }, |
| 528 | ) { |
| 529 | const originTarget = localOrigin |
| 530 | ? new PrimaryConnectionTarget({ |
| 531 | ...TARGET, |
| 532 | httpBaseUrl: "http://localhost:3774", |
| 533 | wsBaseUrl: "ws://localhost:3774", |
| 534 | }) |
| 535 | : TARGET; |
| 536 | const connectionState: SupervisorConnectionState = { |
| 537 | ...AVAILABLE_CONNECTION_STATE, |
| 538 | desired: true, |
| 539 | network: "online", |
| 540 | phase: "connected", |
| 541 | attempt: 1, |
| 542 | generation: 1, |
| 543 | }; |
| 544 | const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ |
| 545 | target: originTarget, |
| 546 | state: yield* SubscriptionRef.make(connectionState), |
| 547 | session: yield* SubscriptionRef.make(Option.some(session(client))), |
| 548 | prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()), |
| 549 | connect: Effect.void, |
| 550 | disconnect: Effect.void, |
| 551 | retryNow: Effect.void, |
| 552 | } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); |
| 553 | const localTarget = new PrimaryConnectionTarget({ |
| 554 | environmentId: EnvironmentId.make("local-environment"), |
| 555 | label: "Local environment", |
| 556 | httpBaseUrl: "http://localhost:3773", |
| 557 | wsBaseUrl: "ws://localhost:3773", |
| 558 | }); |
| 559 | const localSupervisor = { |
| 560 | ...supervisor, |
| 561 | target: localTarget, |
| 562 | session: yield* SubscriptionRef.make(Option.some(session(localClient ?? client))), |
| 563 | }; |
| 564 | const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ |
| 565 | entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>( |
| 566 | new Map([ |
| 567 | [ |
| 568 | originTarget.environmentId, |
| 569 | { target: originTarget, profile: Option.none(), enabled: true }, |
| 570 | ], |
| 571 | ...(localClient === undefined |
| 572 | ? [] |
| 573 | : [ |
| 574 | [ |
| 575 | localTarget.environmentId, |
| 576 | { target: localTarget, profile: Option.none(), enabled: true }, |
| 577 | ] as const, |
| 578 | ]), |
| 579 | ]), |
| 580 | ), |
| 581 | run: (environmentId, effect) => |
| 582 | Effect.provideService( |
| 583 | effect, |
| 584 | EnvironmentSupervisor.EnvironmentSupervisor, |
| 585 | environmentId === localTarget.environmentId ? localSupervisor : supervisor, |
| 586 | ), |
| 587 | runStream: (_environmentId, stream) => |
| 588 | Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 589 | followStream: (_environmentId, stream) => |
| 590 | Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 591 | } as EnvironmentRegistry.EnvironmentRegistry["Service"]); |
| 592 | const runtime = Atom.runtime( |
| 593 | Layer.mergeAll( |
| 594 | Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 595 | Layer.succeed(PullRequestDiffLoader.PullRequestDiffLoader, diffLoader), |
| 596 | Layer.succeed(EnvironmentQueryStore, queryStore), |
| 597 | ), |
| 598 | ); |
| 599 | const atoms = createPullRequestEnvironmentAtoms(runtime, onAnswer); |
| 600 | const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) => |
| 601 | Effect.sync(() => registry.dispose()), |
| 602 | ); |
| 603 | return { runtime, atoms, registry, environmentRegistry, supervisor, localSupervisor }; |
| 604 | }); |
| 605 | |
| 606 | it.effect.each([ |
| 607 | "default", |
| 608 | "origin-off", |
| 609 | "destination-off", |
| 610 | "read-only", |
| 611 | "destination-disabled", |
| 612 | "destination-unsupported", |
| 613 | ] as const)( |
| 614 | "preserves source requests when routing to another environment is blocked by %s", |
| 615 | (permission) => |
| 616 | Effect.gen(function* () { |
| 617 | const calls: string[] = []; |
| 618 | const failure = new PullRequestOperationError({ |
| 619 | operation: "summary", |
| 620 | detail: "source failed", |
| 621 | }); |
| 622 | const client = { |
| 623 | [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) => |
| 624 | Effect.suspend(() => { |
| 625 | calls.push("source-read"); |
| 626 | expect(input.allowStale).toBeUndefined(); |
| 627 | return Effect.fail(failure); |
| 628 | }), |
| 629 | [WS_METHODS.pullRequestsRunAction]: () => |
| 630 | Effect.sync(() => { |
| 631 | calls.push("source-write"); |
| 632 | }), |
| 633 | } as unknown as WsRpcProtocolClient; |
| 634 | const alternate = { |
| 635 | [WS_METHODS.pullRequestsRoutingIdentity]: () => |
| 636 | Effect.die("untrusted environment was contacted"), |
| 637 | } as unknown as WsRpcProtocolClient; |
| 638 | const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime( |
| 639 | client, |
| 640 | alternate, |
| 641 | ); |
| 642 | if (permission === "destination-disabled" || permission === "destination-unsupported") { |
| 643 | yield* SubscriptionRef.update( |
| 644 | environmentRegistry.entries, |
| 645 | (entries) => |
| 646 | new Map( |
| 647 | [...entries].map(([id, entry]) => [ |
| 648 | id, |
| 649 | id === TARGET.environmentId |
| 650 | ? entry |
| 651 | : { |
| 652 | ...entry, |
| 653 | enabled: permission !== "destination-disabled", |
| 654 | ...(permission === "destination-unsupported" |
| 655 | ? { unsupportedReason: "Protocol version mismatch" } |
| 656 | : {}), |
| 657 | }, |
| 658 | ]), |
| 659 | ), |
| 660 | ); |
| 661 | yield* SubscriptionRef.set(localSupervisor.session, Option.none()); |
| 662 | } |
| 663 | const ref = { |
| 664 | projectId: ProjectId.make("project-1"), |
| 665 | repository: "private/repo", |
| 666 | number: 7, |
| 667 | }; |
| 668 | const request = Effect.gen(function* () { |
| 669 | const route = createPullRequestRouter(); |
| 670 | if (permission !== "read-only") |
| 671 | yield* route(WS_METHODS.pullRequestsSummary, ref).pipe(Effect.flip); |
| 672 | yield* route(WS_METHODS.pullRequestsRunAction, { ...ref, action: "merge" }); |
| 673 | }).pipe( |
| 674 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 675 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 676 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 677 | ); |
| 678 | yield* permission === "default" |
| 679 | ? request |
| 680 | : request.pipe( |
| 681 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 682 | Effect.provideService(PullRequestRoutingPermissions, { |
| 683 | ...trustedRouting, |
| 684 | get: (entry) => |
| 685 | Effect.succeed( |
| 686 | permission === "read-only" |
| 687 | ? "read" |
| 688 | : permission === "destination-disabled" || |
| 689 | permission === "destination-unsupported" |
| 690 | ? "read-write" |
| 691 | : (entry.target.environmentId === TARGET.environmentId) === |
| 692 | (permission === "origin-off") |
| 693 | ? "off" |
| 694 | : "read-write", |
| 695 | ), |
| 696 | }), |
| 697 | ); |
| 698 | expect(calls).toEqual( |
| 699 | permission === "read-only" ? ["source-write"] : ["source-read", "source-write"], |
| 700 | ); |
| 701 | }), |
| 702 | ); |
| 703 | |
| 704 | it.effect.each( |
| 705 | (["origin", "destination"] as const).flatMap((side) => |
| 706 | (["matching", "changed", "missing", "unavailable", "failed"] as const).map((stored) => ({ |
| 707 | side, |
| 708 | stored, |
| 709 | })), |
| 710 | ), |
| 711 | )("checks the current $side SSH profile before routing with $stored storage", ({ side, stored }) => |
| 712 | Effect.gen(function* () { |
| 713 | const calls: string[] = []; |
| 714 | const identity = { |
| 715 | host: "github.com", |
| 716 | provider: "github", |
| 717 | viewer: "maria", |
| 718 | accountId: "123", |
| 719 | }; |
| 720 | const client = { |
| 721 | [WS_METHODS.pullRequestsRouting]: () => |
| 722 | Effect.sync(() => { |
| 723 | calls.push("source-probe"); |
| 724 | return identity; |
| 725 | }), |
| 726 | [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) => |
| 727 | Effect.gen(function* () { |
| 728 | if (input.expectedAccountId !== undefined) { |
| 729 | return yield* new PullRequestOperationError({ |
| 730 | operation: "routeIdentity", |
| 731 | detail: "Source guard refused.", |
| 732 | }); |
| 733 | } |
| 734 | calls.push("source-write"); |
| 735 | }), |
| 736 | [WS_METHODS.pullRequestsInvalidate]: () => Effect.void, |
| 737 | } as unknown as WsRpcProtocolClient; |
| 738 | const alternate = { |
| 739 | [WS_METHODS.pullRequestsRoutingIdentity]: () => |
| 740 | Effect.sync(() => { |
| 741 | calls.push("alternate-probe"); |
| 742 | return identity; |
| 743 | }), |
| 744 | [WS_METHODS.pullRequestsRunAction]: () => |
| 745 | Effect.sync(() => { |
| 746 | calls.push("alternate-write"); |
| 747 | }), |
| 748 | [WS_METHODS.pullRequestsInvalidate]: () => Effect.void, |
| 749 | } as unknown as WsRpcProtocolClient; |
| 750 | const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate); |
| 751 | const environmentId = |
| 752 | side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment"); |
| 753 | const profile = new SshConnectionProfile({ |
| 754 | connectionId: "ssh-1", |
| 755 | environmentId, |
| 756 | label: "SSH", |
| 757 | target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 }, |
| 758 | }); |
| 759 | yield* SubscriptionRef.update(environmentRegistry.entries, (entries) => |
| 760 | new Map(entries).set(environmentId, { |
| 761 | target: new SshConnectionTarget({ |
| 762 | environmentId, |
| 763 | connectionId: profile.connectionId, |
| 764 | label: "SSH", |
| 765 | }), |
| 766 | profile: Option.some(profile), |
| 767 | enabled: true, |
| 768 | }), |
| 769 | ); |
| 770 | const read = Effect.suspend(() => |
| 771 | stored === "failed" |
| 772 | ? Effect.fail( |
| 773 | new ConnectionTransientError({ |
| 774 | reason: "remote-unavailable", |
| 775 | detail: "Profile storage unavailable.", |
| 776 | }), |
| 777 | ) |
| 778 | : Effect.succeed( |
| 779 | stored === "missing" |
| 780 | ? Option.none() |
| 781 | : Option.some( |
| 782 | stored === "changed" |
| 783 | ? new SshConnectionProfile({ |
| 784 | ...profile, |
| 785 | target: { ...profile.target, hostname: "replacement.example.test" }, |
| 786 | }) |
| 787 | : profile, |
| 788 | ), |
| 789 | ), |
| 790 | ); |
| 791 | const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, { |
| 792 | projectId: ProjectId.make("project-1"), |
| 793 | repository: "private/repo", |
| 794 | number: 7, |
| 795 | action: "merge", |
| 796 | }).pipe( |
| 797 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 798 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 799 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 800 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 801 | ); |
| 802 | yield* stored === "unavailable" |
| 803 | ? route |
| 804 | : route.pipe( |
| 805 | Effect.provideService(ConnectionProfileStore.ConnectionProfileStore, { |
| 806 | get: () => read, |
| 807 | put: () => Effect.die("unused"), |
| 808 | remove: () => Effect.die("unused"), |
| 809 | }), |
| 810 | ); |
| 811 | expect(calls).toEqual( |
| 812 | stored === "matching" |
| 813 | ? ["source-probe", "alternate-probe", "alternate-write"] |
| 814 | : ["source-write"], |
| 815 | ); |
| 816 | }), |
| 817 | ); |
| 818 | |
| 819 | it.effect.each([undefined, true, false])( |
| 820 | "keeps source workspace metadata and reports draft %s when an alternate answers a detail read", |
| 821 | (isDraft) => |
| 822 | Effect.gen(function* () { |
| 823 | const noted = yield* Deferred.make<unknown>(); |
| 824 | const clientFor = (local: boolean) => |
| 825 | ({ |
| 826 | [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () => |
| 827 | Effect.succeed({ |
| 828 | host: "github.com", |
| 829 | provider: "github", |
| 830 | viewer: "maria-rcks", |
| 831 | accountId: "123", |
| 832 | projectTitle: local ? "local project" : "source project", |
| 833 | workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo", |
| 834 | }), |
| 835 | [WS_METHODS.pullRequestsDetail]: () => |
| 836 | local |
| 837 | ? Effect.succeed({ |
| 838 | projectId: "local-project", |
| 839 | projectTitle: "local project", |
| 840 | workspaceRoot: "/Users/local/repo", |
| 841 | title: "github title", |
| 842 | state: "closed", |
| 843 | ...(isDraft === undefined ? {} : { isDraft }), |
| 844 | updatedAt: "2026-10-10T01:52:36Z", |
| 845 | }) |
| 846 | : Effect.never, |
| 847 | [WS_METHODS.pullRequestsReportState]: (input: unknown) => |
| 848 | Deferred.succeed(noted, input).pipe(Effect.asVoid), |
| 849 | }) as unknown as WsRpcProtocolClient; |
| 850 | const { environmentRegistry, supervisor } = yield* makeTestRuntime( |
| 851 | clientFor(false), |
| 852 | clientFor(true), |
| 853 | ); |
| 854 | const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, { |
| 855 | projectId: ProjectId.make("project-1"), |
| 856 | repository: "acme/web", |
| 857 | number: 7, |
| 858 | }).pipe( |
| 859 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 860 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 861 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 862 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 863 | ); |
| 864 | expect(result).toEqual({ |
| 865 | projectId: "project-1", |
| 866 | projectTitle: "source project", |
| 867 | workspaceRoot: "/srv/source/repo", |
| 868 | title: "github title", |
| 869 | state: "closed", |
| 870 | ...(isDraft === undefined ? {} : { isDraft }), |
| 871 | updatedAt: "2026-10-10T01:52:36Z", |
| 872 | }); |
| 873 | expect(yield* Deferred.await(noted)).toEqual({ |
| 874 | reference: { projectId: "project-1", repository: "acme/web", number: 7 }, |
| 875 | state: "closed", |
| 876 | ...(isDraft === undefined ? {} : { isDraft }), |
| 877 | }); |
| 878 | }), |
| 879 | ); |
| 880 | |
| 881 | it.effect( |
| 882 | "refreshes identity before writes and invalidates prior readers across router instances", |
| 883 | () => |
| 884 | Effect.gen(function* () { |
| 885 | let originAccountId = "123"; |
| 886 | const mutations: { environment: string; expectedAccountId: string }[] = []; |
| 887 | const invalidations: { environment: string; input: unknown }[] = []; |
| 888 | const identities: string[] = []; |
| 889 | const clientFor = (local: boolean) => { |
| 890 | const environment = local ? "local" : "origin"; |
| 891 | return { |
| 892 | [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () => |
| 893 | Effect.sync(() => { |
| 894 | identities.push(environment); |
| 895 | return { |
| 896 | host: "github.com", |
| 897 | provider: "github", |
| 898 | viewer: "maria-rcks", |
| 899 | accountId: local ? "123" : originAccountId, |
| 900 | }; |
| 901 | }), |
| 902 | [WS_METHODS.pullRequestsSummary]: () => (local ? Effect.succeed(null) : Effect.never), |
| 903 | [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId: string }) => |
| 904 | Effect.sync(() => { |
| 905 | mutations.push({ environment, expectedAccountId: input.expectedAccountId }); |
| 906 | }), |
| 907 | [WS_METHODS.pullRequestsInvalidate]: (input: unknown) => |
| 908 | Effect.sync(() => { |
| 909 | invalidations.push({ environment, input }); |
| 910 | }), |
| 911 | } as unknown as WsRpcProtocolClient; |
| 912 | }; |
| 913 | const { environmentRegistry, supervisor } = yield* makeTestRuntime( |
| 914 | clientFor(false), |
| 915 | clientFor(true), |
| 916 | ); |
| 917 | const reference = { |
| 918 | projectId: ProjectId.make("project-1"), |
| 919 | repository: "acme/web", |
| 920 | number: 7, |
| 921 | }; |
| 922 | const hostedReference = { ...reference, host: "github.com", allowStale: false }; |
| 923 | const route = createPullRequestRouter(); |
| 924 | yield* Effect.gen(function* () { |
| 925 | yield* route(WS_METHODS.pullRequestsSummary, reference); |
| 926 | originAccountId = "456"; |
| 927 | yield* route(WS_METHODS.pullRequestsRunAction, { ...reference, action: "merge" }); |
| 928 | |
| 929 | expect(identities.filter((environment) => environment === "origin")).toHaveLength(2); |
| 930 | expect(mutations).toEqual([{ environment: "origin", expectedAccountId: "456" }]); |
| 931 | expect(invalidations).toEqual( |
| 932 | expect.arrayContaining([ |
| 933 | { environment: "origin", input: { reference: expect.objectContaining(reference) } }, |
| 934 | { environment: "origin", input: { reference: hostedReference } }, |
| 935 | { environment: "local", input: { reference: hostedReference } }, |
| 936 | { environment: "origin", input: {} }, |
| 937 | { environment: "local", input: {} }, |
| 938 | ]), |
| 939 | ); |
| 940 | |
| 941 | invalidations.length = 0; |
| 942 | const refresh = createPullRequestRouter(); |
| 943 | yield* refresh(WS_METHODS.pullRequestsInvalidate, { reference }); |
| 944 | expect(invalidations).toContainEqual({ |
| 945 | environment: "local", |
| 946 | input: { reference: hostedReference }, |
| 947 | }); |
| 948 | |
| 949 | invalidations.length = 0; |
| 950 | yield* refresh(WS_METHODS.pullRequestsInvalidate, {}); |
| 951 | expect(invalidations).toContainEqual({ environment: "local", input: {} }); |
| 952 | }).pipe( |
| 953 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), |
| 954 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 955 | Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }), |
| 956 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 957 | ); |
| 958 | }), |
| 959 | ); |
| 960 | |
| 961 | it.effect("keeps concurrent diff file reads on different hosts separate", () => |
| 962 | Effect.gen(function* () { |
| 963 | const release = yield* Latch.make(); |
| 964 | const started = yield* Latch.make(); |
| 965 | const calls: string[] = []; |
| 966 | const client = { |
| 967 | [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) => |
| 968 | Effect.gen(function* () { |
| 969 | calls.push(input.host); |
| 970 | yield* started.open; |
| 971 | yield* release.await; |
| 972 | return { oldContents: "", newContents: input.host }; |
| 973 | }), |
| 974 | } as unknown as WsRpcProtocolClient; |
| 975 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 976 | const input = { |
| 977 | projectId: ProjectId.make("project-1"), |
| 978 | repository: "acme/web", |
| 979 | number: 1, |
| 980 | changeType: "change", |
| 981 | oldPath: "src/app.ts", |
| 982 | newPath: "src/app.ts", |
| 983 | } as const; |
| 984 | const first = yield* Effect.forkChild( |
| 985 | Effect.exit( |
| 986 | atoms.diffFileContents.run(registry, { |
| 987 | environmentId: TARGET.environmentId, |
| 988 | input: { ...input, host: "github.com" }, |
| 989 | }), |
| 990 | ), |
| 991 | { startImmediately: true }, |
| 992 | ); |
| 993 | yield* started.await; |
| 994 | const second = yield* Effect.forkChild( |
| 995 | Effect.exit( |
| 996 | atoms.diffFileContents.run(registry, { |
| 997 | environmentId: TARGET.environmentId, |
| 998 | input: { ...input, host: "github.example.com" }, |
| 999 | }), |
| 1000 | ), |
| 1001 | { startImmediately: true }, |
| 1002 | ); |
| 1003 | yield* release.open; |
| 1004 | |
| 1005 | const results = yield* Fiber.joinAll([first, second]); |
| 1006 | expect(results).toMatchObject([ |
| 1007 | { _tag: "Success", value: { newContents: "github.com" } }, |
| 1008 | { _tag: "Success", value: { newContents: "github.example.com" } }, |
| 1009 | ]); |
| 1010 | expect(calls).toEqual(["github.com", "github.example.com"]); |
| 1011 | }), |
| 1012 | ); |
| 1013 | |
| 1014 | it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)( |
| 1015 | "rejects an unsafe quick merge with %s and keeps later actions running", |
| 1016 | (reason) => |
| 1017 | Effect.gen(function* () { |
| 1018 | const calls: string[] = []; |
| 1019 | const client = { |
| 1020 | [WS_METHODS.pullRequestsDetail]: () => |
| 1021 | Effect.succeed({ |
| 1022 | state: reason === "closed" ? "closed" : "open", |
| 1023 | isDraft: reason === "draft", |
| 1024 | capabilities: { actions: ["merge"], stackActions: true }, |
| 1025 | viewerPermissions: { actions: reason === "permission" ? [] : ["merge"] }, |
| 1026 | }), |
| 1027 | [WS_METHODS.pullRequestsStack]: () => Effect.succeed(reason === "stack" ? {} : null), |
| 1028 | [WS_METHODS.pullRequestsRunAction]: (input: { action: string }) => |
| 1029 | Effect.sync(() => calls.push(input.action)), |
| 1030 | } as unknown as WsRpcProtocolClient; |
| 1031 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1032 | const target = { |
| 1033 | environmentId: TARGET.environmentId, |
| 1034 | input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, |
| 1035 | }; |
| 1036 | const merge = yield* Effect.forkChild( |
| 1037 | Effect.exit( |
| 1038 | atoms.runAction.run(registry, { |
| 1039 | ...target, |
| 1040 | input: { |
| 1041 | ...target.input, |
| 1042 | action: "merge", |
| 1043 | resolveMergeMethod: () => { |
| 1044 | if (reason === "method") throw new Error("No merge method is available."); |
| 1045 | return "squash"; |
| 1046 | }, |
| 1047 | }, |
| 1048 | }), |
| 1049 | ), |
| 1050 | { startImmediately: true }, |
| 1051 | ); |
| 1052 | const close = yield* Effect.forkChild( |
| 1053 | Effect.exit( |
| 1054 | atoms.runAction.run(registry, { |
| 1055 | ...target, |
| 1056 | input: { ...target.input, action: "close" }, |
| 1057 | }), |
| 1058 | ), |
| 1059 | { startImmediately: true }, |
| 1060 | ); |
| 1061 | const results = yield* Fiber.joinAll([merge, close]); |
| 1062 | expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]); |
| 1063 | expect(calls).toEqual(["close"]); |
| 1064 | }), |
| 1065 | ); |
| 1066 | |
| 1067 | it.effect("keeps a close batch ordered and continues after a refused close", () => |
| 1068 | Effect.gen(function* () { |
| 1069 | const calls: number[] = []; |
| 1070 | const started = yield* Deferred.make<void>(); |
| 1071 | const release = yield* Deferred.make<void>(); |
| 1072 | const client = { |
| 1073 | [WS_METHODS.pullRequestsRunAction]: (input: { number: number; action: string }) => |
| 1074 | Effect.gen(function* () { |
| 1075 | expect(input.action).toBe("close"); |
| 1076 | calls.push(input.number); |
| 1077 | if (input.number === 6) { |
| 1078 | yield* Deferred.succeed(started, undefined); |
| 1079 | yield* Deferred.await(release); |
| 1080 | } |
| 1081 | if (input.number === 5) |
| 1082 | return yield* new PullRequestOperationError({ |
| 1083 | operation: "runAction", |
| 1084 | detail: "You cannot close this pull request.", |
| 1085 | }); |
| 1086 | }), |
| 1087 | } as unknown as WsRpcProtocolClient; |
| 1088 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1089 | const batch = yield* Effect.forEach([6, 5, 4], (number) => |
| 1090 | Effect.forkChild( |
| 1091 | Effect.exit( |
| 1092 | atoms.runAction.run(registry, { |
| 1093 | environmentId: TARGET.environmentId, |
| 1094 | input: { |
| 1095 | projectId: ProjectId.make("project-1"), |
| 1096 | repository: "acme/web", |
| 1097 | number, |
| 1098 | action: "close", |
| 1099 | }, |
| 1100 | }), |
| 1101 | ), |
| 1102 | { startImmediately: true }, |
| 1103 | ), |
| 1104 | ); |
| 1105 | yield* Deferred.await(started); |
| 1106 | expect(calls).toEqual([6]); |
| 1107 | yield* Deferred.succeed(release, undefined); |
| 1108 | const results = yield* Fiber.joinAll(batch); |
| 1109 | expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]); |
| 1110 | expect(calls).toEqual([6, 5, 4]); |
| 1111 | }), |
| 1112 | ); |
| 1113 | |
| 1114 | const actionReference = { |
| 1115 | projectId: ProjectId.make("project-1"), |
| 1116 | host: "github.example.com", |
| 1117 | repository: "acme/web", |
| 1118 | number: 1, |
| 1119 | }; |
| 1120 | const actionReply = { |
| 1121 | ...actionReference, |
| 1122 | provider: "github", |
| 1123 | title: "Ship it", |
| 1124 | url: "https://github.example.com/acme/web/pull/1", |
| 1125 | headBranch: "feature", |
| 1126 | baseBranch: "main", |
| 1127 | state: "merged" as const, |
| 1128 | isDraft: false, |
| 1129 | updatedAt: "2026-10-27T10:00:00Z", |
| 1130 | observedAt: 200, |
| 1131 | }; |
| 1132 | |
| 1133 | const actionListEntry: PullRequestListEntry = { |
| 1134 | ...actionReply, |
| 1135 | provider: SourceControlProviderKind.make("github"), |
| 1136 | projectTitle: "Web", |
| 1137 | state: "open", |
| 1138 | author: null, |
| 1139 | mergeability: "unknown", |
| 1140 | additions: 0, |
| 1141 | deletions: 0, |
| 1142 | createdAt: actionReply.updatedAt, |
| 1143 | viewerReviewRequested: false, |
| 1144 | labels: [], |
| 1145 | }; |
| 1146 | |
| 1147 | function actionReplyClient(overrides: Record<string, unknown> = {}) { |
| 1148 | return { |
| 1149 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never, |
| 1150 | [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed(actionReply), |
| 1151 | ...overrides, |
| 1152 | } as unknown as WsRpcProtocolClient; |
| 1153 | } |
| 1154 | |
| 1155 | it.effect("shows an action's reply in loaded readers and moves list rows without reads", () => |
| 1156 | Effect.gen(function* () { |
| 1157 | const reads: string[] = []; |
| 1158 | const open = { ...actionReference, state: "open", isDraft: true, observedAt: 100 }; |
| 1159 | const read = (name: string) => () => |
| 1160 | Effect.sync(() => { |
| 1161 | reads.push(name); |
| 1162 | return open; |
| 1163 | }); |
| 1164 | const replies: unknown[] = []; |
| 1165 | const listAnswers: unknown[] = []; |
| 1166 | const client = actionReplyClient({ |
| 1167 | [WS_METHODS.pullRequestsDetail]: read("detail"), |
| 1168 | [WS_METHODS.pullRequestsPreview]: read("preview"), |
| 1169 | [WS_METHODS.pullRequestsSummary]: read("summary"), |
| 1170 | [WS_METHODS.pullRequestsList]: (input: { readonly state: string }) => |
| 1171 | Effect.sync(() => { |
| 1172 | reads.push(`list:${input.state}`); |
| 1173 | return { |
| 1174 | entries: input.state === "merged" ? [] : [open], |
| 1175 | viewers: {}, |
| 1176 | providers: [], |
| 1177 | errors: [], |
| 1178 | truncated: false, |
| 1179 | nextCursors: {}, |
| 1180 | }; |
| 1181 | }), |
| 1182 | }); |
| 1183 | const saved = new Map<string, string>(); |
| 1184 | const { atoms, registry, runtime } = yield* makeTestRuntime( |
| 1185 | client, |
| 1186 | undefined, |
| 1187 | false, |
| 1188 | { |
| 1189 | actionReply: (target, reply) => Effect.sync(() => replies.push({ target, reply })), |
| 1190 | list: (_target, value) => Effect.sync(() => listAnswers.push(value.entries)), |
| 1191 | }, |
| 1192 | { |
| 1193 | load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))), |
| 1194 | save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)), |
| 1195 | }, |
| 1196 | ); |
| 1197 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1198 | const list = (input: PullRequestListInput) => |
| 1199 | atoms.list({ environmentId: target.environmentId, input }); |
| 1200 | const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [ |
| 1201 | atoms.detail(target), |
| 1202 | atoms.preview(target), |
| 1203 | createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target), |
| 1204 | ]; |
| 1205 | const all = list({ state: "all" }); |
| 1206 | const openDrafts = list({ state: "open", filters: { draft: "only" } }); |
| 1207 | const merged = list({ state: "merged" }); |
| 1208 | for (const atom of [...readers, all, openDrafts, merged]) { |
| 1209 | registry.mount(atom); |
| 1210 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 1211 | } |
| 1212 | reads.length = 0; |
| 1213 | |
| 1214 | const answer = yield* Effect.exit( |
| 1215 | atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }), |
| 1216 | ); |
| 1217 | |
| 1218 | expect(answer).toMatchObject({ _tag: "Success", value: actionReply }); |
| 1219 | for (const atom of readers) { |
| 1220 | expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({ |
| 1221 | state: "merged", |
| 1222 | isDraft: false, |
| 1223 | title: "Ship it", |
| 1224 | }); |
| 1225 | } |
| 1226 | expect(Option.getOrThrow(AsyncResult.value(registry.get(all))).entries).toMatchObject([ |
| 1227 | // The row keeps its own read time: the reply does not carry its checks or labels. |
| 1228 | { state: "merged", isDraft: false, observedAt: 100 }, |
| 1229 | ]); |
| 1230 | expect(Option.getOrThrow(AsyncResult.value(registry.get(openDrafts))).entries).toEqual([]); |
| 1231 | expect(replies).toEqual([{ target, reply: actionReply }]); |
| 1232 | // A cold start paints the saved copy, so the patch must replace the saved answer. |
| 1233 | const summaryKey = queryPersistenceKey( |
| 1234 | "environment-data:pull-requests:linked-summary", |
| 1235 | actionReference, |
| 1236 | ); |
| 1237 | expect(JSON.parse(saved.get(summaryKey) ?? "null")).toMatchObject({ state: "merged" }); |
| 1238 | // Snapshot writers see the patched rows the way they see an answer. |
| 1239 | expect(listAnswers).toContainEqual([expect.objectContaining({ state: "merged" })]); |
| 1240 | // Only a read can place a row the listing did not hold. |
| 1241 | yield* AtomRegistry.getResult(registry, merged, { suspendOnWaiting: true }); |
| 1242 | expect(reads).toEqual(["list:merged"]); |
| 1243 | }), |
| 1244 | ); |
| 1245 | |
| 1246 | it.effect("keeps an action's reply when a refresh started before the action answers late", () => |
| 1247 | Effect.gen(function* () { |
| 1248 | let state: "open" | "merged" = "open"; |
| 1249 | let reads = 0; |
| 1250 | const started = yield* Deferred.make<void>(); |
| 1251 | const release = yield* Deferred.make<void>(); |
| 1252 | const settled = yield* Deferred.make<void>(); |
| 1253 | const client = actionReplyClient({ |
| 1254 | [WS_METHODS.pullRequestsDetail]: () => |
| 1255 | Effect.gen(function* () { |
| 1256 | reads++; |
| 1257 | const snapshot = { ...actionReference, state, isDraft: false, observedAt: 100 }; |
| 1258 | if (reads === 2) { |
| 1259 | yield* Deferred.succeed(started, undefined); |
| 1260 | yield* Deferred.await(release).pipe( |
| 1261 | Effect.onExit(() => Deferred.succeed(settled, undefined)), |
| 1262 | ); |
| 1263 | } |
| 1264 | return snapshot; |
| 1265 | }), |
| 1266 | [WS_METHODS.pullRequestsRunAction]: () => |
| 1267 | Effect.sync(() => { |
| 1268 | state = "merged"; |
| 1269 | return actionReply; |
| 1270 | }), |
| 1271 | }); |
| 1272 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1273 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1274 | const detail = atoms.detail(target); |
| 1275 | registry.mount(detail); |
| 1276 | yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }); |
| 1277 | registry.refresh(detail); |
| 1278 | yield* Deferred.await(started); |
| 1279 | |
| 1280 | yield* Effect.exit( |
| 1281 | atoms.runAction.run(registry, { |
| 1282 | ...target, |
| 1283 | input: { ...actionReference, action: "merge" }, |
| 1284 | }), |
| 1285 | ); |
| 1286 | yield* Deferred.succeed(release, undefined); |
| 1287 | yield* Deferred.await(settled); |
| 1288 | |
| 1289 | expect( |
| 1290 | (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).state, |
| 1291 | ).toBe("merged"); |
| 1292 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("merged"); |
| 1293 | }), |
| 1294 | ); |
| 1295 | |
| 1296 | it.effect("keeps a list read the server's refresh started before the action replied", () => |
| 1297 | Effect.gen(function* () { |
| 1298 | const refreshEvents = yield* PubSub.unbounded<number>(); |
| 1299 | let state: "open" | "merged" = "open"; |
| 1300 | let reads = 0; |
| 1301 | const actionInputs: unknown[] = []; |
| 1302 | const listWaiting = Latch.makeUnsafe(); |
| 1303 | const release = yield* Deferred.make<void>(); |
| 1304 | const client = actionReplyClient({ |
| 1305 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents), |
| 1306 | [WS_METHODS.pullRequestsList]: () => |
| 1307 | Effect.gen(function* () { |
| 1308 | reads++; |
| 1309 | const entries = [ |
| 1310 | { ...actionReference, state, isDraft: false, updatedAt: actionReply.updatedAt }, |
| 1311 | ]; |
| 1312 | if (reads === 2) yield* Deferred.await(release); |
| 1313 | return { |
| 1314 | entries, |
| 1315 | viewers: {}, |
| 1316 | providers: [], |
| 1317 | errors: [], |
| 1318 | truncated: false, |
| 1319 | nextCursors: {}, |
| 1320 | }; |
| 1321 | }), |
| 1322 | [WS_METHODS.pullRequestsRunAction]: (input: unknown) => |
| 1323 | Effect.gen(function* () { |
| 1324 | actionInputs.push(input); |
| 1325 | state = "merged"; |
| 1326 | // The server announces its refresh before it replies. |
| 1327 | yield* PubSub.publish(refreshEvents, 1); |
| 1328 | yield* listWaiting.await; |
| 1329 | return actionReply; |
| 1330 | }), |
| 1331 | }); |
| 1332 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1333 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1334 | const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } }); |
| 1335 | const unmount = registry.mount(list); |
| 1336 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1337 | yield* Effect.promise(() => executeAtomQuery(registry, list)); |
| 1338 | const stop = registry.subscribe(list, (result) => { |
| 1339 | if (result.waiting) listWaiting.openUnsafe(); |
| 1340 | }); |
| 1341 | yield* Effect.addFinalizer(() => Effect.sync(stop)); |
| 1342 | |
| 1343 | yield* Effect.exit( |
| 1344 | atoms.runAction.run(registry, { |
| 1345 | ...target, |
| 1346 | input: { ...actionReference, action: "merge" }, |
| 1347 | }), |
| 1348 | ); |
| 1349 | yield* Deferred.succeed(release, undefined); |
| 1350 | |
| 1351 | expect( |
| 1352 | (yield* AtomRegistry.getResult(registry, list, { suspendOnWaiting: true })).entries, |
| 1353 | ).toMatchObject([{ state: "merged" }]); |
| 1354 | expect(reads).toBe(2); |
| 1355 | expect(actionInputs).toEqual([expect.objectContaining({ replyWithSummary: true })]); |
| 1356 | }), |
| 1357 | ); |
| 1358 | |
| 1359 | it.effect("restarts a list page read sent while the action was in flight", () => |
| 1360 | Effect.gen(function* () { |
| 1361 | const refreshEvents = yield* PubSub.unbounded<number>(); |
| 1362 | let state: "open" | "closed" = "open"; |
| 1363 | let pageReads = 0; |
| 1364 | const actionSent = yield* Deferred.make<void>(); |
| 1365 | const pageStarted = yield* Deferred.make<void>(); |
| 1366 | const release = yield* Deferred.make<void>(); |
| 1367 | const settled = yield* Deferred.make<void>(); |
| 1368 | const listResult = (entries: ReadonlyArray<object>) => ({ |
| 1369 | entries, |
| 1370 | viewers: {}, |
| 1371 | providers: [], |
| 1372 | errors: [], |
| 1373 | truncated: false, |
| 1374 | nextCursors: {}, |
| 1375 | }); |
| 1376 | const client = actionReplyClient({ |
| 1377 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents), |
| 1378 | [WS_METHODS.pullRequestsList]: (input: PullRequestListInput) => |
| 1379 | Effect.gen(function* () { |
| 1380 | const entries = |
| 1381 | state === "open" |
| 1382 | ? [{ ...actionReference, state, isDraft: false, updatedAt: "2026-10-27T09:00:00Z" }] |
| 1383 | : []; |
| 1384 | if (input.cursors !== undefined && ++pageReads === 2) { |
| 1385 | yield* Deferred.succeed(pageStarted, undefined); |
| 1386 | yield* Deferred.await(release).pipe( |
| 1387 | Effect.onExit(() => Deferred.succeed(settled, undefined)), |
| 1388 | ); |
| 1389 | } |
| 1390 | return listResult(input.cursors === undefined ? [] : entries); |
| 1391 | }), |
| 1392 | [WS_METHODS.pullRequestsRunAction]: () => |
| 1393 | Effect.gen(function* () { |
| 1394 | yield* Deferred.succeed(actionSent, undefined); |
| 1395 | yield* Deferred.await(pageStarted); |
| 1396 | state = "closed"; |
| 1397 | yield* PubSub.publish(refreshEvents, 1); |
| 1398 | return { ...actionReply, state: "closed" }; |
| 1399 | }), |
| 1400 | }); |
| 1401 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1402 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1403 | const listInput = { state: "open" } as const; |
| 1404 | const head = atoms.list({ environmentId: target.environmentId, input: listInput }); |
| 1405 | const page = atoms.list({ |
| 1406 | environmentId: target.environmentId, |
| 1407 | input: { ...listInput, cursors: { "github.example.com": "page-2" } }, |
| 1408 | }); |
| 1409 | for (const atom of [head, page]) { |
| 1410 | const unmount = registry.mount(atom); |
| 1411 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1412 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 1413 | } |
| 1414 | |
| 1415 | const action = yield* Effect.exit( |
| 1416 | atoms.runAction.run(registry, { |
| 1417 | ...target, |
| 1418 | input: { ...actionReference, action: "close" }, |
| 1419 | }), |
| 1420 | ).pipe(Effect.forkScoped); |
| 1421 | yield* Deferred.await(actionSent); |
| 1422 | // Loading more rows re-reads a page while the close is on the wire. |
| 1423 | registry.refresh(page); |
| 1424 | yield* Fiber.join(action); |
| 1425 | yield* Deferred.succeed(release, undefined); |
| 1426 | yield* Deferred.await(settled); |
| 1427 | |
| 1428 | expect( |
| 1429 | (yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true })).entries, |
| 1430 | ).toEqual([]); |
| 1431 | }), |
| 1432 | ); |
| 1433 | |
| 1434 | it.effect("shows a reopen reply at once and re-reads the fields it lacks", () => |
| 1435 | Effect.gen(function* () { |
| 1436 | let reads = 0; |
| 1437 | const release = yield* Deferred.make<void>(); |
| 1438 | const client = actionReplyClient({ |
| 1439 | [WS_METHODS.pullRequestsDetail]: () => |
| 1440 | Effect.gen(function* () { |
| 1441 | reads++; |
| 1442 | if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 }; |
| 1443 | yield* Deferred.await(release); |
| 1444 | return { ...actionReference, state: "open", observedAt: 300 }; |
| 1445 | }), |
| 1446 | [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }), |
| 1447 | }); |
| 1448 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1449 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1450 | const detail = atoms.detail(target); |
| 1451 | registry.mount(detail); |
| 1452 | yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }); |
| 1453 | |
| 1454 | yield* Effect.exit( |
| 1455 | atoms.runAction.run(registry, { |
| 1456 | ...target, |
| 1457 | input: { ...actionReference, action: "reopen" }, |
| 1458 | }), |
| 1459 | ); |
| 1460 | |
| 1461 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open"); |
| 1462 | expect(reads).toBe(2); |
| 1463 | yield* Deferred.succeed(release, undefined); |
| 1464 | expect( |
| 1465 | (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt, |
| 1466 | ).toBe(300); |
| 1467 | }), |
| 1468 | ); |
| 1469 | |
| 1470 | it.effect("keeps each reader's read time when a reply leaves its checks as they were", () => |
| 1471 | Effect.gen(function* () { |
| 1472 | const shown = { |
| 1473 | ...actionReference, |
| 1474 | state: "open", |
| 1475 | isDraft: true, |
| 1476 | updatedAt: "2026-10-27T09:00:00Z", |
| 1477 | observedAt: 100, |
| 1478 | checks: [{ status: "success" }], |
| 1479 | checksState: "passing", |
| 1480 | }; |
| 1481 | const client = actionReplyClient({ |
| 1482 | [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown), |
| 1483 | [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(shown), |
| 1484 | [WS_METHODS.pullRequestsList]: () => |
| 1485 | Effect.succeed({ |
| 1486 | entries: [shown], |
| 1487 | viewers: {}, |
| 1488 | providers: [], |
| 1489 | errors: [], |
| 1490 | truncated: false, |
| 1491 | nextCursors: {}, |
| 1492 | }), |
| 1493 | [WS_METHODS.pullRequestsRunAction]: () => |
| 1494 | Effect.succeed({ ...actionReply, state: "open", observedAt: 300 }), |
| 1495 | }); |
| 1496 | const answeredAt: Array<number | undefined> = []; |
| 1497 | const { atoms, registry, runtime } = yield* makeTestRuntime(client, undefined, false, { |
| 1498 | detail: (_target, value) => Effect.sync(() => answeredAt.push(value.observedAt)), |
| 1499 | }); |
| 1500 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1501 | const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [ |
| 1502 | atoms.detail(target), |
| 1503 | createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target), |
| 1504 | ]; |
| 1505 | const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } }); |
| 1506 | for (const atom of [...readers, list]) { |
| 1507 | registry.mount(atom); |
| 1508 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 1509 | } |
| 1510 | |
| 1511 | yield* Effect.exit( |
| 1512 | atoms.runAction.run(registry, { |
| 1513 | ...target, |
| 1514 | input: { ...actionReference, action: "ready" }, |
| 1515 | }), |
| 1516 | ); |
| 1517 | |
| 1518 | // Checks read at 100 must not pass for a read at 300 against a newer checks read. |
| 1519 | for (const atom of readers) { |
| 1520 | expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({ |
| 1521 | isDraft: false, |
| 1522 | observedAt: 100, |
| 1523 | }); |
| 1524 | } |
| 1525 | expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([ |
| 1526 | { isDraft: false, checksState: "passing", observedAt: 100 }, |
| 1527 | ]); |
| 1528 | expect(answeredAt).toEqual([100, 100]); |
| 1529 | }), |
| 1530 | ); |
| 1531 | |
| 1532 | it.effect("re-reads an unstamped preview rather than order a reply against it", () => |
| 1533 | Effect.gen(function* () { |
| 1534 | let reads = 0; |
| 1535 | const client = actionReplyClient({ |
| 1536 | // Previews from servers before action replies carry neither update nor read time. |
| 1537 | [WS_METHODS.pullRequestsPreview]: () => |
| 1538 | Effect.sync(() => { |
| 1539 | reads++; |
| 1540 | return { |
| 1541 | ...actionReference, |
| 1542 | title: "Reopened elsewhere", |
| 1543 | url: actionReply.url, |
| 1544 | author: null, |
| 1545 | state: "open", |
| 1546 | isDraft: false, |
| 1547 | createdAt: "2026-10-27T08:00:00Z", |
| 1548 | }; |
| 1549 | }), |
| 1550 | [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "closed" }), |
| 1551 | }); |
| 1552 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1553 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1554 | const preview = atoms.preview(target); |
| 1555 | registry.mount(preview); |
| 1556 | yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true }); |
| 1557 | |
| 1558 | yield* Effect.exit( |
| 1559 | atoms.runAction.run(registry, { |
| 1560 | ...target, |
| 1561 | input: { ...actionReference, action: "close" }, |
| 1562 | }), |
| 1563 | ); |
| 1564 | |
| 1565 | expect(Option.getOrThrow(AsyncResult.value(registry.get(preview))).state).toBe("open"); |
| 1566 | expect( |
| 1567 | (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).state, |
| 1568 | ).toBe("open"); |
| 1569 | expect(reads).toBe(2); |
| 1570 | }), |
| 1571 | ); |
| 1572 | |
| 1573 | it.effect("leaves a loaded list page alone when the reply concerns none of its rows", () => |
| 1574 | Effect.gen(function* () { |
| 1575 | let pageReads = 0; |
| 1576 | const client = actionReplyClient({ |
| 1577 | [WS_METHODS.pullRequestsList]: () => |
| 1578 | Effect.sync(() => { |
| 1579 | pageReads++; |
| 1580 | return { |
| 1581 | entries: [ |
| 1582 | { |
| 1583 | ...actionReference, |
| 1584 | number: 2, |
| 1585 | state: "open", |
| 1586 | isDraft: false, |
| 1587 | updatedAt: "2026-10-27T09:00:00Z", |
| 1588 | }, |
| 1589 | ], |
| 1590 | viewers: {}, |
| 1591 | providers: [], |
| 1592 | errors: [], |
| 1593 | truncated: false, |
| 1594 | nextCursors: {}, |
| 1595 | }; |
| 1596 | }), |
| 1597 | [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }), |
| 1598 | }); |
| 1599 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1600 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1601 | const page = atoms.list({ |
| 1602 | environmentId: target.environmentId, |
| 1603 | input: { state: "open", cursors: { "github.example.com": "page-2" } }, |
| 1604 | }); |
| 1605 | const unmount = registry.mount(page); |
| 1606 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1607 | yield* Effect.promise(() => executeAtomQuery(registry, page)); |
| 1608 | |
| 1609 | yield* Effect.exit( |
| 1610 | atoms.runAction.run(registry, { |
| 1611 | ...target, |
| 1612 | input: { ...actionReference, action: "ready" }, |
| 1613 | }), |
| 1614 | ); |
| 1615 | |
| 1616 | yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true }); |
| 1617 | expect(pageReads).toBe(1); |
| 1618 | }), |
| 1619 | ); |
| 1620 | |
| 1621 | it.effect("keeps the server's post-commit read when a reopen reply lacks fields", () => |
| 1622 | Effect.gen(function* () { |
| 1623 | const refreshEvents = yield* PubSub.unbounded<number>(); |
| 1624 | let reads = 0; |
| 1625 | const detailWaiting = Latch.makeUnsafe(); |
| 1626 | const release = yield* Deferred.make<void>(); |
| 1627 | const client = actionReplyClient({ |
| 1628 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents), |
| 1629 | [WS_METHODS.pullRequestsDetail]: () => |
| 1630 | Effect.gen(function* () { |
| 1631 | reads++; |
| 1632 | if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 }; |
| 1633 | yield* Deferred.await(release); |
| 1634 | return { ...actionReference, state: "open", observedAt: 300 }; |
| 1635 | }), |
| 1636 | [WS_METHODS.pullRequestsRunAction]: () => |
| 1637 | Effect.gen(function* () { |
| 1638 | // The server announces its refresh before it replies. |
| 1639 | yield* PubSub.publish(refreshEvents, 1); |
| 1640 | yield* detailWaiting.await; |
| 1641 | return { ...actionReply, state: "open" }; |
| 1642 | }), |
| 1643 | }); |
| 1644 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1645 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1646 | const detail = atoms.detail(target); |
| 1647 | const unmount = registry.mount(detail); |
| 1648 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1649 | yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }); |
| 1650 | const stop = registry.subscribe(detail, (result) => { |
| 1651 | if (result.waiting) detailWaiting.openUnsafe(); |
| 1652 | }); |
| 1653 | yield* Effect.addFinalizer(() => Effect.sync(stop)); |
| 1654 | |
| 1655 | yield* Effect.exit( |
| 1656 | atoms.runAction.run(registry, { |
| 1657 | ...target, |
| 1658 | input: { ...actionReference, action: "reopen" }, |
| 1659 | }), |
| 1660 | ); |
| 1661 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open"); |
| 1662 | yield* Deferred.succeed(release, undefined); |
| 1663 | |
| 1664 | expect( |
| 1665 | (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt, |
| 1666 | ).toBe(300); |
| 1667 | expect(reads).toBe(2); |
| 1668 | }), |
| 1669 | ); |
| 1670 | |
| 1671 | it.effect.each([ |
| 1672 | ["a newer update", "open", "2026-10-27T10:00:01Z", 100, "open"], |
| 1673 | ["a merge", "merged", "2026-10-27T09:00:00Z", 100, "open"], |
| 1674 | ] as const)( |
| 1675 | "keeps %s when an older or reverting action reply arrives", |
| 1676 | ([, shownState, updatedAt, observedAt, replyState]) => |
| 1677 | Effect.gen(function* () { |
| 1678 | const shown = { |
| 1679 | ...actionReference, |
| 1680 | state: shownState, |
| 1681 | isDraft: true, |
| 1682 | updatedAt, |
| 1683 | observedAt, |
| 1684 | }; |
| 1685 | const client = actionReplyClient({ |
| 1686 | [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown), |
| 1687 | [WS_METHODS.pullRequestsPreview]: () => Effect.succeed(shown), |
| 1688 | [WS_METHODS.pullRequestsRunAction]: () => |
| 1689 | Effect.succeed({ ...actionReply, state: replyState }), |
| 1690 | }); |
| 1691 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1692 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 1693 | const readers = [atoms.detail(target), atoms.preview(target), atoms.previewCard(target)]; |
| 1694 | for (const reader of readers) { |
| 1695 | registry.mount(reader); |
| 1696 | yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true }); |
| 1697 | } |
| 1698 | |
| 1699 | yield* Effect.exit( |
| 1700 | atoms.runAction.run(registry, { |
| 1701 | ...target, |
| 1702 | input: { ...actionReference, action: "ready" }, |
| 1703 | }), |
| 1704 | ); |
| 1705 | for (const reader of readers) { |
| 1706 | expect(Option.getOrThrow(AsyncResult.value(registry.get(reader)))).toMatchObject({ |
| 1707 | state: shownState, |
| 1708 | isDraft: true, |
| 1709 | }); |
| 1710 | } |
| 1711 | }), |
| 1712 | ); |
| 1713 | |
| 1714 | it.effect("keeps hover previews fresh after edits and turns", () => |
| 1715 | Effect.gen(function* () { |
| 1716 | const refreshEvents = yield* PubSub.unbounded<number>(); |
| 1717 | let title = "Original title"; |
| 1718 | let reads = 0; |
| 1719 | const read = (input: unknown) => |
| 1720 | Effect.sync(() => { |
| 1721 | expect(input).toEqual(reference); |
| 1722 | reads++; |
| 1723 | return { ...reference, title }; |
| 1724 | }); |
| 1725 | const reference = { |
| 1726 | projectId: ProjectId.make("project-1"), |
| 1727 | repository: "acme/web", |
| 1728 | number: 1, |
| 1729 | host: "github.example.com", |
| 1730 | }; |
| 1731 | const client = { |
| 1732 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents), |
| 1733 | [WS_METHODS.pullRequestsPreview]: read, |
| 1734 | [WS_METHODS.pullRequestsDetail]: read, |
| 1735 | [WS_METHODS.pullRequestsUpdate]: (input: { title: string }) => |
| 1736 | Effect.sync(() => { |
| 1737 | title = input.title; |
| 1738 | }), |
| 1739 | [WS_METHODS.pullRequestsRunAction]: () => |
| 1740 | Effect.sync(() => { |
| 1741 | title = "Closed"; |
| 1742 | }), |
| 1743 | [WS_METHODS.pullRequestsInvalidate]: () => Effect.void, |
| 1744 | } as unknown as WsRpcProtocolClient; |
| 1745 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1746 | const target = { environmentId: TARGET.environmentId, input: reference }; |
| 1747 | const preview = atoms.preview(target); |
| 1748 | const unmount = registry.mount(preview); |
| 1749 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1750 | expect( |
| 1751 | (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title, |
| 1752 | ).toBe(title); |
| 1753 | yield* Effect.promise(() => executeAtomQuery(registry, preview)); |
| 1754 | expect(reads).toBe(1); |
| 1755 | const edited = yield* Effect.exit( |
| 1756 | atoms.update.run(registry, { ...target, input: { ...reference, title: "Edited" } }), |
| 1757 | ); |
| 1758 | expect(Exit.isSuccess(edited)).toBe(true); |
| 1759 | expect( |
| 1760 | (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title, |
| 1761 | ).toBe("Edited"); |
| 1762 | yield* Effect.exit( |
| 1763 | atoms.runAction.run(registry, { ...target, input: { ...reference, action: "close" } }), |
| 1764 | ); |
| 1765 | expect( |
| 1766 | (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title, |
| 1767 | ).toBe("Closed"); |
| 1768 | title = "Refreshed"; |
| 1769 | yield* Effect.exit( |
| 1770 | atoms.invalidate.run(registry, { |
| 1771 | environmentId: target.environmentId, |
| 1772 | input: { reference }, |
| 1773 | }), |
| 1774 | ); |
| 1775 | expect( |
| 1776 | (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title, |
| 1777 | ).toBe("Refreshed"); |
| 1778 | const refreshed = Latch.makeUnsafe(); |
| 1779 | const stop = registry.subscribe(preview, (result) => { |
| 1780 | if (AsyncResult.isSuccess(result) && result.value.title === "After turn") |
| 1781 | refreshed.openUnsafe(); |
| 1782 | }); |
| 1783 | yield* Effect.addFinalizer(() => Effect.sync(stop)); |
| 1784 | title = "After turn"; |
| 1785 | yield* PubSub.publish(refreshEvents, 1); |
| 1786 | yield* refreshed.await; |
| 1787 | }), |
| 1788 | ); |
| 1789 | |
| 1790 | it.effect("shares one refresh stream between independently created pull request readers", () => |
| 1791 | Effect.gen(function* () { |
| 1792 | const revision = yield* SubscriptionRef.make(0); |
| 1793 | let subscriptions = 0; |
| 1794 | let title = "Original title"; |
| 1795 | const client = { |
| 1796 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => |
| 1797 | Stream.unwrap( |
| 1798 | Effect.sync(() => { |
| 1799 | subscriptions++; |
| 1800 | return SubscriptionRef.changes(revision); |
| 1801 | }), |
| 1802 | ), |
| 1803 | [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ title, state: "open" })), |
| 1804 | [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ title, state: "open" })), |
| 1805 | } as unknown as WsRpcProtocolClient; |
| 1806 | const { runtime, atoms, registry } = yield* makeTestRuntime(client); |
| 1807 | const target = { |
| 1808 | environmentId: TARGET.environmentId, |
| 1809 | input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, |
| 1810 | }; |
| 1811 | const summary = createLinkedPullRequestSummaryAtomFamily(runtime)(target); |
| 1812 | const detail = atoms.detail(target); |
| 1813 | for (const atom of [summary, detail]) { |
| 1814 | const unmount = registry.mount(atom); |
| 1815 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1816 | expect((yield* AtomRegistry.getResult(registry, atom)).title).toBe(title); |
| 1817 | } |
| 1818 | yield* AtomRegistry.getResult( |
| 1819 | registry, |
| 1820 | atoms.refreshes({ environmentId: target.environmentId, input: {} }), |
| 1821 | ); |
| 1822 | expect(subscriptions).toBe(1); |
| 1823 | |
| 1824 | const changed = [summary, detail].map((atom) => { |
| 1825 | const ready = Latch.makeUnsafe(); |
| 1826 | const stop = registry.subscribe(atom, (result) => { |
| 1827 | if (AsyncResult.isSuccess(result) && result.value.title === "Updated title") { |
| 1828 | ready.openUnsafe(); |
| 1829 | } |
| 1830 | }); |
| 1831 | return { ready, stop }; |
| 1832 | }); |
| 1833 | yield* Effect.addFinalizer(() => Effect.sync(() => changed.forEach(({ stop }) => stop()))); |
| 1834 | title = "Updated title"; |
| 1835 | yield* SubscriptionRef.update(revision, (value) => value + 1); |
| 1836 | for (const { ready } of changed) yield* ready.await; |
| 1837 | expect(subscriptions).toBe(1); |
| 1838 | }), |
| 1839 | ); |
| 1840 | |
| 1841 | it.effect.each([ |
| 1842 | { linkedThreadRefreshes: undefined, polledReads: 1, signalledReads: 0 }, |
| 1843 | { linkedThreadRefreshes: true, polledReads: 0, signalledReads: 1 }, |
| 1844 | ])( |
| 1845 | "polls linked threads only on servers without linked-thread refreshes ($linkedThreadRefreshes)", |
| 1846 | ({ linkedThreadRefreshes, polledReads, signalledReads }) => |
| 1847 | Effect.gen(function* () { |
| 1848 | let reads = 0; |
| 1849 | const linkedThreadSignal = yield* SubscriptionRef.make(0); |
| 1850 | const client = { |
| 1851 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never, |
| 1852 | [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: () => |
| 1853 | SubscriptionRef.changes(linkedThreadSignal).pipe(Stream.filter((value) => value > 0)), |
| 1854 | [WS_METHODS.pullRequestsLinkedThreads]: () => |
| 1855 | Effect.sync(() => { |
| 1856 | reads++; |
| 1857 | return { threads: [] }; |
| 1858 | }), |
| 1859 | } as unknown as WsRpcProtocolClient; |
| 1860 | vi.useFakeTimers(); |
| 1861 | yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers())); |
| 1862 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1863 | registry.set(initialConfigs(TARGET.environmentId), { |
| 1864 | environment: { capabilities: { linkedThreadRefreshes } }, |
| 1865 | }); |
| 1866 | const linked = atoms.linkedThreads({ |
| 1867 | environmentId: TARGET.environmentId, |
| 1868 | input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, |
| 1869 | }); |
| 1870 | const unmount = registry.mount(linked); |
| 1871 | yield* Effect.addFinalizer(() => Effect.sync(unmount)); |
| 1872 | yield* AtomRegistry.getResult(registry, linked); |
| 1873 | expect(reads).toBe(1); |
| 1874 | |
| 1875 | yield* Effect.promise(() => vi.advanceTimersByTimeAsync(10_000)); |
| 1876 | expect(reads).toBe(1 + polledReads); |
| 1877 | |
| 1878 | yield* SubscriptionRef.set(linkedThreadSignal, 1); |
| 1879 | yield* Effect.promise(() => vi.advanceTimersByTimeAsync(0)); |
| 1880 | expect(reads).toBe(1 + polledReads + signalledReads); |
| 1881 | }), |
| 1882 | ); |
| 1883 | |
| 1884 | it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () => |
| 1885 | Effect.gen(function* () { |
| 1886 | const revision = yield* SubscriptionRef.make(0); |
| 1887 | let state: "open" | "closed" | "merged" = "open"; |
| 1888 | const client = { |
| 1889 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => SubscriptionRef.changes(revision), |
| 1890 | [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ state })), |
| 1891 | [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ state })), |
| 1892 | [WS_METHODS.pullRequestsList]: () => Effect.sync(() => ({ entries: [{ number: 1, state }] })), |
| 1893 | [WS_METHODS.pullRequestsRunAction]: (input: { |
| 1894 | readonly action: "close" | "reopen" | "merge"; |
| 1895 | }) => |
| 1896 | Effect.gen(function* () { |
| 1897 | state = |
| 1898 | input.action === "close" ? "closed" : input.action === "merge" ? "merged" : "open"; |
| 1899 | yield* SubscriptionRef.update(revision, (value) => value + 1); |
| 1900 | }), |
| 1901 | } as unknown as WsRpcProtocolClient; |
| 1902 | const writer = yield* makeTestRuntime(client); |
| 1903 | const reader = yield* makeTestRuntime(client); |
| 1904 | const target = { |
| 1905 | environmentId: TARGET.environmentId, |
| 1906 | input: { |
| 1907 | projectId: ProjectId.make("project-1"), |
| 1908 | host: "github.example.com", |
| 1909 | repository: "acme/web", |
| 1910 | number: 1, |
| 1911 | }, |
| 1912 | }; |
| 1913 | const detail = reader.atoms.detail(target); |
| 1914 | const summary = createLinkedPullRequestSummaryAtomFamily( |
| 1915 | reader.runtime, |
| 1916 | reader.atoms.refreshes, |
| 1917 | )(target); |
| 1918 | const list = reader.atoms.list({ |
| 1919 | environmentId: TARGET.environmentId, |
| 1920 | input: { state: "all" }, |
| 1921 | }); |
| 1922 | const unmountDetail = reader.registry.mount(detail); |
| 1923 | const unmountSummary = reader.registry.mount(summary); |
| 1924 | const unmountList = reader.registry.mount(list); |
| 1925 | yield* Effect.addFinalizer(() => |
| 1926 | Effect.sync(() => { |
| 1927 | unmountDetail(); |
| 1928 | unmountSummary(); |
| 1929 | unmountList(); |
| 1930 | }), |
| 1931 | ); |
| 1932 | expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe("open"); |
| 1933 | expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe("open"); |
| 1934 | expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe("open"); |
| 1935 | |
| 1936 | for (const [action, expected] of [ |
| 1937 | ["close", "closed"], |
| 1938 | ["reopen", "open"], |
| 1939 | ["merge", "merged"], |
| 1940 | ] as const) { |
| 1941 | const detailChanged = Latch.makeUnsafe(); |
| 1942 | const summaryChanged = Latch.makeUnsafe(); |
| 1943 | const listChanged = Latch.makeUnsafe(); |
| 1944 | const stops = [ |
| 1945 | reader.registry.subscribe(detail, (result) => { |
| 1946 | if (AsyncResult.isSuccess(result) && result.value.state === expected) { |
| 1947 | detailChanged.openUnsafe(); |
| 1948 | } |
| 1949 | }), |
| 1950 | reader.registry.subscribe(summary, (result) => { |
| 1951 | if (AsyncResult.isSuccess(result) && result.value.state === expected) { |
| 1952 | summaryChanged.openUnsafe(); |
| 1953 | } |
| 1954 | }), |
| 1955 | reader.registry.subscribe(list, (result) => { |
| 1956 | if (AsyncResult.isSuccess(result) && result.value.entries[0]?.state === expected) { |
| 1957 | listChanged.openUnsafe(); |
| 1958 | } |
| 1959 | }), |
| 1960 | ]; |
| 1961 | yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop()))); |
| 1962 | const result = yield* Effect.exit( |
| 1963 | writer.atoms.runAction.run(writer.registry, { |
| 1964 | ...target, |
| 1965 | input: { ...target.input, action }, |
| 1966 | }), |
| 1967 | ); |
| 1968 | expect(Exit.isSuccess(result)).toBe(true); |
| 1969 | yield* detailChanged.await; |
| 1970 | yield* summaryChanged.await; |
| 1971 | yield* listChanged.await; |
| 1972 | expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe(expected); |
| 1973 | expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe(expected); |
| 1974 | expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe( |
| 1975 | expected, |
| 1976 | ); |
| 1977 | stops.forEach((stop) => stop()); |
| 1978 | } |
| 1979 | }), |
| 1980 | ); |
| 1981 | |
| 1982 | it.effect("shares checks reads across reference property order", () => |
| 1983 | Effect.gen(function* () { |
| 1984 | let reads = 0; |
| 1985 | const client = { |
| 1986 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never, |
| 1987 | [WS_METHODS.pullRequestsChecks]: () => |
| 1988 | Effect.sync(() => { |
| 1989 | reads += 1; |
| 1990 | return { state: "open", checks: [], observedAt: 1_000 }; |
| 1991 | }), |
| 1992 | } as unknown as WsRpcProtocolClient; |
| 1993 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 1994 | const projectId = ProjectId.make("project-1"); |
| 1995 | const row = atoms.checks({ |
| 1996 | environmentId: TARGET.environmentId, |
| 1997 | input: { host: "github.com", repository: "acme/web", number: 1, projectId }, |
| 1998 | }); |
| 1999 | const panel = atoms.checks({ |
| 2000 | environmentId: TARGET.environmentId, |
| 2001 | input: { projectId, host: "github.com", repository: "acme/web", number: 1 }, |
| 2002 | }); |
| 2003 | yield* AtomRegistry.getResult(registry, row); |
| 2004 | yield* AtomRegistry.getResult(registry, panel); |
| 2005 | expect(reads).toBe(1); |
| 2006 | }), |
| 2007 | ); |
| 2008 | |
| 2009 | it.effect("keeps live detail reads separate from reads that allow stale data", () => |
| 2010 | Effect.gen(function* () { |
| 2011 | let reads = 0; |
| 2012 | let hostStamp: number | undefined; |
| 2013 | let hold = false; |
| 2014 | const readStarted = yield* Latch.make(); |
| 2015 | const releaseRead = yield* Latch.make(); |
| 2016 | const client = { |
| 2017 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never, |
| 2018 | [WS_METHODS.pullRequestsDetail]: (input: { allowStale?: boolean }) => |
| 2019 | Effect.gen(function* () { |
| 2020 | reads++; |
| 2021 | if (hold) { |
| 2022 | yield* readStarted.open; |
| 2023 | yield* releaseRead.await; |
| 2024 | } |
| 2025 | return { |
| 2026 | title: input.allowStale === false ? "latest checks" : "cached checks", |
| 2027 | ...(hostStamp === undefined ? {} : { observedAt: hostStamp }), |
| 2028 | }; |
| 2029 | }), |
| 2030 | } as unknown as WsRpcProtocolClient; |
| 2031 | const { atoms, registry, supervisor } = yield* makeTestRuntime(client); |
| 2032 | const target = { |
| 2033 | environmentId: TARGET.environmentId, |
| 2034 | input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, |
| 2035 | }; |
| 2036 | const cached = atoms.detail(target); |
| 2037 | const live = atoms.detail({ ...target, input: { ...target.input, allowStale: false } }); |
| 2038 | const first = yield* AtomRegistry.getResult(registry, cached); |
| 2039 | expect(first.title).toBe("cached checks"); |
| 2040 | expect(first.observedAt).toBeUndefined(); |
| 2041 | const reading = atoms.detailReadVersion(target); |
| 2042 | const firstVersion = registry.get(reading); |
| 2043 | expect(firstVersion).toBeGreaterThan(0); |
| 2044 | expect((yield* AtomRegistry.getResult(registry, live)).title).toBe("latest checks"); |
| 2045 | expect(reads).toBe(2); |
| 2046 | hold = true; |
| 2047 | registry.refresh(cached); |
| 2048 | yield* readStarted.await; |
| 2049 | expect(registry.get(reading)).toBe(firstVersion); |
| 2050 | yield* releaseRead.open; |
| 2051 | expect(yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).toBe(first); |
| 2052 | const settledVersion = registry.get(reading); |
| 2053 | expect(settledVersion).toBeGreaterThan(firstVersion); |
| 2054 | hold = false; |
| 2055 | |
| 2056 | yield* SubscriptionRef.update(supervisor.state, (state) => ({ |
| 2057 | ...state, |
| 2058 | phase: "offline" as const, |
| 2059 | })); |
| 2060 | yield* Effect.yieldNow; |
| 2061 | registry.refresh(cached); |
| 2062 | const offline = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true }); |
| 2063 | expect(offline.observedAt).toBeUndefined(); |
| 2064 | expect(registry.get(reading)).toBe(settledVersion); |
| 2065 | expect(reads).toBe(3); |
| 2066 | |
| 2067 | yield* SubscriptionRef.update(supervisor.state, (state) => ({ |
| 2068 | ...state, |
| 2069 | phase: "connected" as const, |
| 2070 | })); |
| 2071 | yield* Effect.yieldNow; |
| 2072 | registry.refresh(cached); |
| 2073 | const reread = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true }); |
| 2074 | expect(reread).toBe(first); |
| 2075 | expect(reread.observedAt).toBeUndefined(); |
| 2076 | expect(registry.get(reading)).toBeGreaterThan(settledVersion); |
| 2077 | |
| 2078 | hostStamp = 27; |
| 2079 | registry.refresh(cached); |
| 2080 | expect( |
| 2081 | (yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).observedAt, |
| 2082 | ).toBe(hostStamp); |
| 2083 | }), |
| 2084 | ); |
| 2085 | |
| 2086 | it.effect("updates cached labels after successful edits without rereading the host", () => |
| 2087 | Effect.gen(function* () { |
| 2088 | let detailReads = 0; |
| 2089 | let candidateReads = 0; |
| 2090 | let refuse = false; |
| 2091 | let failDetail = false; |
| 2092 | const existing = { name: "existing", color: "111111" }; |
| 2093 | const addedLabel = { name: "new", color: "abcdef" }; |
| 2094 | const detailRefreshStarted = yield* Latch.make(); |
| 2095 | const releaseDetailRefresh = yield* Latch.make(); |
| 2096 | const client = { |
| 2097 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never, |
| 2098 | [WS_METHODS.pullRequestsDetail]: () => |
| 2099 | Effect.gen(function* () { |
| 2100 | detailReads++; |
| 2101 | if (failDetail) { |
| 2102 | yield* detailRefreshStarted.open; |
| 2103 | yield* releaseDetailRefresh.await; |
| 2104 | return yield* new MutationRefused(); |
| 2105 | } |
| 2106 | return { title: "keep this title", labels: [existing] }; |
| 2107 | }), |
| 2108 | [WS_METHODS.pullRequestsLabelCandidates]: () => |
| 2109 | Effect.sync(() => { |
| 2110 | candidateReads++; |
| 2111 | return { |
| 2112 | candidates: [ |
| 2113 | { ...existing, description: null, isApplied: true }, |
| 2114 | { ...addedLabel, description: "description", isApplied: false }, |
| 2115 | ], |
| 2116 | truncated: false, |
| 2117 | }; |
| 2118 | }), |
| 2119 | [WS_METHODS.pullRequestsSetLabels]: () => |
| 2120 | refuse ? Effect.fail(new MutationRefused()) : Effect.void, |
| 2121 | } as unknown as WsRpcProtocolClient; |
| 2122 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 2123 | const target = { |
| 2124 | environmentId: TARGET.environmentId, |
| 2125 | input: { |
| 2126 | projectId: ProjectId.make("project-1"), |
| 2127 | repository: "acme/web", |
| 2128 | number: 1, |
| 2129 | host: "github.example.com", |
| 2130 | }, |
| 2131 | }; |
| 2132 | const detail = atoms.detail({ ...target, input: { ...target.input, allowStale: false } }); |
| 2133 | const candidates = atoms.labelCandidates(target); |
| 2134 | registry.mount(detail); |
| 2135 | const unmountCandidates = registry.mount(candidates); |
| 2136 | yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }); |
| 2137 | yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true }); |
| 2138 | |
| 2139 | const added = yield* Effect.exit( |
| 2140 | atoms.setLabels.run(registry, { |
| 2141 | ...target, |
| 2142 | input: { |
| 2143 | host: target.input.host, |
| 2144 | projectId: target.input.projectId, |
| 2145 | repository: target.input.repository, |
| 2146 | number: target.input.number, |
| 2147 | labels: ["new"], |
| 2148 | applied: true, |
| 2149 | }, |
| 2150 | }), |
| 2151 | ); |
| 2152 | expect(Exit.isSuccess(added)).toBe(true); |
| 2153 | expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({ |
| 2154 | title: "keep this title", |
| 2155 | labels: [existing, addedLabel], |
| 2156 | }); |
| 2157 | unmountCandidates(); |
| 2158 | registry.mount(atoms.labelCandidates(target)); |
| 2159 | expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({ |
| 2160 | ...addedLabel, |
| 2161 | description: "description", |
| 2162 | isApplied: true, |
| 2163 | }); |
| 2164 | |
| 2165 | for (const name of ["existing", "new"]) { |
| 2166 | refuse = name === "new"; |
| 2167 | const result = yield* Effect.exit( |
| 2168 | atoms.setLabels.run(registry, { |
| 2169 | ...target, |
| 2170 | input: { ...target.input, labels: [name], applied: false }, |
| 2171 | }), |
| 2172 | ); |
| 2173 | expect(result._tag).toBe(refuse ? "Failure" : "Success"); |
| 2174 | expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]); |
| 2175 | expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([ |
| 2176 | { name: "existing", isApplied: false }, |
| 2177 | { name: "new", isApplied: true }, |
| 2178 | ]); |
| 2179 | } |
| 2180 | expect(detailReads).toBe(1); |
| 2181 | expect(candidateReads).toBe(1); |
| 2182 | |
| 2183 | failDetail = true; |
| 2184 | registry.refresh(detail); |
| 2185 | yield* detailRefreshStarted.await; |
| 2186 | expect(registry.get(detail).waiting).toBe(true); |
| 2187 | expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]); |
| 2188 | yield* releaseDetailRefresh.open; |
| 2189 | yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })); |
| 2190 | expect(AsyncResult.isFailure(registry.get(detail))).toBe(true); |
| 2191 | expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]); |
| 2192 | failDetail = false; |
| 2193 | registry.refresh(detail); |
| 2194 | expect( |
| 2195 | (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels, |
| 2196 | ).toEqual([existing]); |
| 2197 | expect(detailReads).toBe(3); |
| 2198 | }), |
| 2199 | ); |
| 2200 | |
| 2201 | vi.mock("./session.ts", () => ({ |
| 2202 | createEnvironmentSessionAtoms: () => ({ |
| 2203 | sessionStateAtom: grantedSessions, |
| 2204 | initialConfigValueAtom: initialConfigs, |
| 2205 | }), |
| 2206 | })); |
| 2207 | const initialConfigs = Atom.family((_id: EnvironmentId) => Atom.make<unknown>(null)); |
| 2208 | const grantedSessions = Atom.family((_id: EnvironmentId) => |
| 2209 | Atom.make<AsyncResult.AsyncResult<AuthSessionState>>( |
| 2210 | AsyncResult.success({ |
| 2211 | authenticated: true, |
| 2212 | auth: { |
| 2213 | policy: "remote-reachable" as const, |
| 2214 | bootstrapMethods: [], |
| 2215 | sessionMethods: [], |
| 2216 | sessionCookieName: "test", |
| 2217 | }, |
| 2218 | scopes: [AuthSourceControlWriteScope], |
| 2219 | }), |
| 2220 | ), |
| 2221 | ); |
| 2222 | |
| 2223 | it.effect("denies a routed write when only the origin has source-control permission", () => |
| 2224 | Effect.gen(function* () { |
| 2225 | let writes = 0; |
| 2226 | const identity = { host: "github.com", provider: "github", viewer: "test", accountId: "123" }; |
| 2227 | const client = { |
| 2228 | [WS_METHODS.pullRequestsRouting]: () => Effect.succeed(identity), |
| 2229 | [WS_METHODS.pullRequestsRoutingIdentity]: () => Effect.succeed(identity), |
| 2230 | [WS_METHODS.pullRequestsRunAction]: () => |
| 2231 | Effect.sync(() => { |
| 2232 | writes++; |
| 2233 | }), |
| 2234 | } as unknown as WsRpcProtocolClient; |
| 2235 | const fixture = yield* makeTestRuntime(client, client); |
| 2236 | const local = EnvironmentId.make("local-environment"); |
| 2237 | const stop = fixture.registry.mount(grantedSessions(local)); |
| 2238 | yield* Effect.addFinalizer(() => Effect.sync(stop)); |
| 2239 | fixture.registry.set( |
| 2240 | grantedSessions(local), |
| 2241 | AsyncResult.success({ |
| 2242 | authenticated: true, |
| 2243 | scopes: [], |
| 2244 | auth: { |
| 2245 | policy: "remote-reachable" as const, |
| 2246 | bootstrapMethods: [], |
| 2247 | sessionMethods: [], |
| 2248 | sessionCookieName: "test", |
| 2249 | }, |
| 2250 | }), |
| 2251 | ); |
| 2252 | const error = yield* createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, { |
| 2253 | projectId: ProjectId.make("project"), |
| 2254 | repository: "acme/repo", |
| 2255 | number: 1, |
| 2256 | action: "merge", |
| 2257 | }).pipe( |
| 2258 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, fixture.environmentRegistry), |
| 2259 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, fixture.supervisor), |
| 2260 | Effect.provideService(PullRequestRoutingPermissions, trustedRouting), |
| 2261 | Effect.provideService(RpcPermissionGuard, { |
| 2262 | authorize: (id, method, input) => |
| 2263 | createCommandPermissions(fixture.runtime, method).authorize(fixture.registry, id, input), |
| 2264 | }), |
| 2265 | Effect.flip, |
| 2266 | ); |
| 2267 | expect(error._tag).toBe("EnvironmentAuthorizationError"); |
| 2268 | expect(writes).toBe(0); |
| 2269 | }), |
| 2270 | ); |
| 2271 | |
| 2272 | it.effect("publishes the accepted guide run before the follow-up read finishes", () => |
| 2273 | Effect.gen(function* () { |
| 2274 | const accepted = { |
| 2275 | guide: null, |
| 2276 | currentHeadSha: "head", |
| 2277 | run: { _tag: "Running" as const, headSha: "head", startedAt: "2026-10-11T00:00:00.000Z" }, |
| 2278 | }; |
| 2279 | let reads = 0; |
| 2280 | const refreshStarted = yield* Latch.make(); |
| 2281 | const client = { |
| 2282 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never, |
| 2283 | [WS_METHODS.pullRequestsReviewGuide]: () => |
| 2284 | Effect.gen(function* () { |
| 2285 | if (++reads > 1) { |
| 2286 | yield* refreshStarted.open; |
| 2287 | return yield* Effect.never; |
| 2288 | } |
| 2289 | return { guide: null, run: null, currentHeadSha: "head" }; |
| 2290 | }), |
| 2291 | [WS_METHODS.pullRequestsGenerateReviewGuide]: () => Effect.succeed(accepted), |
| 2292 | } as unknown as WsRpcProtocolClient; |
| 2293 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 2294 | const target = { |
| 2295 | environmentId: TARGET.environmentId, |
| 2296 | input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }, |
| 2297 | }; |
| 2298 | registry.update( |
| 2299 | grantedSessions(target.environmentId), |
| 2300 | AsyncResult.map((session) => ({ |
| 2301 | ...session, |
| 2302 | scopes: [...(session.scopes ?? []), AuthOrchestrationOperateScope], |
| 2303 | })), |
| 2304 | ); |
| 2305 | const query = atoms.reviewGuide(target); |
| 2306 | registry.mount(query); |
| 2307 | yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true }); |
| 2308 | const result = yield* Effect.exit(atoms.generateReviewGuide.run(registry, target)); |
| 2309 | expect(result._tag).toBe("Success"); |
| 2310 | yield* refreshStarted.await; |
| 2311 | expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted); |
| 2312 | }), |
| 2313 | ); |
| 2314 | |
| 2315 | const listResult = (entries: ReadonlyArray<object>) => ({ |
| 2316 | entries, |
| 2317 | viewers: {}, |
| 2318 | providers: [], |
| 2319 | errors: [], |
| 2320 | truncated: false, |
| 2321 | nextCursors: {}, |
| 2322 | }); |
| 2323 | |
| 2324 | it.effect.each([ |
| 2325 | ["close", { state: "closed" }, "open"], |
| 2326 | ["reopen", { state: "open" }, "closed"], |
| 2327 | ["ready", { isDraft: false }, "open"], |
| 2328 | ["draft", { isDraft: true }, "open"], |
| 2329 | ["enable-auto-merge", { autoMergeEnabled: true }, "open"], |
| 2330 | ["disable-auto-merge", { autoMergeEnabled: false }, "open"], |
| 2331 | ] as const)("shows %s in loaded readers before the host replies", ([action, shown, from]) => |
| 2332 | Effect.scoped( |
| 2333 | Effect.gen(function* () { |
| 2334 | let reads = 0; |
| 2335 | const sent = yield* Deferred.make<void>(); |
| 2336 | const release = yield* Deferred.make<void>(); |
| 2337 | const before = { |
| 2338 | ...actionReference, |
| 2339 | provider: "github", |
| 2340 | title: "Ship it", |
| 2341 | url: actionReply.url, |
| 2342 | author: null, |
| 2343 | headBranch: "feature", |
| 2344 | baseBranch: "main", |
| 2345 | state: from, |
| 2346 | isDraft: action === "ready", |
| 2347 | autoMergeEnabled: action === "disable-auto-merge", |
| 2348 | createdAt: "2026-10-27T08:00:00Z", |
| 2349 | updatedAt: "2026-10-27T09:00:00Z", |
| 2350 | observedAt: 100, |
| 2351 | }; |
| 2352 | const read = () => |
| 2353 | Effect.sync(() => { |
| 2354 | reads++; |
| 2355 | return before; |
| 2356 | }); |
| 2357 | const client = actionReplyClient({ |
| 2358 | [WS_METHODS.pullRequestsDetail]: read, |
| 2359 | [WS_METHODS.pullRequestsPreview]: read, |
| 2360 | [WS_METHODS.pullRequestsSummary]: read, |
| 2361 | [WS_METHODS.pullRequestsList]: () => |
| 2362 | Effect.sync(() => { |
| 2363 | reads++; |
| 2364 | return listResult([before]); |
| 2365 | }), |
| 2366 | [WS_METHODS.pullRequestsRunAction]: () => |
| 2367 | Effect.gen(function* () { |
| 2368 | yield* Deferred.succeed(sent, undefined); |
| 2369 | yield* Deferred.await(release); |
| 2370 | return { ...before, ...shown, updatedAt: "2026-10-27T10:00:00Z", observedAt: 200 }; |
| 2371 | }), |
| 2372 | }); |
| 2373 | const { atoms, registry, runtime } = yield* makeTestRuntime(client); |
| 2374 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2375 | const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [ |
| 2376 | atoms.detail(target), |
| 2377 | atoms.preview(target), |
| 2378 | createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target), |
| 2379 | ]; |
| 2380 | const list = atoms.list({ environmentId: target.environmentId, input: { state: from } }); |
| 2381 | for (const atom of [...readers, list]) { |
| 2382 | registry.mount(atom); |
| 2383 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 2384 | } |
| 2385 | reads = 0; |
| 2386 | |
| 2387 | const acting = yield* Effect.exit( |
| 2388 | atoms.runAction.run(registry, { ...target, input: { ...actionReference, action } }), |
| 2389 | ).pipe(Effect.forkScoped); |
| 2390 | yield* Deferred.await(sent); |
| 2391 | |
| 2392 | for (const atom of readers.slice(0, action.includes("auto-merge") ? 1 : readers.length)) { |
| 2393 | expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject(shown); |
| 2394 | } |
| 2395 | const rows = Option.getOrThrow(AsyncResult.value(registry.get(list))).entries; |
| 2396 | if ("state" in shown) expect(rows).toEqual([]); |
| 2397 | else if ("isDraft" in shown) expect(rows).toMatchObject([shown]); |
| 2398 | else expect(rows).toHaveLength(1); |
| 2399 | yield* Deferred.succeed(release, undefined); |
| 2400 | yield* Fiber.join(acting); |
| 2401 | expect(Option.getOrThrow(AsyncResult.value(registry.get(readers[0]!)))).toMatchObject({ |
| 2402 | ...shown, |
| 2403 | updatedAt: "2026-10-27T10:00:00Z", |
| 2404 | }); |
| 2405 | // Only a reopen re-reads, for the branch data and permissions its reply lacks. |
| 2406 | expect(reads).toBe(action === "reopen" ? 1 : 0); |
| 2407 | }), |
| 2408 | ), |
| 2409 | ); |
| 2410 | |
| 2411 | it.effect("puts readers back when the host refuses an action, and saves nothing it guessed", () => |
| 2412 | Effect.scoped( |
| 2413 | Effect.gen(function* () { |
| 2414 | const sent = yield* Deferred.make<void>(); |
| 2415 | const release = yield* Deferred.make<void>(); |
| 2416 | const open = { ...actionReference, state: "open", isDraft: false, observedAt: 100 }; |
| 2417 | const saved = new Map<string, string>(); |
| 2418 | const client = actionReplyClient({ |
| 2419 | [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(open), |
| 2420 | [WS_METHODS.pullRequestsList]: () => Effect.succeed(listResult([open])), |
| 2421 | [WS_METHODS.pullRequestsRunAction]: () => |
| 2422 | Effect.gen(function* () { |
| 2423 | yield* Deferred.succeed(sent, undefined); |
| 2424 | yield* Deferred.await(release); |
| 2425 | return yield* new PullRequestOperationError({ |
| 2426 | operation: "runAction", |
| 2427 | detail: "You cannot close this pull request.", |
| 2428 | }); |
| 2429 | }), |
| 2430 | }); |
| 2431 | const { atoms, registry } = yield* makeTestRuntime( |
| 2432 | client, |
| 2433 | undefined, |
| 2434 | false, |
| 2435 | {}, |
| 2436 | { |
| 2437 | load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))), |
| 2438 | save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)), |
| 2439 | }, |
| 2440 | ); |
| 2441 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2442 | const detail = atoms.detail(target); |
| 2443 | const list = atoms.list({ environmentId: target.environmentId, input: { state: "open" } }); |
| 2444 | const loaded: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [ |
| 2445 | detail, |
| 2446 | list, |
| 2447 | ]; |
| 2448 | for (const atom of loaded) { |
| 2449 | registry.mount(atom); |
| 2450 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 2451 | } |
| 2452 | |
| 2453 | const acting = yield* Effect.exit( |
| 2454 | atoms.runAction.run(registry, { |
| 2455 | ...target, |
| 2456 | input: { ...actionReference, action: "close" }, |
| 2457 | }), |
| 2458 | ).pipe(Effect.forkScoped); |
| 2459 | yield* Deferred.await(sent); |
| 2460 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("closed"); |
| 2461 | const held = Option.getOrThrow( |
| 2462 | AsyncResult.value(registry.get(pullRequestHostAnswer(list))), |
| 2463 | ).entries; |
| 2464 | const shownHeld = () => |
| 2465 | editHeldPullRequestListEntries({ state: "open" }, held, () => |
| 2466 | registry.get(pullRequestPendingEditsFor(target.environmentId, actionReference)), |
| 2467 | ); |
| 2468 | expect(shownHeld()).toEqual([]); |
| 2469 | yield* Deferred.succeed(release, undefined); |
| 2470 | expect((yield* Fiber.join(acting))._tag).toBe("Failure"); |
| 2471 | |
| 2472 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open"); |
| 2473 | expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([ |
| 2474 | { state: "open" }, |
| 2475 | ]); |
| 2476 | expect(shownHeld()).toMatchObject([{ state: "open" }]); |
| 2477 | expect([...saved.values()].some((payload) => payload.includes('"closed"'))).toBe(false); |
| 2478 | }), |
| 2479 | ), |
| 2480 | ); |
| 2481 | |
| 2482 | it.effect( |
| 2483 | "keeps an accepted change on screen until the re-read when the reply has no summary", |
| 2484 | () => |
| 2485 | Effect.scoped( |
| 2486 | Effect.gen(function* () { |
| 2487 | let state = "open"; |
| 2488 | let reads = 0; |
| 2489 | const rereadStarted = yield* Deferred.make<void>(); |
| 2490 | const releaseReread = yield* Deferred.make<void>(); |
| 2491 | const client = actionReplyClient({ |
| 2492 | [WS_METHODS.pullRequestsDetail]: () => |
| 2493 | Effect.gen(function* () { |
| 2494 | reads++; |
| 2495 | const answer = { ...actionReference, state, observedAt: reads }; |
| 2496 | if (reads === 2) { |
| 2497 | yield* Deferred.succeed(rereadStarted, undefined); |
| 2498 | yield* Deferred.await(releaseReread); |
| 2499 | } |
| 2500 | return answer; |
| 2501 | }), |
| 2502 | [WS_METHODS.pullRequestsRunAction]: () => |
| 2503 | Effect.sync(() => { |
| 2504 | state = "closed"; |
| 2505 | return undefined; |
| 2506 | }), |
| 2507 | }); |
| 2508 | let held = [actionListEntry] as ReadonlyArray<PullRequestListEntry>; |
| 2509 | const { atoms, registry } = yield* makeTestRuntime(client, undefined, false, { |
| 2510 | acceptedEdit: (_target, edit) => |
| 2511 | Effect.sync(() => { |
| 2512 | held = editHeldPullRequestListEntries({ state: "all" }, held, () => [edit]); |
| 2513 | }), |
| 2514 | }); |
| 2515 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2516 | const retained = heldPullRequestListEntriesAtom( |
| 2517 | target.environmentId, |
| 2518 | { state: "all" }, |
| 2519 | held, |
| 2520 | ); |
| 2521 | registry.mount(retained); |
| 2522 | const detail = atoms.detail(target); |
| 2523 | registry.mount(detail); |
| 2524 | yield* Effect.promise(() => executeAtomQuery(registry, detail)); |
| 2525 | |
| 2526 | yield* Effect.exit( |
| 2527 | atoms.runAction.run(registry, { |
| 2528 | ...target, |
| 2529 | input: { ...actionReference, action: "close" }, |
| 2530 | }), |
| 2531 | ); |
| 2532 | yield* Deferred.await(rereadStarted); |
| 2533 | |
| 2534 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("closed"); |
| 2535 | expect(held[0]?.state).toBe("closed"); |
| 2536 | expect(Option.getOrThrow(AsyncResult.value(registry.get(retained)))[0]?.state).toBe( |
| 2537 | "closed", |
| 2538 | ); |
| 2539 | yield* Deferred.succeed(releaseReread, undefined); |
| 2540 | expect( |
| 2541 | (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt, |
| 2542 | ).toBe(2); |
| 2543 | }), |
| 2544 | ), |
| 2545 | ); |
| 2546 | |
| 2547 | it.effect.each([ |
| 2548 | ["with", { ...actionReply, state: "closed" as const }], |
| 2549 | ["without", undefined], |
| 2550 | ] as const)("shows a queued close before the action ahead of it answers, %s a reply", ([, reply]) => |
| 2551 | Effect.scoped( |
| 2552 | Effect.gen(function* () { |
| 2553 | const firstSent = yield* Deferred.make<void>(); |
| 2554 | const release = yield* Deferred.make<void>(); |
| 2555 | const releaseReopen = yield* Deferred.make<void>(); |
| 2556 | const rows = [1, 2].map((number) => ({ |
| 2557 | ...actionReference, |
| 2558 | number, |
| 2559 | state: "open", |
| 2560 | isDraft: false, |
| 2561 | updatedAt: `2026-10-27T0${number}:00:00Z`, |
| 2562 | })); |
| 2563 | const client = actionReplyClient({ |
| 2564 | [WS_METHODS.pullRequestsList]: () => Effect.succeed(listResult(rows)), |
| 2565 | [WS_METHODS.pullRequestsRunAction]: (input: { |
| 2566 | readonly number: number; |
| 2567 | readonly action: string; |
| 2568 | }) => |
| 2569 | Effect.gen(function* () { |
| 2570 | if (input.action === "reopen") { |
| 2571 | yield* Deferred.await(releaseReopen); |
| 2572 | return yield* new PullRequestOperationError({ |
| 2573 | operation: "runAction", |
| 2574 | detail: "reopen refused", |
| 2575 | }); |
| 2576 | } |
| 2577 | if (input.number === 1) { |
| 2578 | yield* Deferred.succeed(firstSent, undefined); |
| 2579 | yield* Deferred.await(release); |
| 2580 | return reply; |
| 2581 | } |
| 2582 | return undefined; |
| 2583 | }), |
| 2584 | }); |
| 2585 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 2586 | const list = atoms.list({ environmentId: TARGET.environmentId, input: { state: "open" } }); |
| 2587 | registry.mount(list); |
| 2588 | yield* Effect.promise(() => executeAtomQuery(registry, list)); |
| 2589 | |
| 2590 | const closes = yield* Effect.forEach([1, 2], (number) => |
| 2591 | Effect.forkChild( |
| 2592 | Effect.exit( |
| 2593 | atoms.runAction.run(registry, { |
| 2594 | environmentId: TARGET.environmentId, |
| 2595 | input: { ...actionReference, number, action: "close" }, |
| 2596 | }), |
| 2597 | ), |
| 2598 | { startImmediately: true }, |
| 2599 | ), |
| 2600 | ); |
| 2601 | yield* Deferred.await(firstSent); |
| 2602 | |
| 2603 | expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]); |
| 2604 | |
| 2605 | const reopen = yield* Effect.forkChild( |
| 2606 | Effect.exit( |
| 2607 | atoms.runAction.run(registry, { |
| 2608 | environmentId: TARGET.environmentId, |
| 2609 | input: { ...actionReference, number: 1, action: "reopen" }, |
| 2610 | }), |
| 2611 | ), |
| 2612 | { startImmediately: true }, |
| 2613 | ); |
| 2614 | expect( |
| 2615 | Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number), |
| 2616 | ).toEqual([1]); |
| 2617 | yield* Deferred.succeed(release, undefined); |
| 2618 | yield* Fiber.joinAll(closes); |
| 2619 | expect( |
| 2620 | Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number), |
| 2621 | ).toEqual([1]); |
| 2622 | yield* Deferred.succeed(releaseReopen, undefined); |
| 2623 | expect((yield* Fiber.join(reopen))._tag).toBe("Failure"); |
| 2624 | expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]); |
| 2625 | }), |
| 2626 | ), |
| 2627 | ); |
| 2628 | |
| 2629 | it.effect("leaves a merge as it is until the host says what it did", () => |
| 2630 | Effect.scoped( |
| 2631 | Effect.gen(function* () { |
| 2632 | const sent = yield* Deferred.make<void>(); |
| 2633 | const release = yield* Deferred.make<void>(); |
| 2634 | const client = actionReplyClient({ |
| 2635 | [WS_METHODS.pullRequestsDetail]: () => |
| 2636 | Effect.succeed({ ...actionReference, state: "open", observedAt: 100 }), |
| 2637 | [WS_METHODS.pullRequestsRunAction]: () => |
| 2638 | Effect.gen(function* () { |
| 2639 | yield* Deferred.succeed(sent, undefined); |
| 2640 | yield* Deferred.await(release); |
| 2641 | // A merge queue takes the merge and merges later. |
| 2642 | return { ...actionReply, state: "open", autoMergeEnabled: true }; |
| 2643 | }), |
| 2644 | }); |
| 2645 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 2646 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2647 | const detail = atoms.detail(target); |
| 2648 | registry.mount(detail); |
| 2649 | yield* Effect.promise(() => executeAtomQuery(registry, detail)); |
| 2650 | |
| 2651 | const acting = yield* Effect.exit( |
| 2652 | atoms.runAction.run(registry, { |
| 2653 | ...target, |
| 2654 | input: { ...actionReference, action: "merge" }, |
| 2655 | }), |
| 2656 | ).pipe(Effect.forkScoped); |
| 2657 | yield* Deferred.await(sent); |
| 2658 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open"); |
| 2659 | yield* Deferred.succeed(release, undefined); |
| 2660 | yield* Fiber.join(acting); |
| 2661 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail)))).toMatchObject({ |
| 2662 | state: "open", |
| 2663 | autoMergeEnabled: true, |
| 2664 | }); |
| 2665 | }), |
| 2666 | ), |
| 2667 | ); |
| 2668 | |
| 2669 | it.effect.each(["accepted", "refused"] as const)( |
| 2670 | "shows a title edit at once and keeps it only when the host takes it (%s)", |
| 2671 | (outcome) => |
| 2672 | Effect.scoped( |
| 2673 | Effect.gen(function* () { |
| 2674 | let title = "Original"; |
| 2675 | let reads = 0; |
| 2676 | const sent = yield* Deferred.make<void>(); |
| 2677 | const release = yield* Deferred.make<void>(); |
| 2678 | const read = () => |
| 2679 | Effect.sync(() => { |
| 2680 | reads++; |
| 2681 | return { ...actionReference, state: "open", title, observedAt: reads }; |
| 2682 | }); |
| 2683 | const client = actionReplyClient({ |
| 2684 | [WS_METHODS.pullRequestsDetail]: read, |
| 2685 | [WS_METHODS.pullRequestsPreview]: read, |
| 2686 | [WS_METHODS.pullRequestsList]: () => |
| 2687 | Effect.sync(() => { |
| 2688 | reads++; |
| 2689 | return listResult([ |
| 2690 | { ...actionReference, state: "open", title, updatedAt: actionReply.updatedAt }, |
| 2691 | ]); |
| 2692 | }), |
| 2693 | [WS_METHODS.pullRequestsUpdate]: (input: { readonly title: string }) => |
| 2694 | Effect.gen(function* () { |
| 2695 | yield* Deferred.succeed(sent, undefined); |
| 2696 | yield* Deferred.await(release); |
| 2697 | if (outcome === "refused") return yield* new MutationRefused(); |
| 2698 | title = input.title; |
| 2699 | }), |
| 2700 | }); |
| 2701 | let held: ReadonlyArray<PullRequestListEntry> = []; |
| 2702 | let observedTitle = "Original"; |
| 2703 | const handlers = { |
| 2704 | detail: (_target: unknown, detail: { readonly title: string }) => |
| 2705 | Effect.sync(() => { |
| 2706 | observedTitle = detail.title; |
| 2707 | }), |
| 2708 | acceptedEdit: ( |
| 2709 | _target: unknown, |
| 2710 | edit: Parameters<typeof applyPullRequestSummaryEdits>[2][number], |
| 2711 | ) => |
| 2712 | Effect.sync(() => { |
| 2713 | observedTitle = edit.title ?? observedTitle; |
| 2714 | held = editHeldPullRequestListEntries({ state: "open" }, held, () => [edit]); |
| 2715 | }), |
| 2716 | }; |
| 2717 | const { atoms, registry } = yield* makeTestRuntime(client, undefined, false, handlers); |
| 2718 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2719 | const detail = atoms.detail(target); |
| 2720 | const preview = atoms.preview(target); |
| 2721 | const list = atoms.list({ environmentId: target.environmentId, input: { state: "open" } }); |
| 2722 | const loaded: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [ |
| 2723 | detail, |
| 2724 | preview, |
| 2725 | list, |
| 2726 | ]; |
| 2727 | for (const atom of loaded) { |
| 2728 | registry.mount(atom); |
| 2729 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 2730 | } |
| 2731 | held = Option.getOrThrow( |
| 2732 | AsyncResult.value(registry.get(pullRequestHostAnswer(list))), |
| 2733 | ).entries; |
| 2734 | const retained = heldPullRequestListEntriesAtom( |
| 2735 | target.environmentId, |
| 2736 | { state: "open" }, |
| 2737 | held, |
| 2738 | ); |
| 2739 | registry.mount(retained); |
| 2740 | const titles = () => [ |
| 2741 | Option.getOrThrow(AsyncResult.value(registry.get(detail))).title, |
| 2742 | Option.getOrThrow(AsyncResult.value(registry.get(preview))).title, |
| 2743 | Option.getOrThrow(AsyncResult.value(registry.get(list))).entries[0]?.title, |
| 2744 | applyPullRequestSummaryEdits( |
| 2745 | actionReference, |
| 2746 | { |
| 2747 | ...actionReply, |
| 2748 | provider: SourceControlProviderKind.make("github"), |
| 2749 | title: observedTitle, |
| 2750 | }, |
| 2751 | registry.get(pullRequestPendingEditsAtom(target.environmentId)), |
| 2752 | )?.title, |
| 2753 | ]; |
| 2754 | |
| 2755 | const editing = yield* Effect.exit( |
| 2756 | atoms.update.run(registry, { ...target, input: { ...actionReference, title: "Edited" } }), |
| 2757 | ).pipe(Effect.forkScoped); |
| 2758 | yield* Deferred.await(sent); |
| 2759 | expect(titles()).toEqual(["Edited", "Edited", "Edited", "Edited"]); |
| 2760 | yield* Deferred.succeed(release, undefined); |
| 2761 | yield* Fiber.join(editing); |
| 2762 | |
| 2763 | expect(titles()).toEqual( |
| 2764 | outcome === "refused" |
| 2765 | ? ["Original", "Original", "Original", "Original"] |
| 2766 | : ["Edited", "Edited", "Edited", "Edited"], |
| 2767 | ); |
| 2768 | expect(observedTitle).toBe(outcome === "refused" ? "Original" : "Edited"); |
| 2769 | expect(held[0]?.title).toBe(outcome === "refused" ? "Original" : "Edited"); |
| 2770 | expect(Option.getOrThrow(AsyncResult.value(registry.get(retained)))[0]?.title).toBe( |
| 2771 | outcome === "refused" ? "Original" : "Edited", |
| 2772 | ); |
| 2773 | // The edit is known, so no reader asks the host again. |
| 2774 | expect(reads).toBe(3); |
| 2775 | }), |
| 2776 | ), |
| 2777 | ); |
| 2778 | |
| 2779 | it.effect.each(["accepted", "refused"] as const)( |
| 2780 | "keeps a label change on retained rows only when the host takes it (%s)", |
| 2781 | (outcome) => |
| 2782 | Effect.scoped( |
| 2783 | Effect.gen(function* () { |
| 2784 | const sent = yield* Deferred.make<void>(); |
| 2785 | const release = yield* Deferred.make<void>(); |
| 2786 | const existing = { name: "existing", color: "111111" }; |
| 2787 | const added = { name: "new", color: "abcdef" }; |
| 2788 | const client = actionReplyClient({ |
| 2789 | [WS_METHODS.pullRequestsDetail]: () => |
| 2790 | Effect.succeed({ ...actionReference, state: "open", labels: [existing] }), |
| 2791 | [WS_METHODS.pullRequestsLabelCandidates]: () => |
| 2792 | Effect.succeed({ |
| 2793 | candidates: [ |
| 2794 | { ...existing, description: null, isApplied: true }, |
| 2795 | { ...added, description: null, isApplied: false }, |
| 2796 | ], |
| 2797 | truncated: false, |
| 2798 | }), |
| 2799 | [WS_METHODS.pullRequestsSetLabels]: () => |
| 2800 | Effect.gen(function* () { |
| 2801 | yield* Deferred.succeed(sent, undefined); |
| 2802 | yield* Deferred.await(release); |
| 2803 | if (outcome === "refused") return yield* new MutationRefused(); |
| 2804 | }), |
| 2805 | }); |
| 2806 | let held: ReadonlyArray<PullRequestListEntry> = [ |
| 2807 | { ...actionListEntry, labels: [existing] }, |
| 2808 | ]; |
| 2809 | const { atoms, registry } = yield* makeTestRuntime(client, undefined, false, { |
| 2810 | acceptedEdit: (_target, edit) => |
| 2811 | Effect.sync(() => { |
| 2812 | held = editHeldPullRequestListEntries({ state: "open" }, held, () => [edit]); |
| 2813 | }), |
| 2814 | }); |
| 2815 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2816 | const retained = heldPullRequestListEntriesAtom( |
| 2817 | target.environmentId, |
| 2818 | { state: "open" }, |
| 2819 | held, |
| 2820 | ); |
| 2821 | registry.mount(retained); |
| 2822 | const detail = atoms.detail(target); |
| 2823 | const candidates = atoms.labelCandidates(target); |
| 2824 | const loaded: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [ |
| 2825 | detail, |
| 2826 | candidates, |
| 2827 | ]; |
| 2828 | for (const atom of loaded) { |
| 2829 | registry.mount(atom); |
| 2830 | yield* Effect.promise(() => executeAtomQuery(registry, atom)); |
| 2831 | } |
| 2832 | |
| 2833 | const labelling = yield* Effect.exit( |
| 2834 | atoms.setLabels.run(registry, { |
| 2835 | ...target, |
| 2836 | input: { ...actionReference, labels: ["new"], applied: true }, |
| 2837 | }), |
| 2838 | ).pipe(Effect.forkScoped); |
| 2839 | yield* Deferred.await(sent); |
| 2840 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([ |
| 2841 | existing, |
| 2842 | added, |
| 2843 | ]); |
| 2844 | expect( |
| 2845 | Option.getOrThrow(AsyncResult.value(registry.get(candidates))).candidates.map( |
| 2846 | (candidate) => candidate.isApplied, |
| 2847 | ), |
| 2848 | ).toEqual([true, true]); |
| 2849 | yield* Deferred.succeed(release, undefined); |
| 2850 | expect((yield* Fiber.join(labelling))._tag).toBe( |
| 2851 | outcome === "refused" ? "Failure" : "Success", |
| 2852 | ); |
| 2853 | expect(held[0]?.labels).toEqual(outcome === "refused" ? [existing] : [existing, added]); |
| 2854 | expect(Option.getOrThrow(AsyncResult.value(registry.get(retained)))[0]?.labels).toEqual( |
| 2855 | outcome === "refused" ? [existing] : [existing, added], |
| 2856 | ); |
| 2857 | |
| 2858 | expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual( |
| 2859 | outcome === "refused" ? [existing] : [existing, added], |
| 2860 | ); |
| 2861 | expect( |
| 2862 | Option.getOrThrow(AsyncResult.value(registry.get(candidates))).candidates.map( |
| 2863 | (candidate) => candidate.isApplied, |
| 2864 | ), |
| 2865 | ).toEqual(outcome === "refused" ? [true, false] : [true, true]); |
| 2866 | }), |
| 2867 | ), |
| 2868 | ); |
| 2869 | |
| 2870 | it.effect.each(["loaded", "loading"] as const)( |
| 2871 | "keeps an accepted label change when a candidates read sent before it answers late (%s)", |
| 2872 | (shown) => |
| 2873 | Effect.scoped( |
| 2874 | Effect.gen(function* () { |
| 2875 | let applied = false; |
| 2876 | let reads = 0; |
| 2877 | const readStarted = yield* Deferred.make<void>(); |
| 2878 | const releaseRead = yield* Deferred.make<void>(); |
| 2879 | const client = actionReplyClient({ |
| 2880 | [WS_METHODS.pullRequestsLabelCandidates]: () => |
| 2881 | Effect.gen(function* () { |
| 2882 | reads++; |
| 2883 | const answer = { |
| 2884 | candidates: [{ name: "new", color: null, description: null, isApplied: applied }], |
| 2885 | truncated: false, |
| 2886 | }; |
| 2887 | if (reads === (shown === "loaded" ? 2 : 1)) { |
| 2888 | yield* Deferred.succeed(readStarted, undefined); |
| 2889 | yield* Deferred.await(releaseRead); |
| 2890 | } |
| 2891 | return answer; |
| 2892 | }), |
| 2893 | [WS_METHODS.pullRequestsSetLabels]: () => |
| 2894 | Effect.sync(() => { |
| 2895 | applied = true; |
| 2896 | }), |
| 2897 | }); |
| 2898 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 2899 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2900 | const candidates = atoms.labelCandidates(target); |
| 2901 | registry.mount(candidates); |
| 2902 | if (shown === "loaded") { |
| 2903 | yield* Effect.promise(() => executeAtomQuery(registry, candidates)); |
| 2904 | registry.refresh(candidates); |
| 2905 | } |
| 2906 | yield* Deferred.await(readStarted); |
| 2907 | |
| 2908 | yield* Effect.exit( |
| 2909 | atoms.setLabels.run(registry, { |
| 2910 | ...target, |
| 2911 | input: { ...actionReference, labels: ["new"], applied: true }, |
| 2912 | }), |
| 2913 | ); |
| 2914 | yield* Deferred.succeed(releaseRead, undefined); |
| 2915 | |
| 2916 | expect( |
| 2917 | (yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true })) |
| 2918 | .candidates[0]?.isApplied, |
| 2919 | ).toBe(true); |
| 2920 | }), |
| 2921 | ), |
| 2922 | ); |
| 2923 | |
| 2924 | it.effect.each(["accepted", "refused"] as const)( |
| 2925 | "shows a close in the checks read the panel takes its state from (%s)", |
| 2926 | (outcome) => |
| 2927 | Effect.scoped( |
| 2928 | Effect.gen(function* () { |
| 2929 | const sent = yield* Deferred.make<void>(); |
| 2930 | const release = yield* Deferred.make<void>(); |
| 2931 | let reads = 0; |
| 2932 | const client = actionReplyClient({ |
| 2933 | [WS_METHODS.pullRequestsChecks]: () => |
| 2934 | reads++ === 0 |
| 2935 | ? Effect.succeed({ state: "open", checks: [], observedAt: 100 }) |
| 2936 | : Effect.never, |
| 2937 | [WS_METHODS.pullRequestsRunAction]: () => |
| 2938 | Effect.gen(function* () { |
| 2939 | yield* Deferred.succeed(sent, undefined); |
| 2940 | yield* Deferred.await(release); |
| 2941 | if (outcome === "accepted") return { ...actionReply, state: "closed" as const }; |
| 2942 | return yield* new PullRequestOperationError({ |
| 2943 | operation: "runAction", |
| 2944 | detail: "You cannot close this pull request.", |
| 2945 | }); |
| 2946 | }), |
| 2947 | }); |
| 2948 | const { atoms, registry } = yield* makeTestRuntime(client); |
| 2949 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2950 | const checks = atoms.checks(target); |
| 2951 | registry.mount(checks); |
| 2952 | yield* Effect.promise(() => executeAtomQuery(registry, checks)); |
| 2953 | const state = () => Option.getOrThrow(AsyncResult.value(registry.get(checks)))?.state; |
| 2954 | |
| 2955 | const acting = yield* Effect.exit( |
| 2956 | atoms.runAction.run(registry, { |
| 2957 | ...target, |
| 2958 | input: { ...actionReference, action: "close" }, |
| 2959 | }), |
| 2960 | ).pipe(Effect.forkScoped); |
| 2961 | yield* Deferred.await(sent); |
| 2962 | expect(state()).toBe("closed"); |
| 2963 | yield* Deferred.succeed(release, undefined); |
| 2964 | yield* Fiber.join(acting); |
| 2965 | // An accepted close stays while the next checks read is still out. |
| 2966 | expect(state()).toBe(outcome === "accepted" ? "closed" : "open"); |
| 2967 | }), |
| 2968 | ), |
| 2969 | ); |
| 2970 | |
| 2971 | it.effect("paints a saved stack answer at once while the host read is out", () => |
| 2972 | Effect.scoped( |
| 2973 | Effect.gen(function* () { |
| 2974 | const saved = new Map<string, string>(); |
| 2975 | const store = { |
| 2976 | load: (_environmentId: EnvironmentId, key: string) => |
| 2977 | Effect.sync(() => Option.fromUndefinedOr(saved.get(key))), |
| 2978 | save: (_environmentId: EnvironmentId, key: string, payload: string) => |
| 2979 | Effect.sync(() => void saved.set(key, payload)), |
| 2980 | }; |
| 2981 | const earlier = yield* makeTestRuntime( |
| 2982 | { |
| 2983 | [WS_METHODS.pullRequestsStack]: () => Effect.succeed(null), |
| 2984 | } as unknown as WsRpcProtocolClient, |
| 2985 | undefined, |
| 2986 | false, |
| 2987 | {}, |
| 2988 | store, |
| 2989 | ); |
| 2990 | const target = { environmentId: TARGET.environmentId, input: actionReference }; |
| 2991 | const stacks = createPullRequestStackAtomFamily(earlier.runtime); |
| 2992 | const first = stacks(target); |
| 2993 | earlier.registry.mount(first); |
| 2994 | yield* Effect.promise(() => executeAtomQuery(earlier.registry, first)); |
| 2995 | expect(earlier.registry.get(stacks.answered(target))).toBe(true); |
| 2996 | |
| 2997 | // A later session finds the answer saved while its own read waits on the host. |
| 2998 | const sent = yield* Deferred.make<void>(); |
| 2999 | const waiting = yield* makeTestRuntime( |
| 3000 | { |
| 3001 | [WS_METHODS.pullRequestsStack]: () => |
| 3002 | Deferred.succeed(sent, undefined).pipe(Effect.andThen(Effect.never)), |
| 3003 | } as unknown as WsRpcProtocolClient, |
| 3004 | undefined, |
| 3005 | false, |
| 3006 | {}, |
| 3007 | store, |
| 3008 | ); |
| 3009 | const waitingStacks = createPullRequestStackAtomFamily(waiting.runtime); |
| 3010 | const stack = waitingStacks(target); |
| 3011 | waiting.registry.mount(stack); |
| 3012 | yield* Deferred.await(sent); |
| 3013 | expect(waiting.registry.get(stack)).toMatchObject({ _tag: "Success", value: null }); |
| 3014 | // Offline, a saved answer settles without the host; only a host answer may clear a merge. |
| 3015 | expect(waiting.registry.get(waitingStacks.answered(target))).toBe(false); |
| 3016 | }), |
| 3017 | ), |
| 3018 | ); |
| 3019 | |
| 3020 | it.effect("loads the diff again for a new guide head without sending the head", () => |
| 3021 | Effect.gen(function* () { |
| 3022 | const inputs: unknown[] = []; |
| 3023 | const { atoms, registry, supervisor } = yield* makeTestRuntime( |
| 3024 | {} as WsRpcProtocolClient, |
| 3025 | undefined, |
| 3026 | false, |
| 3027 | {}, |
| 3028 | null, |
| 3029 | { |
| 3030 | load: (_prepared, input) => |
| 3031 | Effect.sync(() => { |
| 3032 | inputs.push(input); |
| 3033 | return { patch: "", truncated: false, nextCursor: null }; |
| 3034 | }), |
| 3035 | }, |
| 3036 | ); |
| 3037 | yield* SubscriptionRef.set( |
| 3038 | supervisor.prepared, |
| 3039 | Option.some({ |
| 3040 | environmentId: TARGET.environmentId, |
| 3041 | label: TARGET.label, |
| 3042 | httpBaseUrl: "https://example.test", |
| 3043 | socketUrl: "wss://example.test", |
| 3044 | httpAuthorization: null, |
| 3045 | target: TARGET, |
| 3046 | }), |
| 3047 | ); |
| 3048 | const reference = { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 }; |
| 3049 | for (const cacheHeadSha of ["old-head", "new-head"]) { |
| 3050 | const query = atoms.diff({ |
| 3051 | environmentId: TARGET.environmentId, |
| 3052 | input: { ...reference, cacheHeadSha }, |
| 3053 | }); |
| 3054 | registry.mount(query); |
| 3055 | yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true }); |
| 3056 | } |
| 3057 | expect(inputs).toEqual([reference, reference]); |
| 3058 | }), |
| 3059 | ); |