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