@devries-cameron20 / t3code-1 / commits / b1bc5ce20f
Fork 0

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

fix(server): linking says why each address failed discovery (#30884)

Julius Marminge committed Nov 12, 2026 at 19:32 UTC b1bc5ce20f33442daa194002f338fcf52f4dbb62
2 files changed +82 -44
apps/server/src/peer/PeerLinks.test.ts
+24 -1
@@ -742,7 +742,7 @@ it.effect("linking a picked machine that answers nowhere names it and links noth
742 .pipe(Effect.flip);
743 expect(failed.reason).toBe("unreachable");
744 expect(failed.message).toBe(
745 - `This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
745 + `This environment could not reach Box: ${new URL(impostor.url).origin} answered as another environment, Impostor. http://192.168.1.20:3773 is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
746 );
747 expect(yield* a.links.list).toEqual([]);
748 expect(yield* linkedSessions(impostor)).toEqual([]);
@@ -763,6 +763,29 @@ it.effect("linking a picked machine that answers nowhere names it and links noth
763 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
764 );
765
766 +it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () =>
767 + Effect.scoped(
768 + Effect.gen(function* () {
769 + const closed = yield* Effect.scoped(
770 + serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
771 + );
772 + const notT3 = yield* serveRaw(() =>
773 + Effect.succeed(
774 + HttpServerResponse.text("<h1>Not Found</h1>", { status: 404, contentType: "text/html" }),
775 + ),
776 + );
777 + const a = yield* makeA(laptop);
778 + const linking = (url: string) =>
779 + a.links.link({ url, pairingCode: "unused", access: "auto" }).pipe(Effect.flip);
780 + expect((yield* linking(closed)).message).toBe(`${closed} did not answer (ECONNREFUSED).`);
781 + expect((yield* linking(notT3)).message).toBe(
782 + `${notT3} answered, but not as a T3 Code environment this version understands.`,
783 + );
784 + expect(yield* a.links.list).toEqual([]);
785 + }),
786 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
787 +);
788 +
789 /** An https listener whose certificate this machine does not trust. */
790 const serveUntrusted = Layer.build(
791 Layer.fresh(
apps/server/src/peer/PeerLinks.ts
+58 -43
@@ -5,7 +5,6 @@ import {
5 EnvironmentHttpApi,
6 EnvironmentId,
7 type ExecutionEnvironmentCapabilities,
8 - type ExecutionEnvironmentDescriptor,
8 MCP_PEER_LINK_SOFTWARE_ID,
9 type PeerLink,
10 type PeerLinkCreateInput,
@@ -13,6 +12,7 @@ import {
12 type PeerLinkSummary,
13 } from "@t3tools/contracts";
14 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
15 +import * as Cause from "effect/Cause";
16 import * as Context from "effect/Context";
17 import * as Digest from "effect/crypto/Digest";
18 import * as SecureRandom from "effect/crypto/SecureRandom";
@@ -31,6 +31,7 @@ import * as Schema from "effect/Schema";
31 import * as SqlClient from "effect/sql/SqlClient";
32 import * as FetchHttpClient from "effect/http/FetchHttpClient";
33 import * as HttpClient from "effect/http/HttpClient";
34 +import * as HttpClientError from "effect/http/HttpClientError";
35 import * as HttpApi from "effect/http-api/HttpApi";
36 import * as HttpApiClient from "effect/http-api/HttpApiClient";
37 import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
@@ -176,6 +177,38 @@ const peerOrigin = (url: string) => {
177 return Effect.succeed(parsed.origin);
178 };
179
180 +/** The system error under a failed connection, such as ECONNREFUSED or ENOTFOUND. */
181 +const connectionCode = (cause: unknown) =>
182 + [cause, Predicate.hasProperty(cause, "cause") ? cause.cause : undefined]
183 + .map((error) => (Predicate.hasProperty(error, "code") ? error.code : undefined))
184 + .find(Predicate.isString);
185 +
186 +/** Why `origin` did not answer as T3 Code, short enough for a toast. Never echoes a body. */
187 +const probeFailure = (
188 + origin: string,
189 + error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError,
190 + timeout: Duration.Duration,
191 +) => {
192 + const unreachable = (message: string) => new PeerLinkError({ reason: "unreachable", message });
193 + const certificate = certificateErrorCode(error);
194 + if (certificate !== undefined) {
195 + return unreachable(`${origin} presented a certificate this machine rejected (${certificate}).`);
196 + }
197 + if (Cause.isTimeoutError(error)) {
198 + return unreachable(`${origin} did not answer within ${Duration.toSeconds(timeout)} seconds.`);
199 + }
200 + if (HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError") {
201 + const code = connectionCode(error.reason.cause);
202 + return unreachable(
203 + code === undefined ? `${origin} did not answer.` : `${origin} did not answer (${code}).`,
204 + );
205 + }
206 + return new PeerLinkError({
207 + reason: "not_a_t3_environment",
208 + message: `${origin} answered, but not as a T3 Code environment this version understands.`,
209 + });
210 +};
211 +
212 /** Whether a host is this machine's own loopback. Tests serve their peers there, so they narrow it. */
213 export const LoopbackHost = Context.Reference<(host: string) => boolean>(
214 "t3/peer/PeerLinks/LoopbackHost",
@@ -217,13 +250,10 @@ const make = Effect.gen(function* () {
250 Effect.provideService(HttpClient.HttpClient, peerHttpClient),
251 );
252
220 - /**
221 - * The environment answering at `origin`, or nothing when it does not answer
222 - * as T3 Code. A certificate this machine rejects fails instead, since
223 - * the peer may well be there.
224 - */
225 - const describe = (origin: string) =>
226 - clientFor(origin).pipe(
253 + /** The environment answering at `origin`, or why nothing there answers as T3 Code. */
254 + const probe = (origin: string) => {
255 + const timeout = probeTimeout(origin);
256 + return clientFor(origin).pipe(
257 Effect.flatMap((client) => client.metadata.descriptor()),
258 // A brief network drop must not list a live peer as down; the timeout still bounds both tries.
259 Effect.retry({
@@ -231,27 +261,18 @@ const make = Effect.gen(function* () {
261 schedule: Schedule.spaced("1 second"),
262 while: (error) => certificateErrorCode(error) === undefined,
263 }),
234 - Effect.timeout(probeTimeout(origin)),
235 - Effect.asSome,
236 - Effect.catch((error) => {
237 - const code = certificateErrorCode(error);
238 - return code === undefined
239 - ? Effect.succeed(Option.none<ExecutionEnvironmentDescriptor>())
240 - : Effect.fail(
241 - new PeerLinkError({
242 - reason: "unreachable",
243 - message: `${origin} presented a certificate this machine rejected (${code}).`,
244 - }),
245 - );
246 - }),
264 + Effect.timeout(timeout),
265 + // No cause: a decode error can carry the response body to the client.
266 + Effect.mapError((error) => probeFailure(origin, error, timeout)),
267 );
268 + };
269
249 - /** Whether `url` answers as `environmentId`, counting an untrusted certificate as no. */
270 + /** Whether `url` answers as `environmentId`, counting any failure as no. */
271 const answersAs = Effect.fn("PeerLinks.answersAs")(function* (
272 url: string,
273 environmentId: EnvironmentId,
274 ) {
254 - const found = yield* describe(url).pipe(Effect.orElseSucceed(() => Option.none()));
275 + const found = yield* probe(url).pipe(Effect.option);
276 return Option.filter(found, (peer) => peer.environmentId === environmentId);
277 });
278
@@ -404,7 +425,8 @@ const make = Effect.gen(function* () {
425 /**
426 * The addresses that answer as `environmentId`, in the order given, with
427 * what the first one answered. Addresses this environment would not send
407 - * credentials to are skipped; when every one is, the failure says why.
428 + * credentials to are skipped; when none answers as it, the failure says why
429 + * for each.
430 */
431 const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
432 urls: ReadonlyArray<string>,
@@ -423,28 +445,28 @@ const make = Effect.gen(function* () {
445 message: `${origin} is this machine, not ${name}.`,
446 });
447 }
426 - return { origin, descriptor: yield* describe(origin) };
448 + const descriptor = yield* probe(origin);
449 + if (descriptor.environmentId !== environmentId) {
450 + return yield* new PeerLinkError({
451 + reason: "unreachable",
452 + message: `${origin} answered as another environment, ${descriptor.label}.`,
453 + });
454 + }
455 + return { origin, descriptor };
456 }).pipe(Effect.result),
457 { concurrency: "unbounded" },
458 );
459 const matching = checked.flatMap((result) =>
431 - Result.isSuccess(result) &&
432 - Option.isSome(result.success.descriptor) &&
433 - result.success.descriptor.value.environmentId === environmentId
434 - ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }]
435 - : [],
460 + Result.isSuccess(result) ? [result.success] : [],
461 );
462 const first = matching[0];
463 if (first === undefined) {
439 - const refusals = checked.flatMap((result) =>
464 + const reasons = checked.flatMap((result) =>
465 Result.isFailure(result) ? [result.failure.message] : [],
466 );
467 return yield* new PeerLinkError({
468 reason: "unreachable",
444 - message:
445 - refusals.length === checked.length
446 - ? `This environment could not reach ${name}: ${refusals.join(" ")}`
447 - : `This environment could not reach ${name} at ${urls.join(", ")}.`,
469 + message: `This environment could not reach ${name}: ${reasons.join(" ")}`,
470 });
471 }
472 // Each address is kept once, even when two spellings share an origin.
@@ -456,14 +478,7 @@ const make = Effect.gen(function* () {
478 const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
479 const origins = yield* Effect.forEach(urls, peerOrigin);
480 const primary = origins[0]!;
459 - const descriptor = yield* describe(primary);
460 - if (Option.isNone(descriptor)) {
461 - return yield* new PeerLinkError({
462 - reason: "not_a_t3_environment",
463 - message: `Nothing at ${primary} answered as a T3 Code environment.`,
464 - });
465 - }
466 - return { primary, peer: descriptor.value, origins };
481 + return { primary, peer: yield* probe(primary), origins };
482 });
483
484 const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {