Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

linkRequest.test.ts

404 lines13.9 KB

1import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts";
2import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
3import * as Option from "effect/Option";
4import { describe, expect, it } from "vite-plus/test";
5​
6import { BearerConnectionProfile } from "./connection/catalog.ts";
7import { BearerConnectionTarget, RelayConnectionTarget } from "./connection/model.ts";
8import type { EnvironmentPresentation } from "./connection/presentation.ts";
9import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
10import {
11 linkableMachines,
12 linkedEnvironmentNames,
13 linkRequestAnswerInput,
14 linkRequestDisplay,
15 linkRequestFailureMessage,
16 linkRequestInitialMachine,
17 rankMachinesByHint,
18} from "./linkRequest.ts";
19​
20const item = {
21 id: TurnItemId.make("turn-item:link-request:1"),
22 threadId: ThreadId.make("thread-1"),
23};
24const asked = { url: "https://box.example.ts.net", label: "Box" };
25const accessLabel = (access: string) => `<${access}>`;
26​
27describe("linkRequestDisplay", () => {
28 it("names the environment linked and the access the user chose", () => {
29 expect(
30 linkRequestDisplay(
31 { ...asked, linkStatus: "linked", linkedLabel: "Box", linkedAccess: "auto" },
32 "local",
33 accessLabel,
34 ),
35 ).toEqual({ kind: "answered", outcome: "linked", label: "Linked Box · <auto>" });
36 });
37​
38 it("shows why a link failed, and never offers the actions outside the asking thread", () => {
39 expect(
40 linkRequestDisplay(
41 { ...asked, linkStatus: "failed", failure: "Pairing code expired." },
42 "local",
43 accessLabel,
44 ),
45 ).toMatchObject({ outcome: "failed", label: "Could not link: Pairing code expired." });
46 expect(
47 linkRequestDisplay({ ...asked, linkStatus: "pending" }, "inherited", accessLabel),
48 ).toMatchObject({ kind: "pending-elsewhere" });
49 });
50});
51​
52describe("linkRequestAnswerInput", () => {
53 const vps = {
54 environmentId: EnvironmentId.make("environment-vps"),
55 label: "VPS",
56 urls: ["https://vps.ts.net", "http://10.0.0.2:3773"],
57 };
58​
59 it("answers with the machine picked and every address known for it", () => {
60 expect(
61 linkRequestAnswerInput(item, {
62 type: "link",
63 target: vps,
64 access: "auto",
65 pairingCode: " abc ",
66 }),
67 ).toEqual({
68 threadId: item.threadId,
69 turnItemId: item.id,
70 answer: { type: "link", ...vps, access: "auto", pairingCode: "abc" },
71 });
72 expect(
73 linkRequestAnswerInput(item, {
74 type: "link",
75 target: { url: " https://box.ts.net " },
76 access: "auto",
77 pairingCode: "abc",
78 }),
79 ).toMatchObject({ answer: { urls: ["https://box.ts.net"] } });
80 });
81​
82 it("refuses a blank code, a blank address, or a machine with no address", () => {
83 const blank = (target: Parameters<typeof linkRequestAnswerInput>[1] & { type: "link" }) =>
84 linkRequestAnswerInput(item, target);
85 expect(blank({ type: "link", target: vps, access: "auto", pairingCode: " " })).toBeNull();
86 expect(
87 blank({ type: "link", target: { url: " " }, access: "auto", pairingCode: "abc" }),
88 ).toBeNull();
89 expect(
90 blank({ type: "link", target: { ...vps, urls: [] }, access: "auto", pairingCode: "abc" }),
91 ).toBeNull();
92 });
93});
94​
95const presentation = (
96 id: string,
97 label: string,
98 options: {
99 readonly saved?: ReadonlyArray<string>;
100 readonly reported?: ReadonlyArray<string>;
101 readonly connected?: boolean;
102 } = {},
103): EnvironmentPresentation & { readonly environmentId: EnvironmentId } => {
104 const environmentId = EnvironmentId.make(id);
105 const [first, ...rest] = (options.saved ?? []).map((httpBaseUrl, index) => {
106 const connectionId = `${id}-${index}`;
107 return {
108 target: new BearerConnectionTarget({ environmentId, label, connectionId }),
109 profile: Option.some(
110 new BearerConnectionProfile({
111 connectionId,
112 environmentId,
113 label,
114 httpBaseUrl,
115 wsBaseUrl: httpBaseUrl,
116 }),
117 ),
118 };
119 });
120 return {
121 environmentId,
122 entry: {
123 ...(first ?? {
124 target: new RelayConnectionTarget({ environmentId, label }),
125 profile: Option.none(),
126 }),
127 ...(rest.length === 0 ? {} : { alternateRoutes: rest }),
128 enabled: true,
129 },
130 connection: {
131 phase: options.connected === false ? "offline" : "connected",
132 error: null,
133 traceId: null,
134 },
135 serverConfig:
136 options.reported === undefined
137 ? null
138 : ({
139 environment: { platform: { machine: "laptop" } },
140 directEndpoints: options.reported.map((httpBaseUrl) => ({
141 kind: "tailnet",
142 httpBaseUrl,
143 })),
144 } as unknown as ServerConfig),
145 };
146};
147​
148const discovered = (
149 id: string,
150 label: string,
151 machine?: "mac-mini",
152): RelayDiscoveredEnvironment => ({
153 environment: {
154 environmentId: EnvironmentId.make(id),
155 label,
156 endpoint: {
157 httpBaseUrl: `https://${id}.t3.example`,
158 wsBaseUrl: `wss://${id}.t3.example`,
159 providerKind: "cloudflare_tunnel",
160 },
161 linkedAt: "2026-10-01T00:00:00.000Z",
162 },
163 availability: "online",
164 status:
165 machine === undefined
166 ? Option.none()
167 : Option.some({
168 environmentId: EnvironmentId.make(id),
169 endpoint: {
170 httpBaseUrl: `https://${id}.t3.example`,
171 wsBaseUrl: `wss://${id}.t3.example`,
172 providerKind: "cloudflare_tunnel",
173 },
174 status: "online",
175 checkedAt: "2026-10-01T00:00:00.000Z",
176 descriptor: {
177 environmentId: EnvironmentId.make(id),
178 label,
179 platform: { os: "darwin", arch: "arm64", machine },
180 serverVersion: "1.0.0",
181 capabilities: {},
182 },
183 } as unknown as RelayEnvironmentStatusResponse),
184 error: Option.none(),
185});
186​
187describe("linkableMachines", () => {
188 it("lists the other machines with reported addresses before saved ones, once each", () => {
189 const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
190 const vps = presentation("environment-vps", "VPS", {
191 saved: ["https://vps.example.com", "https://vps.ts.net"],
192 reported: ["https://vps.ts.net"],
193 });
194 const mini = presentation("environment-mini", "Mini", { connected: false });
195 expect(
196 linkableMachines({
197 environments: [here, vps, mini],
198 threadEnvironmentId: here.environmentId,
199 links: [{ environmentId: mini.environmentId, status: "unreachable" }],
200 connect: new Map(),
201 }),
202 ).toEqual([
203 {
204 environmentId: vps.environmentId,
205 label: "VPS",
206 machine: "laptop",
207 connected: true,
208 connectOnly: false,
209 linked: false,
210 urls: ["https://vps.ts.net", "https://vps.example.com"],
211 },
212 {
213 environmentId: mini.environmentId,
214 label: "Mini",
215 machine: "server",
216 connected: false,
217 connectOnly: false,
218 linked: true,
219 urls: [],
220 },
221 ]);
222 });
223​
224 it("reaches a machine saved only over T3 Connect at its Connect address", () => {
225 const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
226 const box = presentation("environment-box", "Box");
227 const [listed] = linkableMachines({
228 environments: [here, box],
229 threadEnvironmentId: here.environmentId,
230 links: [],
231 connect: new Map([[box.environmentId, discovered(box.environmentId, "Box")]]),
232 });
233 expect(listed?.urls).toEqual(["https://environment-box.t3.example"]);
234 // Until discovery has found it, there is no address to offer.
235 expect(
236 linkableMachines({
237 environments: [here, box],
238 threadEnvironmentId: here.environmentId,
239 links: [],
240 connect: new Map(),
241 })[0]?.urls,
242 ).toEqual([]);
243 });
244​
245 it("also offers the Connect address of a machine saved by direct address, last", () => {
246 const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
247 const vps = presentation("environment-vps", "VPS", {
248 saved: ["http://192.168.1.20:3773"],
249 reported: ["https://vps.ts.net"],
250 });
251 const [listed] = linkableMachines({
252 environments: [here, vps],
253 threadEnvironmentId: here.environmentId,
254 links: [],
255 connect: new Map([[vps.environmentId, discovered(vps.environmentId, "VPS")]]),
256 });
257 expect(listed?.urls).toEqual([
258 "https://vps.ts.net",
259 "http://192.168.1.20:3773",
260 "https://environment-vps.t3.example",
261 ]);
262 });
263​
264 it("no longer counts a machine as linked once its link expired", () => {
265 const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
266 const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
267 const mini = presentation("environment-mini", "Mini", { saved: ["http://mini.local:3773"] });
268 const listed = linkableMachines({
269 environments: [here, vps, mini],
270 threadEnvironmentId: here.environmentId,
271 links: [
272 { environmentId: vps.environmentId, status: "expired" },
273 { environmentId: mini.environmentId, status: "unreachable" },
274 { environmentId: EnvironmentId.make("environment-old"), status: "expired" },
275 ],
276 connect: new Map([["environment-old", discovered("environment-old", "Old box")]]),
277 });
278 expect(listed.map((machine) => [machine.label, machine.linked])).toEqual([
279 ["VPS", false],
280 ["Mini", true],
281 ["Old box", false],
282 ]);
283 });
284​
285 it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => {
286 const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
287 const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
288 const listed = linkableMachines({
289 environments: [here, vps],
290 threadEnvironmentId: here.environmentId,
291 links: [{ environmentId: EnvironmentId.make("environment-old"), status: "reachable" }],
292 connect: new Map([
293 // This environment and saved machines are listed once, as saved.
294 [here.environmentId, discovered(here.environmentId, "Here")],
295 [vps.environmentId, discovered(vps.environmentId, "VPS")],
296 ["environment-mini", discovered("environment-mini", "Mac mini", "mac-mini")],
297 ["environment-old", discovered("environment-old", "Old box")],
298 ]),
299 });
300 expect(listed.map((machine) => [machine.label, machine.connectOnly])).toEqual([
301 ["VPS", false],
302 ["Mac mini", true],
303 ["Old box", true],
304 ]);
305 expect(listed[1]).toEqual({
306 environmentId: EnvironmentId.make("environment-mini"),
307 label: "Mac mini",
308 machine: "mac-mini",
309 connected: false,
310 connectOnly: true,
311 linked: false,
312 urls: ["https://environment-mini.t3.example"],
313 });
314 expect(listed[2]).toMatchObject({ machine: "server", linked: true });
315 });
316});
317​
318describe("linkedEnvironmentNames", () => {
319 it("names the unexpired links as this client does, else as the link does", () => {
320 const vps = EnvironmentId.make("environment-vps");
321 const mini = EnvironmentId.make("environment-mini");
322 const unsaved = EnvironmentId.make("environment-unsaved");
323 expect(
324 linkedEnvironmentNames({
325 links: [
326 { environmentId: vps, label: "vps-01", status: "unreachable" },
327 { environmentId: mini, label: "mini", status: "expired" },
328 { environmentId: unsaved, label: "Office box", status: "reachable" },
329 ],
330 environments: [
331 { environmentId: vps, label: "Hetzner VPS" },
332 { environmentId: mini, label: "Mac mini" },
333 ],
334 }),
335 ).toEqual(
336 new Map([
337 [vps, "Hetzner VPS"],
338 [unsaved, "Office box"],
339 ]),
340 );
341 });
342});
343​
344describe("rankMachinesByHint", () => {
345 const machines = [
346 { label: "Old vps box" },
347 { label: "VPS-2" },
348 { label: "Mac mini" },
349 { label: "vps" },
350 ];
351​
352 it("puts an exact name first, then a prefix, then a substring, keeping order within each", () => {
353 expect(rankMachinesByHint(machines, " VPS ").map((machine) => machine.label)).toEqual([
354 "vps",
355 "VPS-2",
356 "Old vps box",
357 "Mac mini",
358 ]);
359 expect(rankMachinesByHint(machines, undefined)).toBe(machines);
360 });
361​
362 it("preselects the card's machine, or the hint's match, and nothing for a hint that matches none", () => {
363 const listed = [
364 { environmentId: EnvironmentId.make("environment-mini"), label: "Mac mini" },
365 { environmentId: EnvironmentId.make("environment-vps"), label: "Hetzner VPS" },
366 ].map(
367 (machine) =>
368 ({
369 ...machine,
370 machine: "server",
371 connected: true,
372 connectOnly: false,
373 linked: false,
374 urls: [],
375 }) as const,
376 );
377 expect(linkRequestInitialMachine({ hint: "vps" }, listed)).toBe("environment-vps");
378 // Agents pass the user's words, which name the machine among others.
379 expect(linkRequestInitialMachine({ hint: "my mac mini" }, listed)).toBe("environment-mini");
380 expect(linkRequestInitialMachine({ hint: "my mac" }, listed)).toBe("environment-mini");
381 expect(linkRequestInitialMachine({ hint: "the hetzner vps box" }, listed)).toBe(
382 "environment-vps",
383 );
384 expect(linkRequestInitialMachine({ hint: "desk" }, listed)).toBeNull();
385 expect(linkRequestInitialMachine({ hint: "minimal" }, listed)).toBeNull();
386 expect(
387 linkRequestInitialMachine(
388 { environmentId: EnvironmentId.make("environment-x"), hint: "vps" },
389 listed,
390 ),
391 ).toBe("environment-x");
392 });
393});
394​
395describe("linkRequestFailureMessage", () => {
396 it("passes through only known user-facing errors", () => {
397 expect(
398 linkRequestFailureMessage({ _tag: "PeerLinkRequestError", message: "Already answered." }),
399 ).toBe("Already answered.");
400 expect(linkRequestFailureMessage({ _tag: "SchemaError", message: "code=abc" })).toBe(
401 "Could not answer the request. Try again.",
402 );
403 });
404});