Open History to see the last commit
1import {
2 EnvironmentId,
3 EventId,
4 ORCHESTRATION_WS_METHODS,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 TurnId,
9 type OrchestrationThread,
10 type OrchestrationThreadDetailSnapshot,
11 type OrchestrationThreadStreamItem,
12} from "@t3tools/contracts";
13import { describe, expect, it } from "@effect/vitest";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import * as TestClock from "effect/testing/TestClock";
21
22import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
23import {
24 AVAILABLE_CONNECTION_STATE,
25 PrimaryConnectionTarget,
26 type PreparedConnection,
27 type SupervisorConnectionState,
28} from "../connection/model.ts";
29import * as ConnectionWakeups from "../connection/wakeups.ts";
30import * as EnvironmentSupervisor from "../connection/supervisor.ts";
31import * as Persistence from "../platform/persistence.ts";
32import * as RpcSession from "../rpc/session.ts";
33import {
34 EMPTY_ENVIRONMENT_THREAD_STATE,
35 makeEnvironmentThreadState,
36 ThreadSnapshotLoader,
37 type EnvironmentThreadState,
38} from "./threads.ts";
39
40const TARGET = new PrimaryConnectionTarget({
41 environmentId: EnvironmentId.make("environment-1"),
42 label: "Test environment",
43 httpBaseUrl: "https://environment.example.test",
44 wsBaseUrl: "wss://environment.example.test",
45});
46const THREAD_ID = ThreadId.make("thread-1");
47const CACHED_SNAPSHOT_SEQUENCE = 7;
48const PREPARED: PreparedConnection = {
49 environmentId: TARGET.environmentId,
50 label: TARGET.label,
51 httpBaseUrl: TARGET.httpBaseUrl,
52 socketUrl: TARGET.wsBaseUrl,
53 httpAuthorization: null,
54 target: TARGET,
55};
56const BASE_THREAD: OrchestrationThread = {
57 id: THREAD_ID,
58 projectId: ProjectId.make("project-1"),
59 title: "Cached thread",
60 modelSelection: {
61 instanceId: ProviderInstanceId.make("codex"),
62 model: "gpt-5.4",
63 },
64 runtimeMode: "full-access",
65 interactionMode: "default",
66 branch: "main",
67 worktreePath: null,
68 latestTurn: null,
69 createdAt: "2026-04-01T00:00:00.000Z",
70 updatedAt: "2026-04-01T00:00:00.000Z",
71 archivedAt: null,
72 settledOverride: null,
73 settledAt: null,
74 deletedAt: null,
75 messages: [],
76 proposedPlans: [],
77 activities: [],
78 checkpoints: [],
79 session: null,
80};
81const ACTIVE_THREAD: OrchestrationThread = {
82 ...BASE_THREAD,
83 latestTurn: {
84 turnId: TurnId.make("turn-1"),
85 state: "running",
86 requestedAt: "2026-04-01T00:01:00.000Z",
87 startedAt: "2026-04-01T00:01:00.000Z",
88 completedAt: null,
89 assistantMessageId: null,
90 },
91 session: {
92 threadId: THREAD_ID,
93 status: "running",
94 providerName: "codex",
95 runtimeMode: "full-access",
96 activeTurnId: TurnId.make("turn-1"),
97 lastError: null,
98 updatedAt: "2026-04-01T00:01:00.000Z",
99 },
100};
101
102type TestThreadInput = OrchestrationThreadStreamItem | Error;
103
104function testSession(
105 client: WsRpcProtocolClient,
106 options?: { readonly completionMarker?: boolean },
107): RpcSession.RpcSession {
108 return {
109 client,
110 initialConfig: Effect.succeed(
111 options?.completionMarker === true
112 ? ({ threadResumeCompletionMarker: true } as never)
113 : ({} as never),
114 ),
115 ready: Effect.void,
116 probe: Effect.void,
117 closed: Effect.never,
118 };
119}
120
121function awaitThreadState(
122 observed: Queue.Queue<EnvironmentThreadState>,
123 predicate: (state: EnvironmentThreadState) => boolean,
124) {
125 return Queue.take(observed).pipe(
126 Effect.repeat({
127 until: predicate,
128 }),
129 );
130}
131
132const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
133 readonly cached?: OrchestrationThread;
134 readonly httpSnapshot?: Option.Option<OrchestrationThreadDetailSnapshot>;
135 readonly completionMarker?: boolean;
136}) {
137 const inputs = yield* Queue.unbounded<TestThreadInput>();
138 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
139 const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
140 const retryCount = yield* Ref.make(0);
141 const subscriptionCount = yield* Ref.make(0);
142 const loaderCalls = yield* Ref.make(0);
143 const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
144 const lastRequestCompletionMarker = yield* Ref.make<boolean | undefined>(undefined);
145 const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
146 const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
147 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
148 const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
149 AVAILABLE_CONNECTION_STATE,
150 );
151 const streamFrom = (queue: Queue.Queue<TestThreadInput>) =>
152 Stream.fromQueue(queue).pipe(
153 Stream.mapEffect((input) =>
154 input instanceof Error ? Effect.fail(input) : Effect.succeed(input),
155 ),
156 );
157 const client = {
158 [ORCHESTRATION_WS_METHODS.subscribeThread]: (input: {
159 readonly afterSequence?: number;
160 readonly requestCompletionMarker?: boolean;
161 }) =>
162 Stream.unwrap(
163 Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
164 Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
165 Effect.andThen(Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker)),
166 Effect.as(streamFrom(inputs)),
167 ),
168 ),
169 } as unknown as WsRpcProtocolClient;
170 const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
171 Option.some(
172 testSession(
173 client,
174 options?.completionMarker === true ? { completionMarker: true } : undefined,
175 ),
176 ),
177 );
178 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
179 Option.some(PREPARED),
180 );
181 const snapshotLoader = ThreadSnapshotLoader.of({
182 load: (_prepared, threadId) =>
183 Ref.update(loaderCalls, (count) => count + 1).pipe(
184 Effect.as(
185 threadId === THREAD_ID
186 ? (options?.httpSnapshot ?? Option.none<OrchestrationThreadDetailSnapshot>())
187 : Option.none<OrchestrationThreadDetailSnapshot>(),
188 ),
189 ),
190 });
191 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
192 target: TARGET,
193 state: supervisorState,
194 session: supervisorSession,
195 prepared,
196 connect: Effect.void,
197 disconnect: Effect.void,
198 retryNow: Ref.update(retryCount, (count) => count + 1),
199 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
200 const cache = Persistence.EnvironmentCacheStore.of({
201 loadShell: () => Effect.succeed(Option.none()),
202 saveShell: () => Effect.void,
203 loadThread: (_environmentId, threadId) =>
204 Effect.succeed(
205 threadId === THREAD_ID && options?.cached !== undefined
206 ? Option.some({
207 snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
208 thread: options.cached,
209 })
210 : Option.none(),
211 ),
212 saveThread: (_environmentId, thread) =>
213 Ref.update(savedThreads, (current) => [...current, thread]),
214 removeThread: (_environmentId, threadId) =>
215 Ref.update(removedThreads, (current) => [...current, threadId]),
216 loadServerConfig: () => Effect.succeed(Option.none()),
217 saveServerConfig: () => Effect.void,
218 loadVcsRefs: () => Effect.succeed(Option.none()),
219 saveVcsRefs: () => Effect.void,
220 removeVcsRefs: () => Effect.void,
221 clearVcsRefs: () => Effect.void,
222 clear: () => Effect.void,
223 });
224 const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
225 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
226 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
227 Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
228 Effect.provideService(
229 ConnectionWakeups.ConnectionWakeups,
230 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
231 ),
232 );
233 yield* SubscriptionRef.changes(threadState).pipe(
234 Stream.runForEach((state) =>
235 Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))),
236 ),
237 Effect.forkScoped,
238 );
239
240 return {
241 inputs,
242 observed,
243 latest,
244 retryCount,
245 subscriptionCount,
246 loaderCalls,
247 lastSubscribeAfterSequence,
248 lastRequestCompletionMarker,
249 supervisorState,
250 supervisorSession,
251 savedThreads,
252 removedThreads,
253 wakeups,
254 replaceSession: SubscriptionRef.set(
255 supervisorSession,
256 Option.some(
257 testSession(
258 client,
259 options?.completionMarker === true ? { completionMarker: true } : undefined,
260 ),
261 ),
262 ),
263 };
264});
265
266const snapshot = (thread: OrchestrationThread): OrchestrationThreadStreamItem => ({
267 kind: "snapshot",
268 snapshot: {
269 snapshotSequence: 1,
270 thread,
271 },
272});
273
274const synchronized = (): OrchestrationThreadStreamItem => ({ kind: "synchronized" });
275
276const titleUpdated = (title: string, sequence = 2): OrchestrationThreadStreamItem => ({
277 kind: "event",
278 event: {
279 eventId: EventId.make("event-title"),
280 sequence,
281 occurredAt: "2026-04-01T01:00:00.000Z",
282 commandId: null,
283 causationEventId: null,
284 correlationId: null,
285 metadata: {},
286 aggregateKind: "thread",
287 aggregateId: THREAD_ID,
288 type: "thread.meta-updated",
289 payload: {
290 threadId: THREAD_ID,
291 title,
292 updatedAt: "2026-04-01T01:00:00.000Z",
293 },
294 },
295});
296
297const deleted = (): OrchestrationThreadStreamItem => ({
298 kind: "event",
299 event: {
300 eventId: EventId.make("event-deleted"),
301 sequence: 3,
302 occurredAt: "2026-04-01T02:00:00.000Z",
303 commandId: null,
304 causationEventId: null,
305 correlationId: null,
306 metadata: {},
307 aggregateKind: "thread",
308 aggregateId: THREAD_ID,
309 type: "thread.deleted",
310 payload: {
311 threadId: THREAD_ID,
312 deletedAt: "2026-04-01T02:00:00.000Z",
313 },
314 },
315});
316
317describe("EnvironmentThreads", () => {
318 it.effect("publishes cached data immediately from a warm cache", () =>
319 Effect.gen(function* () {
320 const harness = yield* makeHarness({ cached: BASE_THREAD });
321 const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
322
323 expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
324 expect(Option.isNone(state.error)).toBe(true);
325 }),
326 );
327
328 it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
329 Effect.gen(function* () {
330 const harness = yield* makeHarness({ cached: BASE_THREAD });
331
332 // The warm cache reaches live from the cached data, and a live event
333 // applies on top of it.
334 yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
335 yield* awaitThreadState(
336 harness.observed,
337 (value) =>
338 value.status === "live" &&
339 Option.isSome(value.data) &&
340 value.data.value.title === "Live title",
341 );
342
343 // The subscription resumed from the cached sequence and never fetched the
344 // full snapshot over HTTP.
345 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
346 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
347 }),
348 );
349
350 it.effect("reduces live events and persists the latest thread", () =>
351 Effect.gen(function* () {
352 const harness = yield* makeHarness({ cached: BASE_THREAD });
353 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
354 yield* Queue.offer(harness.inputs, titleUpdated("Live title"));
355
356 const state = yield* awaitThreadState(
357 harness.observed,
358 (value) =>
359 value.status === "live" &&
360 Option.isSome(value.data) &&
361 value.data.value.title === "Live title",
362 );
363 yield* TestClock.adjust("500 millis");
364 yield* Effect.yieldNow;
365
366 expect(Option.getOrThrow(state.data).title).toBe("Live title");
367 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.thread.title).toBe("Live title");
368 expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
369 }),
370 );
371
372 it.effect("does not persist active thread snapshots during streaming or teardown", () =>
373 Effect.gen(function* () {
374 const savedThreads = yield* Effect.scoped(
375 Effect.gen(function* () {
376 const harness = yield* makeHarness({ cached: ACTIVE_THREAD });
377 yield* awaitThreadState(
378 harness.observed,
379 (value) =>
380 value.status === "live" &&
381 Option.isSome(value.data) &&
382 value.data.value.session?.status === "running",
383 );
384
385 yield* TestClock.adjust("500 millis");
386 yield* Effect.yieldNow;
387
388 expect(yield* Ref.get(harness.savedThreads)).toEqual([]);
389 return harness.savedThreads;
390 }),
391 );
392
393 expect(yield* Ref.get(savedThreads)).toEqual([]);
394 }),
395 );
396
397 it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
398 Effect.gen(function* () {
399 const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
400 const harness = yield* makeHarness({
401 httpSnapshot: Option.some({ snapshotSequence: 1, thread: httpThread }),
402 });
403 // No socket snapshot is pushed; only a live event arrives over the socket.
404 // It can only be applied if the HTTP snapshot already seeded the thread.
405 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
406
407 const state = yield* awaitThreadState(
408 harness.observed,
409 (value) =>
410 value.status === "live" &&
411 Option.isSome(value.data) &&
412 value.data.value.title === "Live title",
413 );
414
415 expect(Option.getOrThrow(state.data).title).toBe("Live title");
416 // Cold cache: the full snapshot was loaded over HTTP and the socket
417 // resumed from that snapshot's sequence.
418 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
419 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
420 }),
421 );
422
423 it.effect("ignores replayed thread events at or below the snapshot sequence", () =>
424 Effect.gen(function* () {
425 const harness = yield* makeHarness({ cached: BASE_THREAD });
426 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
427 yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1));
428 yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
429
430 const state = yield* awaitThreadState(
431 harness.observed,
432 (value) =>
433 value.status === "live" &&
434 Option.isSome(value.data) &&
435 value.data.value.title === "Live title",
436 );
437
438 expect(Option.getOrThrow(state.data).title).toBe("Live title");
439 }),
440 );
441
442 it.effect("removes cached data when the thread is deleted", () =>
443 Effect.gen(function* () {
444 const harness = yield* makeHarness({ cached: BASE_THREAD });
445 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
446 yield* Queue.offer(harness.inputs, deleted());
447
448 const state = yield* awaitThreadState(
449 harness.observed,
450 (value) => value.status === "deleted",
451 );
452
453 expect(Option.isNone(state.data)).toBe(true);
454 expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]);
455 }),
456 );
457
458 it.effect("does not resurrect a deleted thread when the app returns to the foreground", () =>
459 Effect.gen(function* () {
460 const harness = yield* makeHarness({
461 cached: BASE_THREAD,
462 completionMarker: true,
463 httpSnapshot: Option.some({
464 snapshotSequence: 4,
465 thread: { ...BASE_THREAD, title: "Stale HTTP thread" },
466 }),
467 });
468 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
469 yield* Queue.offer(harness.inputs, deleted());
470 yield* awaitThreadState(harness.observed, (value) => value.status === "deleted");
471
472 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
473 yield* Queue.offer(harness.wakeups, "application-active");
474 for (let attempt = 0; attempt < 100; attempt += 1) {
475 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
476 yield* Effect.yieldNow;
477 }
478
479 const latest = yield* Ref.get(harness.latest);
480 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
481 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
482 expect(latest.status).toBe("deleted");
483 expect(Option.isNone(latest.data)).toBe(true);
484 }),
485 );
486
487 it.effect("preserves data after a domain failure and resumes on a replacement session", () =>
488 Effect.gen(function* () {
489 const harness = yield* makeHarness({ cached: BASE_THREAD });
490 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
491 yield* Queue.offer(harness.inputs, new Error("stream failed"));
492
493 const state = yield* awaitThreadState(harness.observed, (value) =>
494 Option.isSome(value.error),
495 );
496
497 expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
498 expect(Option.getOrThrow(state.error)).toBe("stream failed");
499 expect(yield* Ref.get(harness.retryCount)).toBe(0);
500
501 yield* harness.replaceSession;
502 for (let attempt = 0; attempt < 100; attempt += 1) {
503 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
504 break;
505 }
506 yield* Effect.yieldNow;
507 }
508 yield* Queue.offer(
509 harness.inputs,
510 snapshot({
511 ...BASE_THREAD,
512 title: "Recovered thread",
513 }),
514 );
515 const recovered = yield* awaitThreadState(
516 harness.observed,
517 (value) =>
518 value.status === "live" &&
519 Option.isSome(value.data) &&
520 value.data.value.title === "Recovered thread",
521 );
522
523 expect(Option.isNone(recovered.error)).toBe(true);
524 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
525 }),
526 );
527
528 it.effect("recovers from a transient domain failure without replacing the session", () =>
529 Effect.gen(function* () {
530 const harness = yield* makeHarness();
531 yield* Queue.offer(harness.inputs, new Error("thread not found yet"));
532
533 const failed = yield* awaitThreadState(harness.observed, (value) =>
534 Option.isSome(value.error),
535 );
536 expect(Option.getOrThrow(failed.error)).toBe("thread not found yet");
537 expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
538
539 yield* TestClock.adjust("250 millis");
540 for (let attempt = 0; attempt < 100; attempt += 1) {
541 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
542 break;
543 }
544 yield* Effect.yieldNow;
545 }
546 yield* Queue.offer(
547 harness.inputs,
548 snapshot({
549 ...BASE_THREAD,
550 title: "Materialized thread",
551 }),
552 );
553
554 const recovered = yield* awaitThreadState(
555 harness.observed,
556 (value) =>
557 value.status === "live" &&
558 Option.isSome(value.data) &&
559 value.data.value.title === "Materialized thread",
560 );
561
562 expect(Option.isNone(recovered.error)).toBe(true);
563 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
564 expect(yield* Ref.get(harness.retryCount)).toBe(0);
565 }),
566 );
567
568 it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () =>
569 Effect.gen(function* () {
570 const harness = yield* makeHarness({ cached: BASE_THREAD });
571 yield* SubscriptionRef.set(harness.supervisorState, {
572 desired: true,
573 network: "online",
574 phase: "connecting",
575 stage: "synchronizing",
576 attempt: 1,
577 generation: 0,
578 lastFailure: null,
579 retryAt: null,
580 });
581 yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
582 yield* awaitThreadState(harness.observed, (value) => value.status === "live");
583
584 yield* SubscriptionRef.set(harness.supervisorState, {
585 desired: true,
586 network: "online",
587 phase: "connected",
588 stage: null,
589 attempt: 1,
590 generation: 1,
591 lastFailure: null,
592 retryAt: null,
593 });
594 for (let index = 0; index < 10; index += 1) {
595 yield* Effect.yieldNow;
596 }
597
598 expect((yield* Ref.get(harness.latest)).status).toBe("live");
599 }),
600 );
601
602 it.effect("keeps replayed updates synchronizing until the completion marker arrives", () =>
603 Effect.gen(function* () {
604 const harness = yield* makeHarness({ cached: BASE_THREAD, completionMarker: true });
605 yield* awaitThreadState(
606 harness.observed,
607 (value) => value.status === "synchronizing" && Option.isSome(value.data),
608 );
609 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
610
611 yield* Queue.offer(
612 harness.inputs,
613 titleUpdated("Caught-up title", CACHED_SNAPSHOT_SEQUENCE + 1),
614 );
615 const catchingUp = yield* awaitThreadState(
616 harness.observed,
617 (value) =>
618 value.status === "synchronizing" &&
619 Option.isSome(value.data) &&
620 value.data.value.title === "Caught-up title",
621 );
622 expect(catchingUp.status).toBe("synchronizing");
623
624 yield* Queue.offer(harness.inputs, synchronized());
625 const live = yield* awaitThreadState(
626 harness.observed,
627 (value) => value.status === "live" && Option.isSome(value.data),
628 );
629 expect(Option.getOrThrow(live.data).title).toBe("Caught-up title");
630 }),
631 );
632
633 it.effect("resumes replacement sessions from the latest applied sequence", () =>
634 Effect.gen(function* () {
635 const harness = yield* makeHarness({ cached: BASE_THREAD, completionMarker: true });
636 yield* Queue.offer(
637 harness.inputs,
638 titleUpdated("Latest title", CACHED_SNAPSHOT_SEQUENCE + 1),
639 );
640 yield* Queue.offer(harness.inputs, synchronized());
641 yield* awaitThreadState(
642 harness.observed,
643 (value) =>
644 value.status === "live" &&
645 Option.isSome(value.data) &&
646 value.data.value.title === "Latest title",
647 );
648
649 yield* harness.replaceSession;
650 for (let attempt = 0; attempt < 100; attempt += 1) {
651 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
652 yield* Effect.yieldNow;
653 }
654
655 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
656 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
657 expect((yield* Ref.get(harness.latest)).status).toBe("synchronizing");
658 }),
659 );
660
661 it.effect("resubscribes on app foreground from the latest applied sequence", () =>
662 Effect.gen(function* () {
663 const harness = yield* makeHarness({ cached: BASE_THREAD, completionMarker: true });
664 yield* Queue.offer(
665 harness.inputs,
666 titleUpdated("Latest title", CACHED_SNAPSHOT_SEQUENCE + 1),
667 );
668 yield* Queue.offer(harness.inputs, synchronized());
669 yield* awaitThreadState(
670 harness.observed,
671 (value) =>
672 value.status === "live" &&
673 Option.isSome(value.data) &&
674 value.data.value.title === "Latest title",
675 );
676
677 yield* Queue.offer(harness.wakeups, "application-active");
678 const synchronizing = yield* awaitThreadState(
679 harness.observed,
680 (value) => value.status === "synchronizing" && Option.isSome(value.data),
681 );
682 for (let attempt = 0; attempt < 100; attempt += 1) {
683 if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
684 yield* Effect.yieldNow;
685 }
686
687 expect(synchronizing.status).toBe("synchronizing");
688 expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
689 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 1);
690 expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true);
691 expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
692
693 yield* Queue.offer(harness.inputs, synchronized());
694 const live = yield* awaitThreadState(
695 harness.observed,
696 (value) => value.status === "live" && Option.isSome(value.data),
697 );
698 expect(Option.getOrThrow(live.data).title).toBe("Latest title");
699
700 yield* Queue.offer(harness.wakeups, "application-active-probe");
701 for (let attempt = 0; attempt < 100; attempt += 1) {
702 if ((yield* Ref.get(harness.subscriptionCount)) >= 3) break;
703 yield* Effect.yieldNow;
704 }
705 expect(yield* Ref.get(harness.subscriptionCount)).toBe(3);
706
707 yield* Queue.offer(harness.wakeups, "application-active-reconnect");
708 for (let attempt = 0; attempt < 10; attempt += 1) {
709 yield* Effect.yieldNow;
710 }
711 expect(yield* Ref.get(harness.subscriptionCount)).toBe(3);
712 }),
713 );
714});