@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 306 lines 11.3 KB
Raw
1 import { EnvironmentId, PeerLinkError } from "@t3tools/contracts";
2 import * as Result from "effect/Result";
3 import { describe, expect, it } from "vite-plus/test";
4
5 import {
6 linkBackOffer,
7 linkBatchCandidates,
8 linkBatchSummary,
9 linkListState,
10 runLinkBatch,
11 } from "./linkBatch.ts";
12 import type { LinkableMachine } from "./linkRequest.ts";
13
14 const machine = (name: string, overrides: Partial<LinkableMachine> = {}): LinkableMachine => ({
15 environmentId: EnvironmentId.make(`environment-${name}`),
16 label: name,
17 machine: "server",
18 connected: true,
19 connectOnly: false,
20 linked: false,
21 urls: [`https://${name}.example.ts.net`, `http://100.64.0.1:3773`],
22 ...overrides,
23 });
24 const id = (name: string) => EnvironmentId.make(`environment-${name}`);
25
26 describe("linkBatchCandidates", () => {
27 it("offers only machines the client can mint a code on and has an address for", () => {
28 const machines = [
29 machine("ready"),
30 machine("linked", { linked: true, connected: false }),
31 machine("offline", { connected: false }),
32 machine("connect", { connected: false, connectOnly: true }),
33 machine("viewer"),
34 machine("loopback", { urls: [] }),
35 ];
36 const writable = new Set([id("ready"), id("linked"), id("offline"), id("loopback")]);
37 expect(
38 linkBatchCandidates(machines, writable, "loaded").map(({ machine, blocked }) => [
39 machine.label,
40 blocked,
41 ]),
42 ).toEqual([
43 ["ready", null],
44 ["linked", "linked"],
45 ["offline", "not_connected"],
46 ["connect", "not_connected"],
47 ["viewer", "no_access"],
48 ["loopback", "no_address"],
49 ]);
50 });
51
52 it("offers no machine until the linking environment's links have loaded", () => {
53 // With no list, a linked machine reads as unlinked.
54 const machines = [machine("ready"), machine("linked-but-unlisted")];
55 const writable = new Set(machines.map((entry) => entry.environmentId));
56 const blockedWhen = (query: Parameters<typeof linkListState>[0]) =>
57 linkBatchCandidates(machines, writable, linkListState(query)).map(({ blocked }) => blocked);
58 expect(linkListState({ data: null, error: null })).toBe("loading");
59 expect(linkListState({ data: null, error: "The environment request failed." })).toBe("failed");
60 expect(blockedWhen({ data: null, error: null })).toEqual(["links_unknown", "links_unknown"]);
61 expect(blockedWhen({ data: null, error: "failed" })).toEqual([
62 "links_unknown",
63 "links_unknown",
64 ]);
65 expect(blockedWhen({ data: { links: [] }, error: null })).toEqual([null, null]);
66 });
67 });
68
69 describe("runLinkBatch", () => {
70 it("links each machine with its own code, reports each failure, and retries only those", async () => {
71 const machines = ["a", "b", "c", "d", "e"].map((name) => machine(name));
72 const linked: Array<unknown> = [];
73 const failures: Record<string, unknown> = {
74 b: new PeerLinkError({
75 reason: "pairing_rejected",
76 message: "The peer refused the sign-in.",
77 }),
78 c: new PeerLinkError({ reason: "unreachable", message: "c did not answer." }),
79 d: new PeerLinkError({
80 reason: "unreachable",
81 message: "d answered as another environment, Impostor.",
82 answeredAs: "Impostor",
83 }),
84 };
85 const seen: Array<string> = [];
86 const outcomes = await runLinkBatch({
87 machines,
88 access: "auto",
89 mint: async (environmentId) =>
90 environmentId === id("e")
91 ? Result.fail(new Error("no session"))
92 : Result.succeed(`code-for-${environmentId}`),
93 link: async (input) => {
94 linked.push(input);
95 const failure = failures[input.expectedLabel ?? ""];
96 return failure === undefined ? Result.succeed(null) : Result.fail(failure);
97 },
98 refreshLinks: () => {},
99 onOutcome: (environmentId) => seen.push(environmentId),
100 });
101
102 expect(linked[0]).toEqual({
103 url: "https://a.example.ts.net",
104 alternateUrls: ["http://100.64.0.1:3773"],
105 expectedEnvironmentId: id("a"),
106 expectedLabel: "a",
107 pairingCode: `code-for-${id("a")}`,
108 access: "auto",
109 });
110 // A machine with no code is never linked.
111 expect(linked.length).toBe(4);
112 expect(Object.fromEntries(outcomes)).toEqual({
113 [id("a")]: { kind: "linked" },
114 [id("b")]: {
115 kind: "failed",
116 failure: "code_refused",
117 detail: "The peer refused the sign-in.",
118 },
119 [id("c")]: { kind: "failed", failure: "unreachable", detail: "c did not answer." },
120 [id("d")]: {
121 kind: "failed",
122 failure: "wrong_environment",
123 detail: "d answered as another environment, Impostor.",
124 },
125 [id("e")]: { kind: "failed", failure: "no_code", detail: null },
126 });
127 expect(seen.toSorted()).toEqual(machines.map((entry) => entry.environmentId));
128 expect(linkBatchSummary(outcomes)).toEqual({
129 linked: 1,
130 failed: [id("b"), id("c"), id("d"), id("e")],
131 });
132 });
133
134 it("never shows a failure that may carry the request and its pairing code", async () => {
135 const outcomes = await runLinkBatch({
136 machines: [machine("a")],
137 access: "auto",
138 mint: async () => Result.succeed("secret-code"),
139 link: async (input) => Result.fail(new Error(`request failed: ${JSON.stringify(input)}`)),
140 refreshLinks: () => {},
141 });
142 expect(outcomes.get(id("a"))).toEqual({ kind: "failed", failure: "other", detail: null });
143 });
144
145 it("opens at most four pairings at once", async () => {
146 let open = 0;
147 let most = 0;
148 await runLinkBatch({
149 machines: Array.from({ length: 10 }, (_, index) => machine(`vm-${index}`)),
150 access: "auto",
151 mint: async () => {
152 open += 1;
153 most = Math.max(most, open);
154 return Result.succeed("code");
155 },
156 link: async () => {
157 await Promise.resolve();
158 open -= 1;
159 return Result.succeed(null);
160 },
161 refreshLinks: () => {},
162 });
163 expect(most).toBe(4);
164 });
165
166 it("refreshes the links list once for the whole batch, after its last link", async () => {
167 const events: Array<string> = [];
168 const run = (names: ReadonlyArray<string>, fails: boolean) =>
169 runLinkBatch({
170 machines: names.map((name) => machine(name)),
171 access: "auto",
172 mint: async () => Result.succeed("code"),
173 link: async () => {
174 await Promise.resolve();
175 events.push("link");
176 return fails ? Result.fail(new Error("refused")) : Result.succeed(null);
177 },
178 refreshLinks: () => events.push("refresh"),
179 });
180 const names = Array.from({ length: 12 }, (_, index) => `vm-${index}`);
181 await run(names, false);
182 expect(events).toEqual([...names.map(() => "link"), "refresh"]);
183 // A retry batch is one more refresh; a batch that linked nothing changed no list.
184 await run(names.slice(0, 3), false);
185 await run(names.slice(0, 3), true);
186 expect(events.filter((event) => event === "refresh").length).toBe(2);
187 });
188 });
189
190 describe("linkBackOffer", () => {
191 const source = {
192 environmentId: id("source"),
193 connected: true,
194 writable: true,
195 urls: ["https://source.example.ts.net"],
196 };
197 const target = { connected: true, offersLinks: true, writable: true, links: [] };
198 const offer = (overrides: {
199 readonly source?: Partial<typeof source>;
200 readonly target?: Partial<Parameters<typeof linkBackOffer>[0]["target"]> | null;
201 }) =>
202 linkBackOffer({
203 source: { ...source, ...overrides.source },
204 target: overrides.target === null ? null : { ...target, ...overrides.target },
205 });
206
207 it("is offered only when the client can make the reverse link with no pasted code", () => {
208 expect(offer({})).toEqual({ kind: "offered" });
209 // An expired reverse link no longer counts: linking back renews it.
210 expect(
211 offer({ target: { links: [{ environmentId: id("source"), status: "expired" }] } }),
212 ).toEqual({ kind: "offered" });
213 expect(
214 offer({ target: { links: [{ environmentId: id("other"), status: "reachable" }] } }),
215 ).toEqual({ kind: "offered" });
216 });
217
218 it("says nothing where the user would not expect it", () => {
219 for (const hidden of [
220 offer({ target: null }),
221 offer({ target: { connected: false } }),
222 offer({ source: { connected: false } }),
223 // Not known yet, or already linked back: offering could replace a working token.
224 offer({ target: { links: null } }),
225 offer({ target: { links: [{ environmentId: id("source"), status: "reachable" }] } }),
226 offer({ target: { links: [{ environmentId: id("source"), status: "unreachable" }] } }),
227 ]) {
228 expect(hidden).toEqual({ kind: "hidden" });
229 }
230 });
231
232 it("names what is in the way between two connected environments", () => {
233 expect(offer({ target: { offersLinks: false } })).toEqual({
234 kind: "blocked",
235 reason: "target_links_off",
236 });
237 expect(offer({ target: { writable: false } })).toEqual({
238 kind: "blocked",
239 reason: "target_no_access",
240 });
241 expect(offer({ source: { writable: false } })).toEqual({
242 kind: "blocked",
243 reason: "source_no_access",
244 });
245 expect(offer({ source: { urls: [] } })).toEqual({
246 kind: "blocked",
247 reason: "source_no_address",
248 });
249 });
250 });
251
252 describe("runLinkBatch link back", () => {
253 it("links back from each eligible machine, and a reverse failure keeps the forward link", async () => {
254 const source = machine("source");
255 const reverse: Array<unknown> = [];
256 const minted: Array<string> = [];
257 const outcomes = await runLinkBatch({
258 machines: [machine("a"), machine("b"), machine("c"), machine("d")],
259 access: "full-access",
260 mint: async (environmentId) => {
261 minted.push(environmentId);
262 return Result.succeed(`code-for-${environmentId}`);
263 },
264 link: async (input) =>
265 input.expectedLabel === "d" ? Result.fail(new Error("refused")) : Result.succeed(null),
266 back: {
267 source,
268 targets: new Set([id("a"), id("b"), id("d")]),
269 link: async (environmentId, input) => {
270 reverse.push([environmentId, input]);
271 return environmentId === id("b")
272 ? Result.fail(
273 new PeerLinkError({ reason: "unreachable", message: "source did not answer." }),
274 )
275 : Result.succeed(null);
276 },
277 },
278 refreshLinks: () => {},
279 });
280 expect(Object.fromEntries(outcomes)).toEqual({
281 [id("a")]: { kind: "linked", back: { kind: "linked" } },
282 [id("b")]: {
283 kind: "linked",
284 back: { kind: "failed", failure: "unreachable", detail: "source did not answer." },
285 },
286 // Not eligible, so not attempted.
287 [id("c")]: { kind: "linked" },
288 // Its own link failed, so nothing links back.
289 [id("d")]: { kind: "failed", failure: "other", detail: null },
290 });
291 // The reverse link is made on the machine, with a code minted on the source for it.
292 expect(reverse[0]).toEqual([
293 id("a"),
294 {
295 url: "https://source.example.ts.net",
296 alternateUrls: ["http://100.64.0.1:3773"],
297 expectedEnvironmentId: id("source"),
298 expectedLabel: "source",
299 pairingCode: `code-for-${id("source")}`,
300 access: "full-access",
301 },
302 ]);
303 expect(minted.filter((environmentId) => environmentId === id("source")).length).toBe(2);
304 expect(linkBatchSummary(outcomes)).toEqual({ linked: 3, failed: [id("d")] });
305 });
306 });