Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threads-sync.test.ts

715 lines24.3 KB

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