Open History to see the last commit
1import {
2 EnvironmentId,
3 WS_METHODS,
4 type OrchestrationV2ThreadHistoryPage,
5 type OrchestrationV2ThreadStreamItem,
6 type PeerLinkSummary,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "@effect/vitest";
9import * as DateTime from "effect/DateTime";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Stream from "effect/Stream";
16import * as SubscriptionRef from "effect/SubscriptionRef";
17import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
18
19import { EnvironmentRegistry } from "../connection/registry.ts";
20import { EnvironmentSupervisor } from "../connection/supervisor.ts";
21import type { LinkedThreadView } from "../linkedThread.ts";
22import type { RpcSession } from "../rpc/session.ts";
23import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
24import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts";
25
26// regression: #40544 earlier messages vanished when a linked thread's view opened again
27it.effect(
28 "keeps loaded messages when a linked thread's view opens again on the same snapshot",
29 () =>
30 Effect.gen(function* () {
31 const recent = v2MessageRow("Recent message", 2);
32 const older = v2MessageRow("Earlier message", 1);
33 const snapshot = (historyCursor: string): OrchestrationV2ThreadStreamItem => ({
34 kind: "snapshot",
35 snapshotSequence: 7,
36 projection: { ...v2Projection, turnItems: [recent.item], visibleTurnItems: [recent] },
37 historyCursor,
38 hasMoreHistory: true,
39 });
40 const subscriptions = yield* Queue.unbounded<{
41 items: Queue.Queue<OrchestrationV2ThreadStreamItem>;
42 stopped: Deferred.Deferred<void>;
43 }>();
44 const requested: string[] = [];
45 const client = {
46 [WS_METHODS.peerLinksSubscribeThread]: () =>
47 Stream.unwrap(
48 Effect.gen(function* () {
49 const items = yield* Queue.unbounded<OrchestrationV2ThreadStreamItem>();
50 const stopped = yield* Deferred.make<void>();
51 yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined));
52 yield* Queue.offer(subscriptions, { items, stopped });
53 return Stream.fromQueue(items);
54 }),
55 ),
56 [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) =>
57 Effect.sync((): OrchestrationV2ThreadHistoryPage => {
58 requested.push(cursor);
59 return cursor === "before-recent"
60 ? {
61 snapshotSequence: 7,
62 items: [older],
63 nextCursor: "before-earlier",
64 hasMoreHistory: true,
65 }
66 : { snapshotSequence: 7, items: [], nextCursor: null, hasMoreHistory: false };
67 }),
68 } as unknown as RpcSession["client"];
69 const target = {
70 environmentId: EnvironmentId.make("via"),
71 input: { environmentId: EnvironmentId.make("linked"), threadId: v2ThreadId },
72 };
73 const supervisor = EnvironmentSupervisor.of({
74 target: { environmentId: target.environmentId, label: "Via" },
75 session: yield* SubscriptionRef.make(Option.some({ client })),
76 } as unknown as EnvironmentSupervisor["Service"]);
77 const environment = EnvironmentRegistry.of({
78 followStream: (_id, stream) =>
79 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
80 } as Pick<EnvironmentRegistry["Service"], "followStream"> as EnvironmentRegistry["Service"]);
81 const links = createPeerLinkEnvironmentAtoms(
82 Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)),
83 );
84 const registry = yield* Effect.acquireRelease(
85 Effect.sync(() => AtomRegistry.make()),
86 (registry) => Effect.sync(() => registry.dispose()),
87 );
88 const views = yield* Queue.unbounded<LinkedThreadView>();
89 const open = () =>
90 registry.subscribe(links.threadView(target), (result) => {
91 if (AsyncResult.isSuccess(result)) Queue.offerUnsafe(views, result.value);
92 });
93 const visibleMessages = (view: LinkedThreadView) =>
94 view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId);
95
96 const unmount = open();
97 const first = yield* Queue.take(subscriptions);
98 yield* Queue.offer(first.items, snapshot("before-recent"));
99 (yield* Queue.take(views)).loadEarlier();
100 yield* Queue.take(views); // Loading.
101 expect(visibleMessages(yield* Queue.take(views))).toEqual([
102 older.sourceItemId,
103 recent.sourceItemId,
104 ]);
105 unmount();
106 yield* Deferred.await(first.stopped);
107
108 open();
109 const reopened = yield* Queue.take(subscriptions);
110 yield* Queue.offer(reopened.items, snapshot("before-recent"));
111 const resumed = yield* Queue.take(views);
112 expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]);
113 // Paging goes on from where the closed view stopped, without reading the same page again.
114 expect(resumed.thread.historyCursor).toBe("before-earlier");
115 expect(requested).toEqual(["before-recent"]);
116
117 // A snapshot of another window replaces the rows held for the old one.
118 yield* Queue.offer(reopened.items, snapshot("new-window"));
119 const refreshed = yield* Queue.take(views);
120 expect(visibleMessages(refreshed)).toEqual([recent.sourceItemId]);
121 expect(refreshed.thread.historyCursor).toBe("new-window");
122 }).pipe(Effect.scoped),
123);
124
125const now = DateTime.makeUnsafe("2026-11-20T00:00:00.000Z");
126const id = (value: string) => EnvironmentId.make(value);
127
128const link = (target: string, overrides: Partial<PeerLinkSummary> = {}): PeerLinkSummary => ({
129 environmentId: id(target),
130 label: target,
131 urls: [`https://${target}.example`],
132 access: "full-access",
133 status: "reachable",
134 linkedAt: now,
135 lastReachedAt: now,
136 lastError: null,
137 expiresAt: DateTime.makeUnsafe("2026-12-20T00:00:00.000Z"),
138 ...overrides,
139});
140
141describe("linkThroughRoutes", () => {
142 it("offers only machines another environment reaches over a full-access link that answers", () => {
143 const routes = linkThroughRoutes({
144 sourceEnvironmentId: id("source"),
145 hosts: [
146 { environmentId: id("source"), links: [link("own")] },
147 {
148 environmentId: id("via"),
149 links: [
150 link("open"),
151 link("source"),
152 link("supervised", { access: "approval-required" }),
153 link("down", { status: "unreachable" }),
154 link("lapsed", { expiresAt: now }),
155 ],
156 },
157 { environmentId: id("later"), links: [link("open")] },
158 ],
159 now,
160 });
161 expect([...routes.values()]).toEqual([
162 {
163 viaEnvironmentId: id("via"),
164 environmentId: id("open"),
165 label: "open",
166 urls: ["https://open.example"],
167 },
168 ]);
169 });
170});