Open History to see the last commit
1import {
2 EnvironmentId,
3 PeerLinkThreadReadError,
4 WS_METHODS,
5 type OrchestrationV2ThreadHistoryPage,
6 type OrchestrationV2ThreadStreamItem,
7 type PeerLinkSummary,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "@effect/vitest";
10import * as DateTime from "effect/DateTime";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Queue from "effect/Queue";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
19import { TestClock } from "effect/testing";
20
21import {
22 AVAILABLE_CONNECTION_STATE,
23 PrimaryConnectionTarget,
24 type PreparedConnection,
25 type SupervisorConnectionState,
26} from "../connection/model.ts";
27import { EnvironmentRegistry } from "../connection/registry.ts";
28import { EnvironmentSupervisor } from "../connection/supervisor.ts";
29import type { LinkedThreadView } from "../linkedThread.ts";
30import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
31import type { RpcSession } from "../rpc/session.ts";
32import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
33import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts";
34
35// regression: #40544 earlier messages vanished when a linked thread's view opened again
36it.effect(
37 "keeps loaded messages when a linked thread retries and reopens on the same snapshot",
38 () =>
39 Effect.gen(function* () {
40 const recent = v2MessageRow("Recent message", 2);
41 const older = v2MessageRow("Earlier message", 1);
42 const snapshot = (historyCursor: string): OrchestrationV2ThreadStreamItem => ({
43 kind: "snapshot",
44 snapshotSequence: 7,
45 projection: { ...v2Projection, turnItems: [recent.item], visibleTurnItems: [recent] },
46 historyCursor,
47 hasMoreHistory: true,
48 });
49 const subscriptions = yield* Queue.unbounded<{
50 items: Queue.Queue<OrchestrationV2ThreadStreamItem, PeerLinkThreadReadError>;
51 stopped: Deferred.Deferred<void>;
52 }>();
53 const requested: string[] = [];
54 const client = {
55 [WS_METHODS.peerLinksSubscribeThread]: () =>
56 Stream.unwrap(
57 Effect.gen(function* () {
58 const items = yield* Queue.unbounded<
59 OrchestrationV2ThreadStreamItem,
60 PeerLinkThreadReadError
61 >();
62 const stopped = yield* Deferred.make<void>();
63 yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined));
64 yield* Queue.offer(subscriptions, { items, stopped });
65 return Stream.fromQueue(items);
66 }),
67 ),
68 [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) =>
69 Effect.sync((): OrchestrationV2ThreadHistoryPage => {
70 requested.push(cursor);
71 return cursor === "before-recent"
72 ? {
73 snapshotSequence: 7,
74 items: [older],
75 nextCursor: "before-earlier",
76 hasMoreHistory: true,
77 }
78 : { snapshotSequence: 7, items: [], nextCursor: null, hasMoreHistory: false };
79 }),
80 } as unknown as RpcSession["client"];
81 const target = {
82 environmentId: EnvironmentId.make("via"),
83 input: { environmentId: EnvironmentId.make("linked"), threadId: v2ThreadId },
84 };
85 const supervisor = EnvironmentSupervisor.of({
86 target: { environmentId: target.environmentId, label: "Via" },
87 session: yield* SubscriptionRef.make(Option.some({ client })),
88 } as unknown as EnvironmentSupervisor["Service"]);
89 const environment = EnvironmentRegistry.of({
90 followStream: (_id, stream) =>
91 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
92 } as Pick<EnvironmentRegistry["Service"], "followStream"> as EnvironmentRegistry["Service"]);
93 const links = createPeerLinkEnvironmentAtoms(
94 Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)),
95 );
96 const registry = yield* Effect.acquireRelease(
97 Effect.sync(() => AtomRegistry.make()),
98 (registry) => Effect.sync(() => registry.dispose()),
99 );
100 const views = yield* Queue.unbounded<LinkedThreadView>();
101 const open = () =>
102 registry.subscribe(links.threadView(target), (result) => {
103 if (AsyncResult.isSuccess(result)) Queue.offerUnsafe(views, result.value);
104 });
105 const visibleMessages = (view: LinkedThreadView) =>
106 view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId);
107
108 const unmount = open();
109 const first = yield* Queue.take(subscriptions);
110 yield* Queue.offer(first.items, snapshot("before-recent"));
111 (yield* Queue.take(views)).loadEarlier();
112 yield* Queue.take(views); // Loading.
113 expect(visibleMessages(yield* Queue.take(views))).toEqual([
114 older.sourceItemId,
115 recent.sourceItemId,
116 ]);
117 const unreachable = new PeerLinkThreadReadError({
118 reason: "unreachable",
119 label: "Linked",
120 message: "The linked machine is temporarily unreachable.",
121 });
122 yield* Queue.fail(first.items, unreachable);
123 expect((yield* Queue.take(views)).error).toBe(unreachable);
124
125 registry.refresh(links.threadView(target));
126 yield* TestClock.adjust(0);
127 const retry = yield* Queue.poll(subscriptions);
128 if (Option.isNone(retry)) throw new Error("Refresh did not start a new linked thread read");
129 yield* Queue.offer(retry.value.items, snapshot("before-recent"));
130 const recovered = yield* Queue.take(views).pipe(
131 Effect.repeat({ until: (view) => view.error === null }),
132 );
133 expect(visibleMessages(recovered)).toEqual([older.sourceItemId, recent.sourceItemId]);
134
135 unmount();
136 yield* Deferred.await(retry.value.stopped);
137
138 open();
139 const reopened = yield* Queue.take(subscriptions);
140 yield* Queue.offer(reopened.items, snapshot("before-recent"));
141 const resumed = yield* Queue.take(views);
142 expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]);
143 // Paging goes on from where the closed view stopped, without reading the same page again.
144 expect(resumed.thread.historyCursor).toBe("before-earlier");
145 expect(requested).toEqual(["before-recent"]);
146
147 // A snapshot of another window replaces the rows held for the old one.
148 yield* Queue.offer(reopened.items, snapshot("new-window"));
149 const refreshed = yield* Queue.take(views);
150 expect(visibleMessages(refreshed)).toEqual([recent.sourceItemId]);
151 expect(refreshed.thread.historyCursor).toBe("new-window");
152 }).pipe(Effect.scoped),
153);
154
155const now = DateTime.makeUnsafe("2026-11-20T00:00:00.000Z");
156const id = (value: string) => EnvironmentId.make(value);
157
158const link = (target: string, overrides: Partial<PeerLinkSummary> = {}): PeerLinkSummary => ({
159 environmentId: id(target),
160 label: target,
161 urls: [`https://${target}.example`],
162 access: "full-access",
163 status: "reachable",
164 linkedAt: now,
165 lastReachedAt: now,
166 lastError: null,
167 expiresAt: DateTime.makeUnsafe("2026-12-20T00:00:00.000Z"),
168 ...overrides,
169});
170
171describe("linkThroughRoutes", () => {
172 it("offers only machines another environment reaches over a full-access link that answers", () => {
173 const routes = linkThroughRoutes({
174 sourceEnvironmentId: id("source"),
175 hosts: [
176 { environmentId: id("source"), links: [link("own")] },
177 {
178 environmentId: id("via"),
179 links: [
180 link("open"),
181 link("source"),
182 link("supervised", { access: "approval-required" }),
183 link("down", { status: "unreachable" }),
184 link("lapsed", { expiresAt: now }),
185 ],
186 },
187 { environmentId: id("later"), links: [link("open")] },
188 ],
189 now,
190 });
191 expect([...routes.values()]).toEqual([
192 {
193 viaEnvironmentId: id("via"),
194 environmentId: id("open"),
195 label: "open",
196 urls: ["https://open.example"],
197 },
198 ]);
199 });
200});
201
202describe("refreshNamesLacking", () => {
203 // regression: #41707 a link made outside this client stayed unknown while the names were read
204 it.effect("rereads fresh names that lack a wanted machine, once per miss", () =>
205 Effect.gen(function* () {
206 const target = new PrimaryConnectionTarget({
207 environmentId: id("via"),
208 label: "Via",
209 httpBaseUrl: "https://via.example.test",
210 wsBaseUrl: "wss://via.example.test",
211 });
212 let stored = [{ environmentId: id("known"), label: "Known" }];
213 let reads = 0;
214 const client = {
215 [WS_METHODS.peerLinksNames]: () =>
216 Effect.sync(() => {
217 reads += 1;
218 return { links: stored };
219 }),
220 } as unknown as WsRpcProtocolClient;
221 const session = { client } as unknown as RpcSession;
222 const supervisor = EnvironmentSupervisor.of({
223 target,
224 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
225 ...AVAILABLE_CONNECTION_STATE,
226 phase: "connected",
227 }),
228 session: yield* SubscriptionRef.make(Option.some(session)),
229 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
230 } as unknown as EnvironmentSupervisor["Service"]);
231 const environment = EnvironmentRegistry.of({
232 run: (_id, effect) => Effect.provideService(effect, EnvironmentSupervisor, supervisor),
233 followStream: (_id, stream) =>
234 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
235 } as EnvironmentRegistry["Service"]);
236 const links = createPeerLinkEnvironmentAtoms(
237 Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)),
238 );
239 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
240 Effect.sync(() => registry.dispose()),
241 );
242 const names = links.names({ environmentId: target.environmentId, input: {} });
243 registry.mount(names);
244 const settled = () =>
245 AtomRegistry.toStream(registry, names).pipe(
246 Stream.filter((result) => AsyncResult.isSuccess(result) && !result.waiting),
247 Stream.runHead,
248 Effect.map(Option.getOrThrow),
249 );
250 yield* settled();
251 expect(reads).toBe(1);
252
253 links.refreshNamesLacking(registry, target.environmentId, [id("known")]);
254 expect(reads).toBe(1);
255
256 // Linked from the CLI or another client inside the names' stale time: the server has it,
257 // this client was not told.
258 stored = [...stored, { environmentId: id("new"), label: "New" }];
259 links.refreshNamesLacking(registry, target.environmentId, [id("new")]);
260 // A second reader meeting the same machine joins the read under way.
261 links.refreshNamesLacking(registry, target.environmentId, [id("new")]);
262 const reread = yield* settled();
263 expect(reads).toBe(2);
264 expect(
265 AsyncResult.isSuccess(reread) && reread.value.links.map((link) => link.environmentId),
266 ).toEqual([id("known"), id("new")]);
267 }).pipe(Effect.scoped),
268 );
269});