TypeScript
feat(connect): t3 connect checks that other devices can reach this machine (#22172)
Theo Browne91d7bf3eefec
diff --git a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsxindex 0fbfd68b480..df0e8c16592 100644--- a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx+++ b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx@@ -12,7 +12,7 @@ import type { EnvironmentId } from "@t3tools/contracts";import Constants from "expo-constants";import * as Option from "effect/Option";import { AsyncResult } from "effect/reactivity";-import { View } from "react-native";+import { Linking, View } from "react-native";import { AppText as Text } from "../../components/ui/AppText";import { Button } from "../../components/ui/Button";@@ -52,6 +52,7 @@ export function ConnectionDiagnosisDetails(props: {readonly diagnosis: ConnectionDiagnosis;}) {const { diagnosis } = props;+ const { moreInfoUrl } = diagnosis;return (<View className="gap-3"><View className="gap-0.5">@@ -87,6 +88,14 @@ export function ConnectionDiagnosisDetails(props: {});}}/>+ {moreInfoUrl ? (+ <Button+ label="More info"+ icon="safari"+ tone="secondary"+ onPress={() => void Linking.openURL(moreInfoUrl).catch(() => undefined)}+ />+ ) : null}</View>);}diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.tsindex 9cc59335115..94f338cef08 100644--- a/apps/server/src/cli/connect.ts+++ b/apps/server/src/cli/connect.ts@@ -1,6 +1,10 @@import {+ AuthRelayReadScope,AuthRelayWriteScope,+ type AuthEnvironmentScope,+ type EnvironmentConnectReachability,EnvironmentHttpApi,+ formatConnectReachable,type RelayClientInstallProgressEvent,type RelayClientInstallProgressStage,} from "@t3tools/contracts";@@ -9,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";import * as RelayClient from "@t3tools/shared/relayClient";import { withRelayClientTracing } from "@t3tools/shared/relayTracing";import * as Cause from "effect/Cause";+import * as Clock from "effect/Clock";import * as Config from "effect/Config";import * as Console from "effect/Console";import * as Crypto from "effect/Crypto";@@ -29,6 +34,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as BootService from "../cloud/bootService.ts";import * as CliState from "../cloud/CliState.ts";import * as CliTokenManager from "../cloud/CliTokenManager.ts";+import { formatReachabilityFailure } from "../cloud/ConnectReachability.ts";import { filterRelayResponse } from "../cloud/relayResponse.ts";import {CLOUD_LINK_REVOKED,@@ -142,6 +148,9 @@ interface CloudCliStatus {readonly relayUrl: string | null;readonly publishAgentActivity: boolean;readonly relayClient: RelayClient.RelayClientStatus;+ readonly linkMode: CliState.CliDesiredLinkMode;+ /** `null` when no server answered the live check, or none ran because no tunnel is wanted. */+ readonly reachability: EnvironmentConnectReachability | null;}function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {@@ -199,8 +208,19 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b` Relay: ${status.relayUrl ?? "not provisioned"}`,` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,...formatRelayClientStatus(status.relayClient),- "",- "This is saved setup, not a live connection check. Check the background service with `t3 service status`.",+ ...(!status.desired || status.linkMode !== "managed"+ ? []+ : status.reachability === null+ ? [+ "",+ "No running server answered, so reachability was not checked. Check the background service with `t3 service status`.",+ ]+ : status.reachability.status === "reachable"+ ? [+ "",+ `✓ Other devices can reach this machine · ${formatConnectReachable(status.reachability)}`,+ ]+ : ["", formatReachabilityFailure(status.reachability)]),...(nextStep ? ["", `Next: ${nextStep}`] : []),].join("\n");}@@ -261,11 +281,12 @@ export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_clieconst withCloudCliSessionToken = <A, E, R>(environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],+ scope: AuthEnvironmentScope,run: (token: string) => Effect.Effect<A, E, R>,) =>Effect.acquireUseRelease(environmentAuth.issueSession({- scopes: [AuthRelayWriteScope],+ scopes: [scope],subject: "cloud-cli",label: "t3 connect cli",}),@@ -287,7 +308,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;const result = yield* Effect.exit(- withCloudCliSessionToken(environmentAuth, (token) =>+ withCloudCliSessionToken(environmentAuth, AuthRelayWriteScope, (token) =>HttpApiClient.make(EnvironmentHttpApi, {baseUrl: runtimeState.value.origin,}).pipe(@@ -303,6 +324,73 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {: ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);});+// One check probes the endpoint, the tunnel edge, and Tailscale, each with its own timeout.+const CLOUD_CLI_REACHABILITY_TIMEOUT = Duration.seconds(30);+const CLOUD_CLI_REACHABILITY_WAIT = Duration.seconds(60);+const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5);++/** Asks the running server to check T3 Connect now. `null` when no server answers. */+const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);+ if (Option.isNone(runtimeState)) return null;+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;+ return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>+ HttpApiClient.make(EnvironmentHttpApi, { baseUrl: runtimeState.value.origin }).pipe(+ Effect.flatMap((client) =>+ client.connect.checkReachability({ headers: { authorization: `Bearer ${token}` } }),+ ),+ Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),+ ),+ ).pipe(Effect.orElseSucceed(() => null));+});++function formatAlertBox(text: string): string {+ const lines = text.split("\n");+ const width = Math.max(...lines.map((line) => line.length));+ const color = process.stdout.isTTY === true && !process.env.NO_COLOR;+ const red = (line: string) => (color ? `\x1b[1;31m${line}\x1b[0m` : line);+ return [+ `┌${"─".repeat(width + 2)}┐`,+ ...lines.map((line) => `│ ${line.padEnd(width)} │`),+ `└${"─".repeat(width + 2)}┘`,+ ]+ .map(red)+ .join("\n");+}++/**+ * Waits for the server that `t3 connect` just started to prove other devices+ * can reach it, so a broken tunnel fails setup instead of looking green.+ */+const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {+ yield* Console.log("\nChecking that other devices can reach this machine...");+ const deadline =+ (yield* Clock.currentTimeMillis) + Duration.toMillis(CLOUD_CLI_REACHABILITY_WAIT);+ let last: EnvironmentConnectReachability | null = null;+ while (true) {+ last = (yield* checkLiveReachability()) ?? last;+ if (last?.status === "reachable") {+ yield* Console.log(+ `✓ Other devices can reach this machine · ${formatConnectReachable(last)}`,+ );+ return;+ }+ if ((yield* Clock.currentTimeMillis) >= deadline) break;+ yield* Effect.sleep(CLOUD_CLI_REACHABILITY_RETRY);+ }+ yield* Console.error(+ formatAlertBox(+ last === null+ ? "✕ Could not check T3 Connect\n The T3 server on this machine did not answer.\n Fix: run `t3 service status`, then `t3 connect status`."+ : formatReachabilityFailure(last),+ ),+ );+ yield* Effect.sync(() => {+ process.exitCode = 1;+ });+});+type RelayUnlinkResult =| { readonly status: "not-authenticated" }| { readonly status: "revoked" }@@ -551,7 +639,9 @@ const connectStatusCommand = Command.make("status", {...projectLocationFlags,json: jsonFlag,}).pipe(- Command.withDescription("Show persisted T3 Connect and relay client state."),+ Command.withDescription(+ "Show T3 Connect setup and check that other devices can reach this machine.",+ ),Command.withHandler((flags) =>runCloudCommand(flags,@@ -567,6 +657,7 @@ const connectStatusCommand = Command.make("status", {publishAgentActivity,revoked,executable,+ linkMode,] = yield* Effect.all([CliState.readCliDesiredCloudLink,@@ -576,9 +667,13 @@ const connectStatusCommand = Command.make("status", {secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),secrets.get(CLOUD_LINK_REVOKED),relayClient.resolve,+ CliState.readCliDesiredLinkMode,],{ concurrency: "unbounded" },);+ // A publish-only link has no tunnel for other devices to reach.+ const reachability =+ desired && linkMode === "managed" ? yield* checkLiveReachability() : null;const status: CloudCliStatus = {desired,authenticated,@@ -590,6 +685,8 @@ const connectStatusCommand = Command.make("status", {Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,),relayClient: executable,+ linkMode,+ reachability,};yield* Console.log(formatCloudStatus(status, { json: flags.json }));}),@@ -703,7 +800,7 @@ export const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onb}const serveCommand = yield* resolveCliCommand("serve");yield* Console.log(- `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,+ `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.\n It checks that other devices can reach this machine when it starts.`,);},);@@ -724,9 +821,13 @@ export const connectCommand = Command.make("connect", {}yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);- yield* reportServiceOnboarding(- yield* CliService.recoverServiceOnboardingOffer(CliService.offerServiceDuringOnboarding),+ const outcome = yield* CliService.recoverServiceOnboardingOffer(+ CliService.offerServiceDuringOnboarding,);+ yield* reportServiceOnboarding(outcome);+ if (outcome !== "skipped") {+ yield* waitForReachability();+ }}),),),diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.tsindex fea003fe3d5..653a3ce0771 100644--- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts+++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts@@ -43,6 +43,7 @@ import {RELAY_URL_SECRET,} from "./config.ts";import * as CloudLink from "./CloudLink.ts";+import * as ConnectReachability from "./ConnectReachability.ts";import { consumeCloudReplayGuards } from "./CloudLink.ts";import { pendingServiceUpdateExists } from "./updateHandoff.ts";import {@@ -154,6 +155,13 @@ describe("reconcileDesiredCloudLink", () => {expect(error._tag).toBe("CloudLinkAuthorizationMissingError");}).pipe(Effect.provide(CloudLink.layer),+ Effect.provideService(+ ConnectReachability.ConnectReachability,+ ConnectReachability.ConnectReachability.of({+ check: Effect.die("unused"),+ latest: Effect.succeed(Option.none()),+ }),+ ),Effect.provideService(HttpServer.HttpServer, idleHttpServer),Effect.provideService(ServerConfigModule.ServerConfig,@@ -177,6 +185,8 @@ describe("reconcileDesiredCloudLink", () => {recoveryRequests: Stream.empty,requestRecovery: () => Effect.void,tunnelConnected: Stream.empty,+ inspectConnector: Effect.succeed(null),+ readinessChanged: Stream.empty,withLinkStateLock: (effect) => effect,} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),),@@ -276,6 +286,13 @@ describe("releaseManagedTunnelOnShutdown", () => {<A, E, R>(effect: Effect.Effect<A, E, R>) =>effect.pipe(Effect.provide(CloudLink.layer),+ Effect.provideService(+ ConnectReachability.ConnectReachability,+ ConnectReachability.ConnectReachability.of({+ check: Effect.die("unused"),+ latest: Effect.succeed(Option.none()),+ }),+ ),Effect.provideService(HttpServer.HttpServer, {...idleHttpServer,address: harness.address ?? idleHttpServer.address,@@ -308,6 +325,8 @@ describe("releaseManagedTunnelOnShutdown", () => {recoveryRequests: Stream.empty,requestRecovery: () => Effect.void,tunnelConnected: Stream.empty,+ inspectConnector: Effect.succeed(null),+ readinessChanged: Stream.empty,withLinkStateLock: (effect) => effect,}),),diff --git a/apps/server/src/cloud/CloudLink.test.ts b/apps/server/src/cloud/CloudLink.test.tsindex 0f2de771777..db945509a56 100644--- a/apps/server/src/cloud/CloudLink.test.ts+++ b/apps/server/src/cloud/CloudLink.test.ts@@ -16,6 +16,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";import * as CliTokenManager from "./CliTokenManager.ts";import * as CloudLink from "./CloudLink.ts";+import * as ConnectReachability from "./ConnectReachability.ts";import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";import {HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,@@ -94,6 +95,9 @@ const withService = <A, E>(}),Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }),Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),+ Layer.mock(ConnectReachability.ConnectReachability)({+ latest: Effect.succeed(Option.none()),+ }),Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),Layer.mock(CliTokenManager.CloudCliTokenManager)({}),Layer.mock(HttpServer.HttpServer)({diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.tsindex 12d6aee4931..9cab063ef67 100644--- a/apps/server/src/cloud/CloudLink.ts+++ b/apps/server/src/cloud/CloudLink.ts@@ -96,6 +96,7 @@ import {RELAY_URL_SECRET,} from "./config.ts";import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";+import * as ConnectReachability from "./ConnectReachability.ts";import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";import { relayUrlConfig } from "./publicConfig.ts";import {@@ -529,6 +530,7 @@ const make = Effect.gen(function* () {const secrets = yield* ServerSecretStore.ServerSecretStore;const environment = yield* ServerEnvironment.ServerEnvironment;const endpointRuntime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;+ const reachability = yield* ConnectReachability.ConnectReachability;const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;const cliTokenManager = yield* CliTokenManager.CloudCliTokenManager;const httpClient = yield* HttpClient.HttpClient;@@ -1314,6 +1316,7 @@ const make = Effect.gen(function* () {publishAgentActivity,holdWebhooks,revoked,+ latestReachability,] = yield* Effect.all([secrets.get(CLOUD_LINKED_USER_ID),@@ -1323,8 +1326,9 @@ const make = Effect.gen(function* () {secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),secrets.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET),secrets.get(CLOUD_LINK_REVOKED),+ reachability.latest,],- { concurrency: 7 },+ { concurrency: 8 },);return {linked: Option.isSome(cloudUserId),@@ -1338,6 +1342,7 @@ const make = Effect.gen(function* () {: false,holdWebhooksWhileOffline:Option.isSome(holdWebhooks) && bytesToString(holdWebhooks.value) === "true",+ ...(Option.isSome(latestReachability) ? { reachability: latestReachability.value } : {}),} satisfies EnvironmentCloudLinkStateResult;});diff --git a/apps/server/src/cloud/ConnectReachability.test.ts b/apps/server/src/cloud/ConnectReachability.test.tsnew file mode 100644index 00000000000..daf838c4748--- /dev/null+++ b/apps/server/src/cloud/ConnectReachability.test.ts@@ -0,0 +1,153 @@+// @effect-diagnostics nodeBuiltinImport:off - reads the user guide to check its anchors.+import * as NodeFS from "node:fs";++import { formatConnectReachable, T3_CONNECT_TROUBLESHOOTING_SECTIONS } from "@t3tools/contracts";+import { describe, expect, it } from "@effect/vitest";++import {+ classifyReachability,+ formatReachabilityFailure,+ type ReachabilityFacts,+} from "./ConnectReachability.ts";++const checkedAt = "2026-10-19T00:00:00.000Z";+const connected = { readyConnections: 4, hostname: "env.example.test", protocol: "quic" };+const notConnected = { readyConnections: 0, hostname: null, protocol: null };+const facts = (overrides: Partial<ReachabilityFacts>): ReachabilityFacts => ({+ managedTunnelConfigured: true,+ connector: connected,+ endpoint: null,+ edgeReachable: null,+ exitNode: null,+ ...overrides,+});++describe("classifyReachability", () => {+ it("blames the exit node when the tunnel edge times out through it", () => {+ const result = classifyReachability(+ facts({+ connector: notConnected,+ edgeReachable: false,+ exitNode: { name: "home-pi", online: true },+ }),+ checkedAt,+ );++ expect(result.status === "unreachable" && formatReachabilityFailure(result)).toBe(+ [+ "✕ T3 Connect is NOT reachable from other devices",+ " Cloudflare's tunnel port (7844) times out from this machine.",+ ' Tailscale exit node "home-pi" is on. Traffic to Cloudflare goes through it.',+ " Fix: tailscale set --exit-node= (or allow outbound 7844 on that network)",+ " More info: https://github.com/pingdotgg/t3code/blob/main/docs/user/t3-connect-troubleshooting.md#port-7844-is-blocked-on-the-host",+ ].join("\n"),+ );+ });++ it("names a generic blocker when no exit node is on", () => {+ const result = classifyReachability(+ facts({ connector: notConnected, edgeReachable: false }),+ checkedAt,+ );++ expect(result).toMatchObject({+ cause: "edge_unreachable",+ hint: "A VPN, proxy, or firewall may block it.",+ });+ });++ it.each([+ [{ kind: "status", status: 502 }, "origin_unreachable"],+ [{ kind: "status", status: 530 }, "no_connector"],+ [{ kind: "status", status: 404 }, "unexpected_response"],+ [{ kind: "dns_failed" }, "dns_failed"],+ [{ kind: "network_error" }, "timeout"],+ ] as const)("maps endpoint result %o to %s", (endpoint, cause) => {+ expect(classifyReachability(facts({ endpoint, edgeReachable: true }), checkedAt)).toMatchObject(+ { status: "unreachable", cause },+ );+ });++ it("keeps the endpoint cause when the TCP edge test cannot explain it", () => {+ // QUIC (UDP) can connect while TCP 7844 is blocked.+ expect(+ classifyReachability(+ facts({ endpoint: { kind: "status", status: 502 }, edgeReachable: false }),+ checkedAt,+ ),+ ).toMatchObject({ cause: "origin_unreachable" });+ expect(+ classifyReachability(+ facts({+ connector: { readyConnections: null, hostname: "env.example.test", protocol: null },+ endpoint: { kind: "status", status: 502 },+ edgeReachable: false,+ }),+ checkedAt,+ ),+ ).toMatchObject({ cause: "origin_unreachable" });+ // Failed DNS also fails the edge lookups.+ expect(+ classifyReachability(+ facts({+ connector: { readyConnections: null, hostname: "env.example.test", protocol: null },+ endpoint: { kind: "dns_failed" },+ edgeReachable: false,+ }),+ checkedAt,+ ),+ ).toMatchObject({ cause: "dns_failed" });+ });++ it("waits on a connector that has not connected while the edge answers", () => {+ expect(+ classifyReachability(facts({ connector: notConnected, edgeReachable: true }), checkedAt),+ ).toMatchObject({ cause: "connector_not_ready" });+ });++ it("reports connections and protocol when the endpoint answers", () => {+ expect(+ classifyReachability(facts({ endpoint: { kind: "status", status: 200 } }), checkedAt),+ ).toEqual({ status: "reachable", checkedAt, readyConnections: 4, protocol: "quic" });+ });++ it("leaves out the connection count when cloudflared did not report one", () => {+ const result = classifyReachability(+ facts({+ connector: { readyConnections: null, hostname: "env.example.test", protocol: null },+ endpoint: { kind: "status", status: 200 },+ }),+ checkedAt,+ );+ expect(result.status === "reachable" && formatConnectReachable(result)).toBe(+ "Tunnel connected",+ );+ });++ it("does not probe a tunnel that was never set up", () => {+ expect(+ classifyReachability(facts({ managedTunnelConfigured: false, connector: null }), checkedAt),+ ).toMatchObject({ cause: "not_linked" });+ });+});++describe("T3 Connect troubleshooting links", () => {+ it("each section names a heading in the user guide", () => {+ const guide = NodeFS.readFileSync(+ new URL("../../../../docs/user/t3-connect-troubleshooting.md", import.meta.url),+ "utf8",+ );+ // GitHub's heading anchors: lowercase, drop punctuation, spaces become hyphens.+ const anchors = new Set(+ [...guide.matchAll(/^#{2,3} (.+)$/gm)].map(([, heading]) =>+ heading!+ .toLowerCase()+ .replace(/[^\p{L}\p{N} _-]/gu, "")+ .replace(/ /g, "-"),+ ),+ );+ for (const section of T3_CONNECT_TROUBLESHOOTING_SECTIONS) {+ expect(anchors, section).toContain(section);+ }+ });+});diff --git a/apps/server/src/cloud/ConnectReachability.ts b/apps/server/src/cloud/ConnectReachability.tsnew file mode 100644index 00000000000..17e78f4be17--- /dev/null+++ b/apps/server/src/cloud/ConnectReachability.ts@@ -0,0 +1,312 @@+import * as NodeNet from "node:net";++import {+ connectReachabilityHelpUrl,+ type EnvironmentConnectReachability,+ formatConnectReachable,+} from "@t3tools/contracts";+import { readTailscaleExitNode, type TailscaleExitNode } from "@t3tools/tailscale";+import * as Context from "effect/Context";+import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Ref from "effect/Ref";+import * as Stream from "effect/Stream";+import { HttpClient } from "effect/http";+import { ChildProcessSpawner } from "effect/process";++import * as ServerSecretStore from "../auth/ServerSecretStore.ts";+import { CLOUD_ENDPOINT_RUNTIME_CONFIG } from "./config.ts";+import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";++// cloudflared finds the edge through the SRV record `_v2-origintunneld._tcp.argotunnel.com`,+// which names these two hosts on port 7844. QUIC and HTTP/2 both use that port.+const TUNNEL_EDGE_HOSTS = ["region1.v2.argotunnel.com", "region2.v2.argotunnel.com"];+const TUNNEL_EDGE_PORT = 7844;+const EDGE_CONNECT_TIMEOUT = Duration.seconds(5);+const ENDPOINT_REQUEST_TIMEOUT = Duration.seconds(10);+// cloudflared registers several connections within a few seconds; they are one change.+const READINESS_CHANGE_DEBOUNCE = Duration.seconds(3);+// Readiness changes miss failures and recoveries past cloudflared (DNS, origin, edge errors).+const RECHECK_INTERVAL = Duration.minutes(5);++export type EndpointProbe =+ | { readonly kind: "status"; readonly status: number }+ | { readonly kind: "dns_failed" | "timeout" | "network_error" };++/** Everything one check learned. `null` means that step did not run. */+export interface ReachabilityFacts {+ readonly managedTunnelConfigured: boolean;+ readonly connector: ManagedEndpointRuntime.ConnectorFacts | null;+ readonly endpoint: EndpointProbe | null;+ readonly edgeReachable: boolean | null;+ readonly exitNode: TailscaleExitNode | null;+}++type Unreachable = Extract<EnvironmentConnectReachability, { status: "unreachable" }>;++function exitNodeHint(exitNode: TailscaleExitNode | null): string | null {+ if (!exitNode) return null;+ const name = exitNode.name ? ` "${exitNode.name}"` : "";+ return `Tailscale exit node${name} is on. Traffic to Cloudflare goes through it.`;+}++/** Turns what one check learned into the answer every surface shows. */+export function classifyReachability(+ facts: ReachabilityFacts,+ checkedAt: string,+): EnvironmentConnectReachability {+ const { connector, endpoint, exitNode } = facts;+ const fail = (+ cause: Unreachable["cause"],+ reason: string,+ fix: string,+ hint: string | null = null,+ ): Unreachable => ({ status: "unreachable", checkedAt, cause, reason, hint, fix });+ const restart = "Restart T3 Code. If it stays, run `t3 connect` again.";++ if (!facts.managedTunnelConfigured) {+ return fail(+ "not_linked",+ "The server has not set up a T3 Connect tunnel.",+ "Run `t3 connect`, then restart the server (`t3 service restart`) so it applies the link.",+ );+ }+ if (connector === null) {+ return fail(+ "connector_not_running",+ "The tunnel client (cloudflared) is not running.",+ "Restart T3 Code. If it stays down, check the server log for relay client errors.",+ );+ }+ const status = endpoint?.kind === "status" ? endpoint.status : null;+ if (status === 200) {+ return {+ status: "reachable",+ checkedAt,+ readyConnections: connector.readyConnections,+ protocol: connector.protocol,+ };+ }+ // The edge test is TCP only. With QUIC connections up, a 502 from a working tunnel, or+ // DNS already failing, a failed TCP test would hide the real cause.+ if (+ facts.edgeReachable === false &&+ status !== 502 &&+ !(connector.readyConnections && connector.readyConnections > 0) &&+ endpoint?.kind !== "dns_failed"+ ) {+ return fail(+ "edge_unreachable",+ `Cloudflare's tunnel port (${TUNNEL_EDGE_PORT}) times out from this machine.`,+ exitNode+ ? `tailscale set --exit-node= (or allow outbound ${TUNNEL_EDGE_PORT} on that network)`+ : `Allow outbound TCP and UDP port ${TUNNEL_EDGE_PORT}, or turn off the VPN or firewall that blocks it.`,+ exitNodeHint(exitNode) ?? "A VPN, proxy, or firewall may block it.",+ );+ }+ if (status === 502) {+ return fail(+ "origin_unreachable",+ "The tunnel is up, but it cannot reach the T3 server on this machine.",+ "Restart T3 Code so the tunnel uses the port the server listens on.",+ );+ }+ if (endpoint === null || connector.readyConnections === 0) {+ return fail(+ "connector_not_ready",+ "cloudflared has not connected to Cloudflare yet.",+ "Wait a minute. If it stays, check the network and the server log.",+ );+ }+ // Cloudflare answers 530 (error 1033) when the tunnel has no live connector.+ if (status === 530) {+ return fail(+ "no_connector",+ "Cloudflare has no live connection from this machine for the tunnel.",+ restart,+ );+ }+ if (status !== null) {+ return fail(+ "unexpected_response",+ `The T3 Connect address answered with HTTP ${status}.`,+ restart,+ );+ }+ return endpoint.kind === "dns_failed"+ ? fail(+ "dns_failed",+ "The T3 Connect address does not resolve from this machine.",+ "Check the DNS settings on this machine or its VPN.",+ exitNodeHint(exitNode),+ )+ : fail(+ "timeout",+ "The T3 Connect address did not answer from this machine.",+ "Check the network, VPN, or proxy on this machine.",+ exitNodeHint(exitNode),+ );+}++/** The loud diagnosis the CLI prints and the server logs. */+export function formatReachabilityFailure(result: Unreachable): string {+ return [+ "✕ T3 Connect is NOT reachable from other devices",+ ` ${result.reason}`,+ ...(result.hint ? [` ${result.hint}`] : []),+ ` Fix: ${result.fix}`,+ ` More info: ${connectReachabilityHelpUrl(result.cause)}`,+ ].join("\n");+}++function hasErrorCode(error: unknown, codes: ReadonlySet<string>): boolean {+ let current = error;+ for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth++) {+ if ("code" in current && typeof current.code === "string" && codes.has(current.code)) {+ return true;+ }+ current = "cause" in current ? current.cause : undefined;+ }+ return false;+}++const DNS_ERROR_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME"]);++const canOpenTcp = (host: string, port: number) =>+ Effect.callback<boolean>((resume) => {+ const socket = NodeNet.connect({ host, port });+ const finish = (connected: boolean) => {+ socket.destroy();+ resume(Effect.succeed(connected));+ };+ socket.setTimeout(Duration.toMillis(EDGE_CONNECT_TIMEOUT), () => finish(false));+ socket.once("connect", () => finish(true));+ socket.once("error", () => finish(false));+ return Effect.sync(() => socket.destroy());+ });++export class ConnectReachability extends Context.Service<+ ConnectReachability,+ {+ /** Runs a check now. The server also runs one when the tunnel's readiness changes. */+ readonly check: Effect.Effect<EnvironmentConnectReachability>;+ readonly latest: Effect.Effect<Option.Option<EnvironmentConnectReachability>>;+ }+>()("t3/cloud/ConnectReachability") {}++const make = Effect.gen(function* () {+ const runtime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;+ const secrets = yield* ServerSecretStore.ServerSecretStore;+ const httpClient = yield* HttpClient.HttpClient;+ // `order` ranks checks by start, so a slow older one cannot replace a newer result.+ const latestRef = yield* Ref.make(+ Option.none<{ readonly order: number; readonly result: EnvironmentConnectReachability }>(),+ );+ const checkCounter = yield* Ref.make(0);+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const readExitNode = readTailscaleExitNode.pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.orElseSucceed(() => null),+ );++ const probeEndpoint = (hostname: string) =>+ httpClient.get(`https://${hostname}/.well-known/t3/environment`).pipe(+ Effect.map((response): EndpointProbe => ({ kind: "status", status: response.status })),+ Effect.scoped,+ Effect.timeoutOption(ENDPOINT_REQUEST_TIMEOUT),+ Effect.map(Option.getOrElse((): EndpointProbe => ({ kind: "timeout" }))),+ Effect.catch((error) =>+ Effect.succeed<EndpointProbe>({+ kind: hasErrorCode(error, DNS_ERROR_CODES) ? "dns_failed" : "network_error",+ }),+ ),+ );++ const gatherFacts = Effect.gen(function* () {+ const managedTunnelConfigured = Option.isSome(+ yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG).pipe(Effect.orElseSucceed(Option.none)),+ );+ const connector = managedTunnelConfigured ? yield* runtime.inspectConnector : null;+ const endpoint =+ connector?.hostname && connector.readyConnections !== 0+ ? yield* probeEndpoint(connector.hostname)+ : null;+ const facts: ReachabilityFacts = {+ managedTunnelConfigured,+ connector,+ endpoint,+ edgeReachable: null,+ exitNode: null,+ };+ if (connector === null || (endpoint?.kind === "status" && endpoint.status === 200)) {+ return facts;+ }+ const [edgeResults, exitNode] = yield* Effect.all(+ [+ Effect.forEach(TUNNEL_EDGE_HOSTS, (host) => canOpenTcp(host, TUNNEL_EDGE_PORT), {+ concurrency: "unbounded",+ }),+ readExitNode,+ ],+ { concurrency: 2 },+ );+ return { ...facts, edgeReachable: edgeResults.some(Boolean), exitNode };+ });++ const check = Effect.gen(function* () {+ const order = yield* Ref.updateAndGet(checkCounter, (count) => count + 1);+ const facts = yield* gatherFacts;+ const result = classifyReachability(facts, DateTime.formatIso(yield* DateTime.now));+ const previous = yield* Ref.modify(latestRef, (current) =>+ Option.isSome(current) && current.value.order > order+ ? [null, current]+ : [current, Option.some({ order, result })],+ );+ if (previous === null) return result;+ const changed = Option.match(previous, {+ onNone: () => true,+ onSome: ({ result: last }) =>+ last.status !== result.status ||+ (last.status === "unreachable" &&+ result.status === "unreachable" &&+ last.cause !== result.cause),+ });+ if (!changed || (result.status === "unreachable" && result.cause === "not_linked")) {+ return result;+ }+ if (result.status === "unreachable") {+ // A connector that has not connected yet is usually still starting; the+ // runtime restarts it, and an unreachable edge is reported as its own cause.+ const log = result.cause === "connector_not_ready" ? Effect.logWarning : Effect.logError;+ yield* log(`\n${formatReachabilityFailure(result)}`).pipe(+ Effect.annotateLogs({ cause: result.cause }),+ );+ } else {+ yield* Effect.logInfo(+ `T3 Connect is reachable from other devices. ${formatConnectReachable(result)}`,+ );+ }+ return result;+ }).pipe(Effect.withSpan("ConnectReachability.check"));++ yield* runtime.readinessChanged.pipe(+ Stream.debounce(READINESS_CHANGE_DEBOUNCE),+ Stream.runForEach(() => check),+ Effect.forkScoped,+ );+ yield* Effect.sleep(RECHECK_INTERVAL).pipe(+ Effect.andThen(check),+ Effect.forever,+ Effect.forkScoped,+ );++ return ConnectReachability.of({+ check,+ latest: Ref.get(latestRef).pipe(Effect.map(Option.map(({ result }) => result))),+ });+});++export const layer = Layer.effect(ConnectReachability, make);diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.tsindex 1ec54b5e839..2bc742a1706 100644--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts+++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts@@ -11,10 +11,11 @@ import * as Option from "effect/Option";import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Result from "effect/Result";+import * as Schema from "effect/Schema";import * as Semaphore from "effect/Semaphore";import * as Scope from "effect/Scope";import * as Stream from "effect/Stream";-import { HttpClient } from "effect/http";+import { HttpClient, HttpClientResponse } from "effect/http";import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";@@ -42,12 +43,24 @@ export type CloudManagedEndpointRuntimeStatus =readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];};+/** What the running cloudflared reports about itself. `null` fields are not known yet. */+export interface ConnectorFacts {+ readonly readyConnections: number | null;+ /** The public tunnel hostname from the remote config cloudflared receives once it connects. */+ readonly hostname: string | null;+ readonly protocol: string | null;+}+export class CloudManagedEndpointRuntime extends Context.Service<CloudManagedEndpointRuntime,{readonly applyConfig: (config: RelayManagedEndpointRuntimeConfig | null,) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;+ /** `null` when no connector is running. */+ readonly inspectConnector: Effect.Effect<ConnectorFacts | null>;+ /** Emits when a connector registers a connection or its readiness changes. */+ readonly readinessChanged: Stream.Stream<void>;readonly recoveryRequests: Stream.Stream<RelayManagedEndpointRuntimeConfig>;readonly requestRecovery: (config: RelayManagedEndpointRuntimeConfig) => Effect.Effect<void>;readonly tunnelConnected: Stream.Stream<void>;@@ -64,6 +77,7 @@ interface ActiveConnector {readonly startedAtMillis: number;readonly registered: Deferred.Deferred<void>;readonly metricsAddress: Deferred.Deferred<string>;+ readonly protocol: Ref.Ref<string | null>;}// Without the backoff below, a relay client that fails instantly (a stale@@ -86,6 +100,17 @@ const CONNECTOR_READINESS_REQUEST_TIMEOUT = Duration.seconds(5);const CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART = 6;const CONNECTOR_NOT_READY_CHECKS_MAX = 60;const RELAY_CLIENT_METRICS_LINE = /\bStarting metrics server on (127\.0\.0\.1:\d+)\/metrics\b/u;+const RELAY_CLIENT_PROTOCOL = /\bprotocol=(\w+)/u;+// cloudflared's metrics server: `/ready` answers 200 or 503 with this body, and+// `/config` holds the ingress rules the edge pushed after the first connection.+const ConnectorReadyBody = Schema.Struct({ readyConnections: Schema.Number });+const ConnectorConfigBody = Schema.Struct({+ config: Schema.Struct({+ ingress: Schema.optional(+ Schema.NullOr(Schema.Array(Schema.Struct({ hostname: Schema.optional(Schema.String) }))),+ ),+ }),+});// Registration resets cloudflared's own fallback, even when QUIC stalls again// immediately. Keep that evidence across registrations and connector restarts.const QUIC_STALLS_BEFORE_HTTP2 = 30;@@ -173,6 +198,7 @@ export const make = Effect.gen(function* () {const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);const recoveryRequests = yield* Queue.sliding<RelayManagedEndpointRuntimeConfig>(1);const tunnelConnections = yield* Queue.sliding<void>(1);+ const readinessChanges = yield* Queue.sliding<void>(1);const reconcileSemaphore = yield* Semaphore.make(1);const restartDelayRef = yield* Ref.make(0);const linkStateSemaphore = yield* Semaphore.make(1);@@ -403,6 +429,7 @@ export const make = Effect.gen(function* () {const watchConnectorReadiness = Effect.fnUntraced(function* (connector: ActiveConnector) {const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;let notReadyChecks = 0;+ let lastReady: boolean | null = null;while (true) {yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);const status = yield* httpClient.get(readyUrl).pipe(@@ -413,6 +440,11 @@ export const make = Effect.gen(function* () {Effect.orElseSucceed(() => Option.none<number>()),);if (Option.isNone(status)) continue;+ if (status.value === 200 || status.value === 503) {+ const ready = status.value === 200;+ if (ready !== lastReady) yield* Queue.offer(readinessChanges, undefined);+ lastReady = ready;+ }if (status.value === 200) {notReadyChecks = 0;yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);@@ -489,10 +521,14 @@ export const make = Effect.gen(function* () {case "connected":rejectedRegistrations = 0;return Deferred.succeed(connector.registered, undefined).pipe(+ Effect.andThen(+ Ref.set(connector.protocol, RELAY_CLIENT_PROTOCOL.exec(line)?.[1] ?? null),+ ),Effect.andThen(Effect.logInfo("Relay client tunnel connection registered", attributes),),Effect.andThen(Queue.offer(tunnelConnections, undefined)),+ Effect.andThen(Queue.offer(readinessChanges, undefined)),Effect.andThen(RelayClient.isPinnedManagedRelayClient(connector.executable)? Ref.getAndSet(prunedRef, true).pipe(@@ -666,6 +702,7 @@ export const make = Effect.gen(function* () {startedAtMillis: yield* Clock.currentTimeMillis,registered: yield* Deferred.make<void>(),metricsAddress: yield* Deferred.make<string>(),+ protocol: yield* Ref.make<string | null>(null),} satisfies ActiveConnector;yield* Ref.set(activeRef, connector);yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);@@ -712,8 +749,44 @@ export const make = Effect.gen(function* () {),);+ const readMetrics = <S extends Schema.Decoder<unknown>>(url: string, schema: S) =>+ httpClient.get(url).pipe(+ Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),+ Effect.scoped,+ Effect.withTracerEnabled(false),+ Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),+ Effect.map(Option.getOrNull),+ Effect.orElseSucceed(() => null),+ );++ const inspectConnector = Effect.gen(function* () {+ const active = yield* Ref.get(activeRef);+ if (!active || !(yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false)))) {+ return null;+ }+ const protocol = yield* Ref.get(active.protocol);+ if (!(yield* Deferred.isDone(active.metricsAddress))) {+ return { readyConnections: null, hostname: null, protocol } satisfies ConnectorFacts;+ }+ const metricsUrl = `http://${yield* Deferred.await(active.metricsAddress)}`;+ const [ready, config] = yield* Effect.all(+ [+ readMetrics(`${metricsUrl}/ready`, ConnectorReadyBody),+ readMetrics(`${metricsUrl}/config`, ConnectorConfigBody),+ ],+ { concurrency: 2 },+ );+ return {+ readyConnections: ready?.readyConnections ?? null,+ hostname: config?.config.ingress?.find((rule) => rule.hostname)?.hostname ?? null,+ protocol,+ } satisfies ConnectorFacts;+ });+const runtime = CloudManagedEndpointRuntime.of({applyConfig,+ inspectConnector,+ readinessChanged: Stream.fromQueue(readinessChanges),recoveryRequests: Stream.fromQueue(recoveryRequests),requestRecovery: (config) => Queue.offer(recoveryRequests, config).pipe(Effect.asVoid),tunnelConnected: Stream.fromQueue(tunnelConnections),diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.tsindex 3e3aae1423c..0d0f3006a07 100644--- a/apps/server/src/cloud/http.test.ts+++ b/apps/server/src/cloud/http.test.ts@@ -13,6 +13,7 @@ import {} from "@t3tools/contracts/relay";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as Option from "effect/Option";import * as Schema from "effect/Schema";import { HttpClient, HttpServer } from "effect/http";import * as Etag from "effect/http/Etag";@@ -34,6 +35,7 @@ import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";import * as CliTokenManager from "./CliTokenManager.ts";import * as CloudLink from "./CloudLink.ts";import * as ConnectHttp from "./http.ts";+import * as ConnectReachability from "./ConnectReachability.ts";import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";@@ -75,6 +77,9 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(Layer.provide([AuthHttp.layer, ConnectHttp.layer]),Layer.provide(AuthHttp.layerAuthenticatedAuth),Layer.provide(CloudLink.layer),+ Layer.provide(+ Layer.mock(ConnectReachability.ConnectReachability)({ latest: Effect.succeed(Option.none()) }),+ ),Layer.provide(EnvironmentAuth.layer),Layer.provide([SqlitePersistence.layerMemory,@@ -285,6 +290,7 @@ const answerHealthWith = async (failure: HealthFailure) => {answerHealthRequest: () => Effect.fail(failure),}),),+ Layer.provide(Layer.mock(ConnectReachability.ConnectReachability)({})),Layer.provide(AuthHttp.layerAuthenticatedAuth),Layer.provide(Layer.mock(EnvironmentAuth.EnvironmentAuth)({})),Layer.provideMerge(diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.tsindex e9357c2ccc4..568bf937938 100644--- a/apps/server/src/cloud/http.ts+++ b/apps/server/src/cloud/http.ts@@ -17,6 +17,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";import { requireEnvironmentScope } from "../auth/http.ts";import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";import * as CloudLink from "./CloudLink.ts";+import * as ConnectReachability from "./ConnectReachability.ts";import type { RelayRequestError } from "./relayResponse.ts";import { traceRelayRequest } from "./traceRelayRequest.ts";@@ -107,6 +108,7 @@ export const layer = HttpApiBuilder.group("connect",Effect.fnUntraced(function* (handlers) {const cloudLink = yield* CloudLink.CloudLink;+ const reachability = yield* ConnectReachability.ConnectReachability;return handlers.handle("linkProof", ({ payload }) =>Effect.gen(function* () {@@ -127,6 +129,9 @@ export const layer = HttpApiBuilder.group(Effect.andThen(toHttpError(cloudLink.linkState())),),)+ .handle("checkReachability", () =>+ requireEnvironmentScope(AuthRelayReadScope).pipe(Effect.andThen(reachability.check)),+ ).handle("unlink", () =>requireEnvironmentScope(AuthRelayWriteScope).pipe(Effect.andThen(toHttpError(cloudLink.unlink())),diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 0b0f9c2ac3e..48d701103c0 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -140,6 +140,7 @@ import {import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import * as CloudHttp from "./cloud/http.ts";import * as CloudLink from "./cloud/CloudLink.ts";+import * as ConnectReachability from "./cloud/ConnectReachability.ts";import { pendingServiceUpdateExists } from "./cloud/updateHandoff.ts";import * as RelayTracing from "./cloud/relayTracing.ts";import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";@@ -1047,7 +1048,7 @@ const layerMakeServer = Layer.unwrap();return layerServerApplication.pipe(- Layer.provide(CloudLink.layer),+ Layer.provide(CloudLink.layer.pipe(Layer.provideMerge(ConnectReachability.layer))),Layer.provideMerge(layerRuntimeServices),Layer.provideMerge(McpSessionRegistry.layer.pipe(diff --git a/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx b/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsxindex 0f995c7bdac..6de31791230 100644--- a/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx+++ b/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx@@ -166,6 +166,16 @@ export function ConnectionDiagnosisPanel({<li key={step}>{step}</li>))}</ol>+ {diagnosis.moreInfoUrl ? (+ <a+ href={diagnosis.moreInfoUrl}+ target="_blank"+ rel="noreferrer"+ className="text-muted-foreground underline underline-offset-2 hover:text-foreground"+ >+ More info+ </a>+ ) : null}</div><dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 font-mono text-muted-foreground">{diagnosis.facts.map(([label, value]) => (diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex 5585b138dc3..9f613f38665 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -15,6 +15,7 @@ import {type ReactNode,memo,useEffect,+ useEffectEvent,useId,useRef,useState,@@ -41,6 +42,8 @@ import {type DesktopServerExposureState,type DesktopWslState,type EnvironmentId,+ connectReachabilityHelpUrl,+ formatConnectReachable,resolveEnvironmentMachineKind,} from "@t3tools/contracts";import {@@ -1844,6 +1847,32 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b? "Your session does not have permission to manage T3 Connect access.": null;const isBusy = isUpdating || isUpdatingPreference;+ const refreshLinkState = useEffectEvent(primaryCloudLinkState.refresh);+ // The server rechecks reachability when the tunnel's 30 s readiness poll changes.+ // Poll while mounted, so a failed read does not stop later ones.+ useEffect(() => {+ const interval = window.setInterval(() => refreshLinkState(), 30_000);+ return () => window.clearInterval(interval);+ }, []);+ const reachability = managedTunnelActive ? primaryCloudLinkState.data?.reachability : undefined;+ const reachabilityStatus =+ reachability?.status === "reachable" ? (+ formatConnectReachable(reachability)+ ) : reachability?.status === "unreachable" ? (+ <span className="block text-destructive">+ {[reachability.reason, reachability.hint, `Fix: ${reachability.fix}`]+ .filter(Boolean)+ .join(" ")}{" "}+ <a+ href={connectReachabilityHelpUrl(reachability.cause)}+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-2"+ >+ More info+ </a>+ </span>+ ) : null;const updateManagedTunnel = async (enabled: boolean) => {if (@@ -1919,12 +1948,16 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: blinkRevoked? "This environment was removed from T3 Connect. Turn it on to link it again.": managedTunnelActive- ? "This environment is available to your other devices through T3 Connect."+ ? reachability?.status === "unreachable"+ ? "T3 Connect is on, but other devices cannot reach this environment."+ : reachability?.status === "reachable"+ ? "This environment is available to your other devices through T3 Connect."+ : "T3 Connect is on. Reachability has not been checked yet.": managedTunnelOutOfSync? "T3 Connect is out of sync. This environment is linked only to publish agent activity, so other devices cannot connect. Turn T3 Connect on to repair it.": "Make this environment available to your other devices through T3 Connect."}- status={operationError ?? primaryCloudLinkState.error}+ status={operationError ?? primaryCloudLinkState.error ?? reachabilityStatus}control={<CloudLinkSwitchchecked={managedTunnelActive}diff --git a/docs/README.md b/docs/README.mdindex d7628960cb8..dc3c08bfc6c 100644--- a/docs/README.md+++ b/docs/README.md@@ -19,6 +19,7 @@- [Usage and limits](./user/usage.md)- [Product usage data](./user/telemetry.md)- [Remote access](./user/remote-access.md)+- [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md)- [Outside agents (MCP)](./user/outside-agents.md)- [Running in the background](./user/background-service.md)- [Updating T3 Code](./user/updating.md)diff --git a/docs/user/background-service.md b/docs/user/background-service.mdindex 6f3c56d53a5..9310b3fecb2 100644--- a/docs/user/background-service.md+++ b/docs/user/background-service.md@@ -118,7 +118,7 @@ Downloads, it may need Full Disk Access for the `t3` executable listed in`~/Library/LaunchAgents/com.t3tools.t3code.service.plist`.For failures after signing in to T3 Connect, see-[connection troubleshooting](./remote-access.md#t3-connect-troubleshooting).+[connection troubleshooting](./t3-connect-troubleshooting.md).## Reclaim database spacediff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 7e58cb9b050..493a580d14c 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -331,26 +331,9 @@ screenshots, logs, or bug reports.## T3 Connect troubleshooting-Run `t3 connect status` on the host to inspect saved authorization and link-configuration. It is not a live reachability check. If the environment appears-offline, run `t3 service status` and read the displayed log. If it disappears-when SSH closes, see [background-service troubleshooting](./background-service.md#troubleshooting).--| Error | Recovery |-| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |-| `environment_link_limit_exceeded` or managed tunnel limit | Deregister an unused environment, then restart T3 Code on the host. |-| `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. |-| Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. |-| HTTP 403 without a recognized error | Check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. |-| HTTP 408, 429, or 5xx | Check network and relay availability. Startup retries temporary failures for up to ten minutes. |--After fixing a permanent rejection, restart the host's server. On Linux, use-`systemctl --user restart t3code.service` for the background service. For a-foreground server, stop it and run `t3 serve` again with your usual options.-Include the diagnostic message and trace ID when reporting a persistent failure.--For a connection that still fails after linking, check the date and time on both-devices. For server version warnings, follow [Updating T3 Code](./updating.md).+When a T3 Connect connection fails, see+[T3 Connect troubleshooting](./t3-connect-troubleshooting.md). It explains each+error, where the problem is, and how to fix it.## Using the Desktop App as a Remote Onlydiff --git a/docs/user/t3-connect-troubleshooting.md b/docs/user/t3-connect-troubleshooting.mdnew file mode 100644index 00000000000..1150688ec92--- /dev/null+++ b/docs/user/t3-connect-troubleshooting.md@@ -0,0 +1,151 @@+# T3 Connect troubleshooting++A T3 Connect connection goes through four parts, in this order:++1. **This device** reaches T3 Connect over the internet.+2. **T3 Connect** checks your sign-in and the host's link.+3. **The host's tunnel** (cloudflared on the host) carries the request to the host.+4. **T3 Code on the host** answers.++When a connection fails, open **Settings > Connections**, find the environment,+and select **Details**. The first part marked as failed is the cause. Find its+section below.++To see the host's side, run `t3 connect status` on the host, or open+**Settings > Connections** on the host. Both check the host's T3 Connect+address from the host, and say why it fails. `t3 connect` runs the same check+when it finishes setup. This check cannot test another device's network. For a+problem on one device, use **Details** on that device.++## The host's tunnel is offline++T3 Connect could not reach the host's tunnel. This means one of these:++- The host is asleep, turned off, or offline.+- T3 Code is not running on the host.+- The host's network blocks the tunnel. See+ [Port 7844 is blocked on the host](#port-7844-is-blocked-on-the-host).++Fix:++1. Make sure the host is awake and T3 Code runs on it.+2. On the host, run `t3 connect status`. It names the problem on the host's side.+3. If the host was offline for a long time, T3 Connect removes its tunnel. Start+ T3 Code on the host and update it to the latest version. It gets a new tunnel.++## Port 7844 is blocked on the host++The tunnel on the host connects out to Cloudflare on port 7844, with TCP and+UDP. Both tunnel protocols (QUIC and HTTP/2) use this port. When the host's+network blocks it, the tunnel cannot start, but normal web traffic still works.+The host looks online, so this problem is easy to miss.++Common causes:++- **A Tailscale exit node on the host.** All of the host's internet traffic goes+ through the exit node, and that network blocks port 7844. Turn off the exit+ node on the host with `tailscale set --exit-node=`, or allow outbound port+ 7844 on the exit node's network.+- **A VPN on the host.** Work VPNs often block unknown ports. Ask for port 7844+ to be allowed, or use a direct route instead (see below).+- **A firewall or strict network.** Allow outbound TCP and UDP port 7844.++If you cannot unblock the port, you can connect without T3 Connect. When the+host and this device are on the same Tailscale network, add the host's+Tailscale address as a direct route. See+[Reach one machine several ways](./remote-access.md#reach-one-machine-several-ways).++## The tunnel works, but T3 Code does not answer++The host's tunnel is up, but it cannot reach T3 Code on the host. Common causes:++- T3 Code on the host stopped, crashed, or is still starting.+- T3 Code restarted on a different port, for example after an update, and the+ tunnel still points at the old port.+- The server binds only one network address with `T3CODE_HOST`. The tunnel+ sends requests to `127.0.0.1`, so the server must also listen there.++Fix: restart T3 Code on the host. For the background service, run+`t3 service restart`. Then run `t3 connect status` on the host.++## The T3 Connect address does not resolve or answer++The host's T3 Connect address did not resolve, refused the connection, failed a+secure (TLS) connection, or did not answer in time.++Fix:++1. Make sure the host is awake and online.+2. On the host, run `t3 connect status`.+3. If the check fails only on the host, check the host's DNS, VPN, or proxy.++## This device can't reach T3 Connect++The problem is on this device's network, not on the host. This device could+not reach T3 Connect, or it reached T3 Connect but not the host's tunnel+address.++Fix:++1. Check this device's internet connection. On a captive or dead Wi-Fi network,+ the device can look online but cannot reach anything.+2. A VPN, firewall, ad blocker, or DNS filter on this device can block T3+ Connect. Turn it off for a moment to test.+3. On iPhone, Connectivity Assist in the Wi-Fi settings can break T3 Connect.+ Turn it off to test.+4. Try another network, or add a direct route to the host, such as its+ Tailscale address. See+ [Reach one machine several ways](./remote-access.md#reach-one-machine-several-ways).++## Sign-in, account, or link problems++T3 Connect does not have an active link between your account and the host.++- **The host is linked to a different account.** Sign in to the same T3 Connect+ account on this device and on the host. On the host, run `t3 connect logout`,+ then `t3 connect`.+- **T3 Connect is off on the host, or the host only publishes agent activity.**+ On the host, open **Settings > Connections** and turn **T3 Connect** on, or+ run `t3 connect`.+- **The host was linked, but the server did not apply the link yet.** Run+ `t3 service restart` on the host, or restart `t3 serve`.+- **This device's sign-in expired, or the host no longer accepts this+ device.** Sign out of T3 Connect and sign in again.+- **Your account reached its tunnel limit.** Remove an environment you do not+ use from your T3 account's T3 Connect page, then restart T3 Code on the host.++## The clock is off++T3 Connect signs requests with short-lived proofs. When the clock on this+device or the host is a few minutes wrong, T3 Connect rejects them. Turn on+automatic date and time on both devices, then retry.++## The host runs an older T3 Code++This app needs a newer T3 Code on the host. Update T3 Code on the host. See+[Updating T3 Code](./updating.md).++## T3 Connect returned an error++| Error | Fix |+| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |+| `environment_link_limit_exceeded` or managed tunnel limit | Remove an unused environment, then restart T3 Code on the host. |+| `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. |+| Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. |+| HTTP 403 without a recognized error | Check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. |+| HTTP 408, 429, or 5xx | Wait a few minutes. T3 Code retries temporary failures on its own. |++After you fix a permanent rejection, restart the host's server with+`t3 service restart`. For a foreground server, stop it and run `t3 serve` again.++If T3 Code on the host disappears when SSH closes, see+[background-service troubleshooting](./background-service.md#troubleshooting).++## Report a problem++If none of this helps, open an issue on+[GitHub](https://github.com/pingdotgg/t3code/issues). Include:++- The text from **Copy diagnostics** in the environment's **Details**.+- The output of `t3 connect status` on the host.+- The trace ID, if one is shown.diff --git a/packages/client-runtime/src/connection/diagnosis.test.ts b/packages/client-runtime/src/connection/diagnosis.test.tsindex babfccb636d..3a32a96dac1 100644--- a/packages/client-runtime/src/connection/diagnosis.test.ts+++ b/packages/client-runtime/src/connection/diagnosis.test.ts@@ -15,6 +15,7 @@ import {import {AVAILABLE_CONNECTION_STATE,type ConnectionAttemptError,+ ConnectionBlockedError,type SupervisorConnectionState,} from "./model.ts";import { ManagedRelayRequestFailedError } from "../relay/managedRelay.ts";@@ -69,6 +70,24 @@ describe("presentConnectionDiagnosis", () => {expect(diagnosis?.steps.join(" ")).toContain("Tailscale exit node on Mac mini");expect(diagnosis?.facts).toContainEqual(["HTTP status", "530"]);expect(diagnosis?.facts).toContainEqual(["Trace ID", "trace-1"]);+ expect(diagnosis?.moreInfoUrl).toMatch(+ /t3-connect-troubleshooting\.md#the-hosts-tunnel-is-offline$/,+ );+ });++ it("links a host that rejects this device to the sign-in section", () => {+ const failure = new ConnectionBlockedError({+ reason: "authentication",+ detail: "rejected",+ hop: "server",+ via: "relay",+ });+ expect(diagnose(backoff(failure))?.moreInfoUrl).toMatch(/#sign-in-account-or-link-problems$/);+ });++ it("links the guide only for T3 Connect routes", () => {+ const failure = credentialMissingError("direct-1");+ expect(diagnose(backoff(failure), "direct")?.moreInfoUrl).toBeNull();});it("tells a working tunnel apart from T3 Code not answering", () => {diff --git a/packages/client-runtime/src/connection/diagnosis.ts b/packages/client-runtime/src/connection/diagnosis.tsindex 96db26f99be..f774a8e4aeb 100644--- a/packages/client-runtime/src/connection/diagnosis.ts+++ b/packages/client-runtime/src/connection/diagnosis.ts@@ -1,3 +1,7 @@+import {+ t3ConnectTroubleshootingUrl,+ type T3ConnectTroubleshootingSection,+} from "@t3tools/contracts";import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";import * as DateTime from "effect/DateTime";@@ -22,6 +26,8 @@ export interface ConnectionDiagnosis {readonly hops: ReadonlyArray<ConnectionDiagnosisHop>;readonly steps: ReadonlyArray<string>;readonly facts: ReadonlyArray<readonly [label: string, value: string]>;+ /** The troubleshooting guide section for this failure. Null for direct routes. */+ readonly moreInfoUrl: string | null;}export interface ConnectionDiagnosisInput {@@ -203,6 +209,58 @@ function steps(host: string, located: Located, failure: ConnectionAttemptError |}}+function helpSection(+ located: Located,+ failure: ConnectionAttemptError | null,+): T3ConnectTroubleshootingSection {+ switch (located.cause) {+ case "offline":+ return "this-device-cant-reach-t3-connect";+ case "outdated":+ return "the-host-runs-an-older-t3-code";+ case "clock_skew":+ return "the-clock-is-off";+ case "not_linked":+ case "tunnel_not_enabled":+ return "sign-in-account-or-link-problems";+ case "relay_error":+ return "t3-connect-returned-an-error";+ case "released":+ case "tunnel_down":+ case "tunnel_pending":+ return "the-hosts-tunnel-is-offline";+ case "origin_unreachable":+ case "invalid_response":+ return "the-tunnel-works-but-t3-code-does-not-answer";+ case "dns":+ case "tls":+ case "refused":+ case "timeout":+ case "unknown":+ return "the-t3-connect-address-does-not-resolve-or-answer";+ case null:+ break;+ }+ const onThisDevice =+ failure?.reason === "network" ||+ failure?.reason === "transport" ||+ failure?.reason === "timeout";+ switch (located.hop) {+ case "device":+ return "this-device-cant-reach-t3-connect";+ case "relay":+ return failure?.reason === "authentication"+ ? "sign-in-account-or-link-problems"+ : "this-device-cant-reach-t3-connect";+ case "tunnel":+ return onThisDevice ? "this-device-cant-reach-t3-connect" : "the-hosts-tunnel-is-offline";+ case "server":+ return failure?.reason === "authentication" || failure?.reason === "permission"+ ? "sign-in-account-or-link-problems"+ : "the-tunnel-works-but-t3-code-does-not-answer";+ }+}+const HOP_ORDER = {relay: ["device", "relay", "tunnel", "server"],direct: ["device", "server"],@@ -271,6 +329,7 @@ export function presentConnectionDiagnosis(hops,steps: steps(host, located, failure),facts,+ moreInfoUrl: relayPath ? t3ConnectTroubleshootingUrl(helpSection(located, failure)) : null,};}@@ -284,5 +343,6 @@ export function connectionDiagnosisText(hostLabel: string, diagnosis: Connection...diagnosis.hops.map((hop) => `${hop.label}: ${HOP_MARK[hop.result]}`),"",...diagnosis.facts.map(([label, value]) => `${label}: ${value}`),+ ...(diagnosis.moreInfoUrl ? ["", `More info: ${diagnosis.moreInfoUrl}`] : []),].join("\n");}diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.tsindex 31b69997f43..87edc7d664a 100644--- a/packages/contracts/src/environmentHttp.ts+++ b/packages/contracts/src/environmentHttp.ts@@ -408,6 +408,89 @@ export const EnvironmentCloudRelayConfigResult = Schema.Struct({});export type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type;+export const EnvironmentConnectReachabilityCause = Schema.Literals([+ "not_linked",+ "connector_not_running",+ "connector_not_ready",+ "edge_unreachable",+ "no_connector",+ "origin_unreachable",+ "dns_failed",+ "timeout",+ "unexpected_response",+]);+export type EnvironmentConnectReachabilityCause = typeof EnvironmentConnectReachabilityCause.Type;++/** Whether other devices can reach this environment through its T3 Connect tunnel. */+export const EnvironmentConnectReachability = Schema.Union([+ Schema.Struct({+ status: Schema.Literal("reachable"),+ checkedAt: Schema.String,+ /** Null when cloudflared did not report a count. */+ readyConnections: Schema.NullOr(Schema.Int),+ protocol: Schema.NullOr(Schema.String),+ }),+ Schema.Struct({+ status: Schema.Literal("unreachable"),+ checkedAt: Schema.String,+ cause: EnvironmentConnectReachabilityCause,+ reason: Schema.String,+ hint: Schema.NullOr(Schema.String),+ fix: Schema.String,+ }),+]);+export type EnvironmentConnectReachability = typeof EnvironmentConnectReachability.Type;++/** "Tunnel connected · 4 connections · QUIC" for a healthy check. */+export function formatConnectReachable(+ result: Extract<EnvironmentConnectReachability, { status: "reachable" }>,+): string {+ const count = result.readyConnections;+ return [+ "Tunnel connected",+ ...(count === null ? [] : [`${count} connection${count === 1 ? "" : "s"}`]),+ ...(result.protocol ? [result.protocol.toUpperCase()] : []),+ ].join(" · ");+}++/**+ * Sections of docs/user/t3-connect-troubleshooting.md. Each is the GitHub anchor of a+ * heading there; the test fails when a heading is renamed without updating this list.+ */+export const T3_CONNECT_TROUBLESHOOTING_SECTIONS = [+ "the-hosts-tunnel-is-offline",+ "port-7844-is-blocked-on-the-host",+ "the-tunnel-works-but-t3-code-does-not-answer",+ "the-t3-connect-address-does-not-resolve-or-answer",+ "this-device-cant-reach-t3-connect",+ "sign-in-account-or-link-problems",+ "the-clock-is-off",+ "the-host-runs-an-older-t3-code",+ "t3-connect-returned-an-error",+] as const;+export type T3ConnectTroubleshootingSection = (typeof T3_CONNECT_TROUBLESHOOTING_SECTIONS)[number];++/** Clients, the CLI, and server logs link here as "More info". */+export function t3ConnectTroubleshootingUrl(section: T3ConnectTroubleshootingSection): string {+ return `https://github.com/pingdotgg/t3code/blob/main/docs/user/t3-connect-troubleshooting.md#${section}`;+}++const REACHABILITY_SECTION = {+ not_linked: "sign-in-account-or-link-problems",+ connector_not_running: "the-hosts-tunnel-is-offline",+ connector_not_ready: "the-hosts-tunnel-is-offline",+ no_connector: "the-hosts-tunnel-is-offline",+ edge_unreachable: "port-7844-is-blocked-on-the-host",+ origin_unreachable: "the-tunnel-works-but-t3-code-does-not-answer",+ unexpected_response: "the-tunnel-works-but-t3-code-does-not-answer",+ dns_failed: "the-t3-connect-address-does-not-resolve-or-answer",+ timeout: "the-t3-connect-address-does-not-resolve-or-answer",+} satisfies Record<EnvironmentConnectReachabilityCause, T3ConnectTroubleshootingSection>;++export function connectReachabilityHelpUrl(cause: EnvironmentConnectReachabilityCause): string {+ return t3ConnectTroubleshootingUrl(REACHABILITY_SECTION[cause]);+}+export const EnvironmentCloudLinkStateResult = Schema.Struct({linked: Schema.Boolean,cloudUserId: Schema.NullOr(Schema.String),@@ -417,6 +500,8 @@ export const EnvironmentCloudLinkStateResult = Schema.Struct({publishAgentActivity: Schema.Boolean,holdWebhooksWhileOffline: Schema.optional(Schema.Boolean),linkRevoked: Schema.optional(Schema.Boolean),+ /** The latest check the server ran on its own, absent until one finishes. */+ reachability: Schema.optional(EnvironmentConnectReachability),});export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;@@ -689,6 +774,13 @@ class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")error: EnvironmentHttpCloudErrors,}).middleware(EnvironmentAuthenticatedAuth),)+ .add(+ HttpApiEndpoint.post("checkReachability", "/api/connect/reachability", {+ headers: OptionalBearerHeaders,+ success: EnvironmentConnectReachability,+ error: EnvironmentHttpCloudErrors,+ }).middleware(EnvironmentAuthenticatedAuth),+ ).add(HttpApiEndpoint.post("unlink", "/api/connect/unlink", {headers: OptionalBearerHeaders,diff --git a/packages/tailscale/src/tailscale.test.ts b/packages/tailscale/src/tailscale.test.tsindex da20dcd6042..4ae89521b61 100644--- a/packages/tailscale/src/tailscale.test.ts+++ b/packages/tailscale/src/tailscale.test.ts@@ -15,6 +15,7 @@ import {disableTailscaleServe,ensureTailscaleServe,isTailscaleIpv4Address,+ parseTailscaleExitNode,parseTailscaleMagicDnsName,parseTailscaleSshEnabled,parseTailscaleStatus,@@ -147,6 +148,30 @@ describe("tailscale", () => {}),);+ it.effect("names the exit node in use", () =>+ Effect.gen(function* () {+ const inUse = yield* parseTailscaleExitNode(+ JSON.stringify({+ ExitNodeStatus: { ID: "nX", Online: true, TailscaleIPs: ["100.101.102.103/32"] },+ Peer: {+ "nodekey:a": { HostName: "laptop", DNSName: "laptop.tail.ts.net.", ExitNode: false },+ "nodekey:b": {+ HostName: "raspberrypi",+ DNSName: "home-pi.tail.ts.net.",+ ExitNode: true,+ },+ },+ }),+ );+ assert.deepEqual(inUse, { name: "home-pi", online: true });++ const unnamed = yield* parseTailscaleExitNode(`{"ExitNodeStatus":{"Online":false}}`);+ assert.deepEqual(unnamed, { name: null, online: false });++ assert.equal(yield* parseTailscaleExitNode(tailscaleStatusJson), null);+ }),+ );+it.effect("reads the HTTPS serve capability from the status capability map", () =>Effect.gen(function* () {const enabled = yield* parseTailscaleStatus(diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.tsindex 28664e23fa9..97c5d38a1cc 100644--- a/packages/tailscale/src/tailscale.ts+++ b/packages/tailscale/src/tailscale.ts@@ -286,6 +286,57 @@ export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--jEffect.flatMap(parseTailscaleStatus),);+const TailscaleExitNodeJson = Schema.Struct({+ ExitNodeStatus: Schema.optional(Schema.Struct({ Online: Schema.optional(Schema.Unknown) })),+ Peer: Schema.optional(+ Schema.Record(+ Schema.String,+ Schema.Struct({+ ExitNode: Schema.optional(Schema.Unknown),+ HostName: Schema.optional(Schema.Unknown),+ DNSName: Schema.optional(Schema.Unknown),+ }),+ ),+ ),+});++const decodeTailscaleExitNodeJson = Schema.decodeEffect(+ Schema.fromJsonString(TailscaleExitNodeJson),+);++export interface TailscaleExitNode {+ readonly name: string | null;+ readonly online: boolean;+}++/**+ * `ExitNodeStatus` is present only while an exit node is in use, but it has no+ * name. The name comes from the peer marked `ExitNode: true`.+ */+export const parseTailscaleExitNode = (+ rawStatusJson: string,+): Effect.Effect<TailscaleExitNode | null, TailscaleStatusParseError> =>+ decodeTailscaleExitNodeJson(rawStatusJson).pipe(+ Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),+ Effect.map((parsed) => {+ if (parsed.ExitNodeStatus === undefined) return null;+ const peer = Object.values(parsed.Peer ?? {}).find(+ (candidate) => candidate.ExitNode === true,+ );+ // The DNS label is the tailnet machine name; HostName is the OS name and ignores renames.+ const dnsLabel = typeof peer?.DNSName === "string" ? (peer.DNSName.split(".")[0] ?? "") : "";+ const hostName = typeof peer?.HostName === "string" ? peer.HostName.trim() : "";+ return {+ name: dnsLabel || hostName || null,+ online: parsed.ExitNodeStatus.Online === true,+ };+ }),+ );++export const readTailscaleExitNode = readTailscaleOutput("status", ["status", "--json"]).pipe(+ Effect.flatMap(parseTailscaleExitNode),+);+const TailscalePrefsJson = Schema.Struct({RunSSH: Schema.optional(Schema.Unknown),WantRunning: Schema.optional(Schema.Unknown),