@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 239 lines 8.32 KB
Raw
1 import {
2 EnvironmentId,
3 EventId,
4 type OrchestrationV2ThreadHistoryPage,
5 type OrchestrationV2ThreadStreamItem,
6 type PeerLinkClientPairingResult,
7 } from "@t3tools/contracts";
8 import { describe, expect, it } from "@effect/vitest";
9 import * as DateTime from "effect/DateTime";
10 import * as Effect from "effect/Effect";
11 import * as Fiber from "effect/Fiber";
12 import * as Queue from "effect/Queue";
13 import * as Stream from "effect/Stream";
14 import { TestClock } from "effect/testing";
15
16 import {
17 connectLinkedEnvironment,
18 followLinkedThread,
19 keepLinkedThreadView,
20 LINKED_THREAD_RETRY_MS,
21 type LinkedThreadView,
22 } from "./linkedThread.ts";
23 import { v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts";
24
25 const snapshot = (
26 snapshotSequence: number,
27 historyCursor: string | null = null,
28 ): OrchestrationV2ThreadStreamItem => ({
29 kind: "snapshot",
30 snapshotSequence,
31 projection: v2Projection,
32 historyCursor,
33 hasMoreHistory: historyCursor !== null,
34 });
35
36 const retitled = (sequence: number, title: string): OrchestrationV2ThreadStreamItem => ({
37 kind: "event",
38 sequence,
39 event: {
40 id: EventId.make(`event:${sequence}`),
41 type: "thread.metadata-updated",
42 threadId: v2Projection.thread.id,
43 occurredAt: v2Now,
44 payload: { ...v2Projection.thread, title },
45 },
46 });
47
48 const failure = (reason: string) => ({ _tag: "PeerLinkThreadReadError", reason });
49 const titleOf = (view: LinkedThreadView) => view.thread.projection?.thread.title ?? null;
50
51 it.effect("keeps what it read while a linked environment is out of reach, and asks it again", () =>
52 Effect.gen(function* () {
53 const attempts = [
54 Stream.make(snapshot(1), retitled(2, "Renamed")).pipe(
55 Stream.concat(Stream.fail(failure("unreachable"))),
56 ),
57 Stream.make(snapshot(5)).pipe(Stream.concat(Stream.fail(failure("expired")))),
58 ];
59 let opened = 0;
60 const views = yield* Queue.unbounded<LinkedThreadView>();
61 const following = yield* followLinkedThread({
62 items: Stream.suspend(() => attempts[opened++]!),
63 historyPage: () => Effect.die("unused"),
64 }).pipe(
65 Stream.runForEach((view) => Queue.offer(views, view)),
66 Effect.flip,
67 Effect.forkChild,
68 );
69
70 expect(titleOf(yield* Queue.take(views))).toBe(v2Projection.thread.title);
71 expect(titleOf(yield* Queue.take(views))).toBe("Renamed");
72 // Out of reach: the thread stays as read, with the reason beside it.
73 const waiting = yield* Queue.take(views);
74 expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]);
75 expect(opened).toBe(1);
76
77 yield* TestClock.adjust(LINKED_THREAD_RETRY_MS);
78 // It answers again: its snapshot replaces the thread and clears the reason.
79 const back = yield* Queue.take(views);
80 expect([titleOf(back), back.error, back.thread.sequence]).toEqual([
81 v2Projection.thread.title,
82 null,
83 5,
84 ]);
85 // A link that expired cannot come back by waiting, so the stream ends with it.
86 expect(yield* Fiber.join(following)).toEqual(failure("expired"));
87 expect(opened).toBe(2);
88 }),
89 );
90
91 it.effect("keeps the thread a view showed while its reopened stream has read nothing", () =>
92 Effect.gen(function* () {
93 const attempts = [
94 Stream.make(snapshot(1, "cursor-1"), retitled(2, "Renamed")),
95 // The view closed and opened again while the linked environment was out of reach.
96 Stream.fail(failure("unreachable")),
97 Stream.make(snapshot(5)).pipe(Stream.concat(Stream.never)),
98 ];
99 let opened = 0;
100 const follow = () =>
101 followLinkedThread({
102 items: Stream.suspend(() => attempts[opened++]!),
103 historyPage: () => Effect.die("unused"),
104 });
105 let kept: LinkedThreadView | null = null;
106 yield* follow().pipe(
107 Stream.runForEach((view) => Effect.sync(() => (kept = keepLinkedThreadView(kept, view)))),
108 );
109
110 const views = yield* Queue.unbounded<LinkedThreadView>();
111 yield* follow().pipe(
112 Stream.runForEach((view) => Queue.offer(views, keepLinkedThreadView(kept, view))),
113 Effect.forkScoped,
114 );
115 const waiting = yield* Queue.take(views);
116 expect([titleOf(waiting), waiting.error]).toEqual(["Renamed", failure("unreachable")]);
117 // Earlier turns belong to a stream that is gone, so none are offered until one is back.
118 expect(waiting.thread.historyCursor).toBeNull();
119
120 yield* TestClock.adjust(LINKED_THREAD_RETRY_MS);
121 const back = yield* Queue.take(views);
122 expect([titleOf(back), back.error, back.thread.sequence]).toEqual([
123 v2Projection.thread.title,
124 null,
125 5,
126 ]);
127 }).pipe(Effect.scoped),
128 );
129
130 it.effect("loads the turns before a snapshot's window once per request", () =>
131 Effect.gen(function* () {
132 const asked: string[] = [];
133 const page: OrchestrationV2ThreadHistoryPage = {
134 snapshotSequence: 1,
135 items: [],
136 nextCursor: null,
137 hasMoreHistory: false,
138 };
139 const views = yield* Queue.unbounded<LinkedThreadView>();
140 yield* followLinkedThread({
141 items: Stream.make(snapshot(1, "cursor-1")).pipe(Stream.concat(Stream.never)),
142 historyPage: (cursor) =>
143 Effect.sync(() => {
144 asked.push(cursor);
145 return page;
146 }),
147 }).pipe(
148 Stream.runForEach((view) => Queue.offer(views, view)),
149 Effect.forkScoped,
150 );
151
152 const shown = yield* Queue.take(views);
153 expect(shown.thread.historyCursor).toBe("cursor-1");
154 shown.loadEarlier();
155 // A second tap while the page loads asks for nothing more.
156 shown.loadEarlier();
157 expect((yield* Queue.take(views)).history).toEqual({ loading: true, failed: false });
158 const loaded = yield* Queue.take(views);
159 expect([loaded.history.loading, loaded.thread.historyCursor]).toEqual([false, null]);
160 // Nothing is left to load.
161 loaded.loadEarlier();
162 expect(asked).toEqual(["cursor-1"]);
163 }).pipe(Effect.scoped),
164 );
165
166 describe("connectLinkedEnvironment", () => {
167 const lan = "http://192.168.1.20:3773";
168 const tailnet = "https://vm.tail.ts.net";
169 const target = {
170 environmentId: EnvironmentId.make("environment-vm"),
171 label: "VM",
172 urls: [lan, tailnet],
173 };
174 const credential: PeerLinkClientPairingResult = {
175 type: "credential",
176 ...target,
177 credential: "ONE-TIME",
178 expiresAt: DateTime.makeUnsafe(0),
179 };
180 const connect = (
181 pairing: PeerLinkClientPairingResult | null,
182 reachable: ReadonlyArray<string>,
183 paired = true,
184 ) => {
185 const pairs: Array<{ host: string; pairingCode: string }> = [];
186 return connectLinkedEnvironment({
187 label: "vm (saved name)",
188 requestPairing: async () => pairing,
189 reaches: async (host) => reachable.includes(host),
190 pair: async (input) => {
191 pairs.push(input);
192 return paired;
193 },
194 }).then((outcome) => ({ outcome, pairs }));
195 };
196
197 it("redeems the pairing at the first address this device reaches", async () => {
198 expect(await connect(credential, [tailnet])).toEqual({
199 outcome: { type: "connected" },
200 pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
201 });
202 expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan);
203 });
204
205 it("says the machine is out of reach, and spends nothing, when no address answers", async () => {
206 expect(await connect(credential, [])).toEqual({
207 outcome: { type: "unreachable", label: "VM" },
208 pairs: [],
209 });
210 });
211
212 it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => {
213 const unsupported: PeerLinkClientPairingResult = {
214 type: "unsupported",
215 reason: "link_access",
216 ...target,
217 };
218 const manual = (host: string | null) => ({
219 outcome: { type: "manual", label: "VM", host },
220 pairs: [],
221 });
222 expect(await connect(unsupported, [tailnet])).toEqual(manual(tailnet));
223 // An address the user can correct beats an empty field.
224 expect(await connect(unsupported, [])).toEqual(manual(lan));
225 expect(await connect({ ...unsupported, urls: [] }, [])).toEqual(manual(null));
226 // The linking environment never answered, so only the client's own name is known.
227 expect((await connect(null, [lan])).outcome).toEqual({
228 type: "manual",
229 label: "vm (saved name)",
230 host: null,
231 });
232 // The one-time pairing was refused where it was redeemed.
233 expect((await connect(credential, [lan], false)).outcome).toEqual({
234 type: "manual",
235 label: "VM",
236 host: lan,
237 });
238 });
239 });