Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off - The probe fixture uses a Node macrotask boundary.
2import * as NodeTimersPromises from "node:timers/promises";
3import {
4 EnvironmentId,
5 EventId,
6 TurnItemId,
7 type OrchestrationV2ProjectedTurnItem,
8 type OrchestrationV2ThreadHistoryPage,
9 type OrchestrationV2ThreadStreamItem,
10 type PeerLinkClientPairingResult,
11} from "@t3tools/contracts";
12import { describe, expect, it } from "@effect/vitest";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Fiber from "effect/Fiber";
16import * as Queue from "effect/Queue";
17import * as Stream from "effect/Stream";
18import { TestClock } from "effect/testing";
19
20import {
21 connectLinkedEnvironment,
22 followLinkedThread,
23 keepLinkedThreadView,
24 LINKED_THREAD_RETRY_MS,
25 type LinkedThreadView,
26} from "./linkedThread.ts";
27import { v2MessageRow, v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts";
28import { MAX_AUTO_CONTINUE_HISTORY_PAGES } from "./state/threadHistoryMerge.ts";
29
30const snapshot = (
31 snapshotSequence: number,
32 historyCursor: string | null = null,
33): OrchestrationV2ThreadStreamItem => ({
34 kind: "snapshot",
35 snapshotSequence,
36 projection: v2Projection,
37 historyCursor,
38 hasMoreHistory: historyCursor !== null,
39});
40
41const retitled = (sequence: number, title: string): OrchestrationV2ThreadStreamItem => ({
42 kind: "event",
43 sequence,
44 event: {
45 id: EventId.make(`event:${sequence}`),
46 type: "thread.metadata-updated",
47 threadId: v2Projection.thread.id,
48 occurredAt: v2Now,
49 payload: { ...v2Projection.thread, title },
50 },
51});
52
53const failure = (reason: string) => ({ _tag: "PeerLinkThreadReadError", reason });
54const titleOf = (view: LinkedThreadView) => view.thread.projection?.thread.title ?? null;
55
56it.effect("keeps what it read while a linked environment is out of reach, and asks it again", () =>
57 Effect.gen(function* () {
58 const attempts = [
59 Stream.make(snapshot(1), retitled(2, "Renamed")).pipe(
60 Stream.concat(Stream.fail(failure("unreachable"))),
61 ),
62 Stream.make(snapshot(5)).pipe(Stream.concat(Stream.fail(failure("expired")))),
63 ];
64 let opened = 0;
65 const views = yield* Queue.unbounded<LinkedThreadView>();
66 const following = yield* followLinkedThread({
67 items: Stream.suspend(() => attempts[opened++]!),
68 historyPage: () => Effect.die("unused"),
69 }).pipe(
70 Stream.runForEach((view) => Queue.offer(views, view)),
71 Effect.flip,
72 Effect.forkChild,
73 );
74
75 expect(titleOf(yield* Queue.take(views))).toBe(v2Projection.thread.title);
76 expect(titleOf(yield* Queue.take(views))).toBe("Renamed");
77 // Out of reach: the thread stays as read, with the reason beside it.
78 const waiting = yield* Queue.take(views);
79 expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]);
80 expect(opened).toBe(1);
81
82 yield* TestClock.adjust(LINKED_THREAD_RETRY_MS);
83 // It answers again: its snapshot replaces the thread and clears the reason.
84 const back = yield* Queue.take(views);
85 expect([titleOf(back), back.error, back.thread.sequence]).toEqual([
86 v2Projection.thread.title,
87 null,
88 5,
89 ]);
90 // A link that expired cannot come back by waiting, so the stream ends with it.
91 expect(yield* Fiber.join(following)).toEqual(failure("expired"));
92 expect(opened).toBe(2);
93 }),
94);
95
96it.effect("keeps the thread a view showed while its reopened stream has read nothing", () =>
97 Effect.gen(function* () {
98 const attempts = [
99 Stream.make(snapshot(1, "cursor-1"), retitled(2, "Renamed")),
100 // The view closed and opened again while the linked environment was out of reach.
101 Stream.fail(failure("unreachable")),
102 Stream.make(snapshot(5)).pipe(Stream.concat(Stream.never)),
103 ];
104 let opened = 0;
105 const follow = () =>
106 followLinkedThread({
107 items: Stream.suspend(() => attempts[opened++]!),
108 historyPage: () => Effect.die("unused"),
109 });
110 let kept: LinkedThreadView | null = null;
111 yield* follow().pipe(
112 Stream.runForEach((view) => Effect.sync(() => (kept = keepLinkedThreadView(kept, view)))),
113 );
114
115 const views = yield* Queue.unbounded<LinkedThreadView>();
116 yield* follow().pipe(
117 Stream.runForEach((view) => Queue.offer(views, keepLinkedThreadView(kept, view))),
118 Effect.forkScoped,
119 );
120 const waiting = yield* Queue.take(views);
121 expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]);
122 // Earlier turns belong to a stream that is gone, so none are offered until one is back.
123 expect(waiting.thread.historyCursor).toBeNull();
124
125 yield* TestClock.adjust(LINKED_THREAD_RETRY_MS);
126 const back = yield* Queue.take(views);
127 expect([titleOf(back), back.error, back.thread.sequence]).toEqual([
128 v2Projection.thread.title,
129 null,
130 5,
131 ]);
132 }).pipe(Effect.scoped),
133);
134
135it.effect("loads the turns before a snapshot's window once per request", () =>
136 Effect.gen(function* () {
137 const asked: string[] = [];
138 const page: OrchestrationV2ThreadHistoryPage = {
139 snapshotSequence: 1,
140 items: [],
141 nextCursor: null,
142 hasMoreHistory: false,
143 };
144 const views = yield* Queue.unbounded<LinkedThreadView>();
145 yield* followLinkedThread({
146 items: Stream.make(snapshot(1, "cursor-1")).pipe(Stream.concat(Stream.never)),
147 historyPage: (cursor) =>
148 Effect.sync(() => {
149 asked.push(cursor);
150 return page;
151 }),
152 }).pipe(
153 Stream.runForEach((view) => Queue.offer(views, view)),
154 Effect.forkScoped,
155 );
156
157 const shown = yield* Queue.take(views);
158 expect(shown.thread.historyCursor).toBe("cursor-1");
159 shown.loadEarlier();
160 // A second tap while the page loads asks for nothing more.
161 shown.loadEarlier();
162 expect((yield* Queue.take(views)).history).toEqual({ loading: true, failed: false });
163 const loaded = yield* Queue.take(views);
164 expect([loaded.history.loading, loaded.thread.historyCursor]).toEqual([false, null]);
165 // Nothing is left to load.
166 loaded.loadEarlier();
167 expect(asked).toEqual(["cursor-1"]);
168 }).pipe(Effect.scoped),
169);
170
171it.effect("brings back the turns a closed view had loaded when it opens again", () =>
172 Effect.gen(function* () {
173 const older = v2MessageRow("Older", 1);
174 const recent = v2MessageRow("Recent", 2);
175 const latest = v2MessageRow("Latest", 3);
176 const window = (
177 snapshotSequence: number,
178 historyCursor: string,
179 row: typeof recent,
180 ): OrchestrationV2ThreadStreamItem => ({
181 kind: "snapshot",
182 snapshotSequence,
183 projection: { ...v2Projection, turnItems: [row.item], visibleTurnItems: [row] },
184 historyCursor,
185 hasMoreHistory: true,
186 });
187 const pages: Record<string, Pick<OrchestrationV2ThreadHistoryPage, "items" | "nextCursor">> = {
188 "before-recent": { items: [older], nextCursor: "before-older" },
189 "before-latest": { items: [recent], nextCursor: "before-recent" },
190 };
191 const asked: string[] = [];
192 const follow = (
193 items: ReadonlyArray<OrchestrationV2ThreadStreamItem>,
194 previous: LinkedThreadView | null,
195 ) =>
196 Effect.gen(function* () {
197 const views = yield* Queue.unbounded<LinkedThreadView>();
198 yield* followLinkedThread({
199 items: Stream.fromIterable(items).pipe(Stream.concat(Stream.never)),
200 historyPage: (cursor) =>
201 Effect.sync(() => {
202 asked.push(cursor);
203 return { ...pages[cursor]!, snapshotSequence: 3, hasMoreHistory: true };
204 }),
205 previous,
206 }).pipe(
207 Stream.runForEach((view) => Queue.offer(views, view)),
208 Effect.forkScoped,
209 );
210 return views;
211 });
212 const settled = Effect.fnUntraced(function* (views: Queue.Queue<LinkedThreadView>) {
213 let view = yield* Queue.take(views);
214 while (view.history.loading) view = yield* Queue.take(views);
215 return view;
216 });
217 const rows = (view: LinkedThreadView) =>
218 view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId);
219
220 const first = yield* follow([window(1, "before-recent", recent), retitled(2, "Renamed")], null);
221 (yield* Queue.take(first)).loadEarlier();
222 yield* Queue.take(first); // Loading.
223 yield* Queue.take(first); // The earlier page.
224 const closed = yield* Queue.take(first);
225 expect([rows(closed), closed.thread.sequence]).toEqual([
226 [older.sourceItemId, recent.sourceItemId],
227 2,
228 ]);
229
230 // Nothing changed while the view was closed: the rows it held are shown as they were.
231 const same = yield* settled(yield* follow([window(2, "before-recent", recent)], closed));
232 expect([rows(same), same.thread.historyCursor]).toEqual([
233 [older.sourceItemId, recent.sourceItemId],
234 "before-older",
235 ]);
236 expect(asked).toEqual(["before-recent"]);
237
238 // The thread moved on: pages are read again until the oldest row it showed is back.
239 const moved = yield* settled(yield* follow([window(3, "before-latest", latest)], closed));
240 expect([rows(moved), moved.thread.historyCursor]).toEqual([
241 [older.sourceItemId, recent.sourceItemId, latest.sourceItemId],
242 "before-older",
243 ]);
244 expect(asked).toEqual(["before-recent", "before-latest", "before-recent"]);
245 }).pipe(Effect.scoped),
246);
247
248it.effect(
249 "continues loading earlier linked history past notifications until a user message arrives",
250 () =>
251 Effect.gen(function* () {
252 const prompt = v2MessageRow("Prompt", 1);
253 const noticeId = TurnItemId.make("Notice");
254 const notice: OrchestrationV2ProjectedTurnItem = {
255 position: 0,
256 visibility: "local",
257 sourceThreadId: prompt.sourceThreadId,
258 sourceItemId: noticeId,
259 item: {
260 id: noticeId,
261 threadId: prompt.sourceThreadId,
262 runId: null,
263 nodeId: null,
264 providerThreadId: null,
265 providerTurnId: null,
266 nativeItemRef: null,
267 parentItemId: null,
268 ordinal: 2,
269 status: "completed",
270 title: null,
271 startedAt: v2Now,
272 completedAt: v2Now,
273 updatedAt: v2Now,
274 type: "notification",
275 source: { kind: "monitor" },
276 outcome: "completed",
277 summary: "Update",
278 },
279 };
280 const asked: string[] = [];
281 const views = yield* Queue.unbounded<LinkedThreadView>();
282 yield* followLinkedThread({
283 items: Stream.make(snapshot(1, "cursor-2")).pipe(Stream.concat(Stream.never)),
284 historyPage: (cursor) =>
285 Effect.sync((): OrchestrationV2ThreadHistoryPage => {
286 asked.push(cursor);
287 if (cursor === "cursor-2") {
288 return {
289 snapshotSequence: 1,
290 items: [notice],
291 nextCursor: "cursor-1",
292 hasMoreHistory: true,
293 hasEarlierUserMessage: true,
294 };
295 }
296 return {
297 snapshotSequence: 1,
298 items: [prompt],
299 nextCursor: "cursor-0",
300 hasMoreHistory: true,
301 };
302 }),
303 }).pipe(
304 Stream.runForEach((view) => Queue.offer(views, view)),
305 Effect.forkScoped,
306 );
307
308 const shown = yield* Queue.take(views);
309 shown.loadEarlier();
310 let settled = yield* Queue.take(views);
311 while (settled.history.loading || asked.length < 2) {
312 settled = yield* Queue.take(views);
313 }
314 expect(asked).toEqual(["cursor-2", "cursor-1"]);
315 expect(settled.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId)).toEqual([
316 prompt.sourceItemId,
317 notice.sourceItemId,
318 ]);
319 expect(settled.thread.historyCursor).toBe("cursor-0");
320 }).pipe(Effect.scoped),
321);
322
323it.effect("caps linked loadEarlier auto-continuation per click and resumes on the next click", () =>
324 Effect.gen(function* () {
325 const totalPages = MAX_AUTO_CONTINUE_HISTORY_PAGES + 2;
326 const prompt = v2MessageRow("Prompt", 1);
327 const asked: string[] = [];
328 const views = yield* Queue.unbounded<LinkedThreadView>();
329 yield* followLinkedThread({
330 items: Stream.make(snapshot(1, `cursor-${totalPages}`)).pipe(Stream.concat(Stream.never)),
331 historyPage: (cursor) =>
332 Effect.sync((): OrchestrationV2ThreadHistoryPage => {
333 asked.push(cursor);
334 const step = Number(cursor.replace("cursor-", ""));
335 if (step === 1) {
336 return {
337 snapshotSequence: 1,
338 items: [prompt],
339 nextCursor: null,
340 hasMoreHistory: false,
341 };
342 }
343 return {
344 snapshotSequence: 1,
345 items: [v2MessageRow(`Step-${step}`, step)],
346 nextCursor: `cursor-${step - 1}`,
347 hasMoreHistory: true,
348 hasEarlierUserMessage: true,
349 };
350 }),
351 }).pipe(
352 Stream.runForEach((view) => Queue.offer(views, view)),
353 Effect.forkScoped,
354 );
355
356 const shown = yield* Queue.take(views);
357 shown.loadEarlier();
358 let afterFirst = yield* Queue.take(views);
359 while (afterFirst.history.loading || asked.length < MAX_AUTO_CONTINUE_HISTORY_PAGES) {
360 afterFirst = yield* Queue.take(views);
361 }
362 const expectedFirst = Array.from(
363 { length: MAX_AUTO_CONTINUE_HISTORY_PAGES },
364 (_, index) => `cursor-${totalPages - index}`,
365 );
366 expect(asked).toEqual(expectedFirst);
367 expect(afterFirst.history).toEqual({ loading: false, failed: false });
368 expect(afterFirst.thread.historyCursor).toBe("cursor-2");
369
370 afterFirst.loadEarlier();
371 let afterSecond = yield* Queue.take(views);
372 while (afterSecond.history.loading || asked.length < totalPages) {
373 afterSecond = yield* Queue.take(views);
374 }
375 expect(asked).toEqual([...expectedFirst, "cursor-2", "cursor-1"]);
376 expect(afterSecond.thread.historyCursor).toBeNull();
377 expect(
378 afterSecond.thread.projection?.visibleTurnItems.some(
379 (row) => row.sourceItemId === prompt.sourceItemId,
380 ),
381 ).toBe(true);
382 }).pipe(Effect.scoped),
383);
384
385describe("connectLinkedEnvironment", () => {
386 const lan = "http://192.168.1.20:3773";
387 const tailnet = "https://vm.tail.ts.net";
388 const target = {
389 environmentId: EnvironmentId.make("environment-vm"),
390 label: "VM",
391 urls: [lan, tailnet],
392 };
393 const credential: PeerLinkClientPairingResult = {
394 type: "credential",
395 ...target,
396 credential: "ONE-TIME",
397 expiresAt: DateTime.makeUnsafe(0),
398 };
399 const unsupported: PeerLinkClientPairingResult = {
400 type: "unsupported",
401 reason: "link_access",
402 ...target,
403 };
404 const connect = (
405 pairing: PeerLinkClientPairingResult | null,
406 reachable: ReadonlyArray<string> | ((host: string) => Promise<boolean>),
407 paired = true,
408 ) => {
409 const pairs: Array<{ host: string; pairingCode: string }> = [];
410 return connectLinkedEnvironment({
411 label: "vm (saved name)",
412 requestPairing: async () => pairing,
413 reaches:
414 typeof reachable === "function" ? reachable : async (host) => reachable.includes(host),
415 pair: async (input) => {
416 pairs.push(input);
417 return paired;
418 },
419 }).then((outcome) => ({ outcome, pairs }));
420 };
421
422 it("redeems the pairing at the first address this device reaches", async () => {
423 expect(await connect(credential, [tailnet])).toEqual({
424 outcome: { type: "connected" },
425 pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
426 });
427 expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan);
428 });
429
430 it.each([
431 {
432 name: "redeems at an alternate after the preferred probe fails",
433 pairing: credential,
434 preferredReachable: false,
435 expected: {
436 outcome: { type: "connected" },
437 pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
438 },
439 },
440 {
441 name: "prefills the preferred address even when an alternate answers first",
442 pairing: unsupported,
443 preferredReachable: true,
444 expected: { outcome: { type: "manual", label: "VM", host: lan }, pairs: [] },
445 },
446 ])("$name without waiting for a silent last address", async (row) => {
447 const last = "https://other.example.test";
448 const preferred = Promise.withResolvers<boolean>();
449 const silent = Promise.withResolvers<boolean>();
450 const connecting = connect({ ...row.pairing, urls: [lan, tailnet, last] }, (host) => {
451 if (host === lan) return preferred.promise;
452 if (host === last) return silent.promise;
453 queueMicrotask(() => preferred.resolve(row.preferredReachable));
454 return Promise.resolve(true);
455 });
456 try {
457 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Let the already runnable probe continuations finish while the last probe stays pending.
458 const pending = NodeTimersPromises.setImmediate("still waiting for an address");
459 expect(await Promise.race([connecting, pending])).toEqual(row.expected);
460 } finally {
461 silent.resolve(false);
462 preferred.resolve(false);
463 }
464 });
465
466 it("says the machine is out of reach, and spends nothing, when no address answers", async () => {
467 expect(await connect(credential, [])).toEqual({
468 outcome: { type: "unreachable", label: "VM" },
469 pairs: [],
470 });
471 });
472
473 it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => {
474 const manual = (host: string | null) => ({
475 outcome: { type: "manual", label: "VM", host },
476 pairs: [],
477 });
478 expect(await connect(unsupported, [tailnet])).toEqual(manual(tailnet));
479 // An address the user can correct beats an empty field.
480 expect(await connect(unsupported, [])).toEqual(manual(lan));
481 expect(await connect({ ...unsupported, urls: [] }, [])).toEqual(manual(null));
482 // The linking environment never answered, so only the client's own name is known.
483 expect((await connect(null, [lan])).outcome).toEqual({
484 type: "manual",
485 label: "vm (saved name)",
486 host: null,
487 });
488 // The one-time pairing was refused where it was redeemed.
489 expect((await connect(credential, [lan], false)).outcome).toEqual({
490 type: "manual",
491 label: "VM",
492 host: lan,
493 });
494 });
495});