Skip to content

Commit 91d7bf3

Browse files
t3dotggclaude
andauthored
feat(connect): t3 connect checks that other devices can reach this machine (pingdotgg#22172)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 72bdf1e commit 91d7bf3

22 files changed

Lines changed: 1148 additions & 35 deletions

‎apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
1212
import Constants from "expo-constants";
1313
import * as Option from "effect/Option";
1414
import { AsyncResult } from "effect/reactivity";
15-
import { View } from "react-native";
15+
import { Linking, View } from "react-native";
1616

1717
import { AppText as Text } from "../../components/ui/AppText";
1818
import { Button } from "../../components/ui/Button";
@@ -52,6 +52,7 @@ export function ConnectionDiagnosisDetails(props: {
5252
readonly diagnosis: ConnectionDiagnosis;
5353
}) {
5454
const { diagnosis } = props;
55+
const { moreInfoUrl } = diagnosis;
5556
return (
5657
<View className="gap-3">
5758
<View className="gap-0.5">
@@ -87,6 +88,14 @@ export function ConnectionDiagnosisDetails(props: {
8788
});
8889
}}
8990
/>
91+
{moreInfoUrl ? (
92+
<Button
93+
label="More info"
94+
icon="safari"
95+
tone="secondary"
96+
onPress={() => void Linking.openURL(moreInfoUrl).catch(() => undefined)}
97+
/>
98+
) : null}
9099
</View>
91100
);
92101
}

‎apps/server/src/cli/connect.ts‎

Lines changed: 109 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import {
2+
AuthRelayReadScope,
23
AuthRelayWriteScope,
4+
type AuthEnvironmentScope,
5+
type EnvironmentConnectReachability,
36
EnvironmentHttpApi,
7+
formatConnectReachable,
48
type RelayClientInstallProgressEvent,
59
type RelayClientInstallProgressStage,
610
} from "@t3tools/contracts";
@@ -9,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
913
import * as RelayClient from "@t3tools/shared/relayClient";
1014
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
1115
import * as Cause from "effect/Cause";
16+
import * as Clock from "effect/Clock";
1217
import * as Config from "effect/Config";
1318
import * as Console from "effect/Console";
1419
import * as Crypto from "effect/Crypto";
@@ -29,6 +34,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
2934
import * as BootService from "../cloud/bootService.ts";
3035
import * as CliState from "../cloud/CliState.ts";
3136
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
37+
import { formatReachabilityFailure } from "../cloud/ConnectReachability.ts";
3238
import { filterRelayResponse } from "../cloud/relayResponse.ts";
3339
import {
3440
CLOUD_LINK_REVOKED,
@@ -142,6 +148,9 @@ interface CloudCliStatus {
142148
readonly relayUrl: string | null;
143149
readonly publishAgentActivity: boolean;
144150
readonly relayClient: RelayClient.RelayClientStatus;
151+
readonly linkMode: CliState.CliDesiredLinkMode;
152+
/** `null` when no server answered the live check, or none ran because no tunnel is wanted. */
153+
readonly reachability: EnvironmentConnectReachability | null;
145154
}
146155

147156
function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
@@ -199,8 +208,19 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
199208
` Relay: ${status.relayUrl ?? "not provisioned"}`,
200209
` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
201210
...formatRelayClientStatus(status.relayClient),
202-
"",
203-
"This is saved setup, not a live connection check. Check the background service with `t3 service status`.",
211+
...(!status.desired || status.linkMode !== "managed"
212+
? []
213+
: status.reachability === null
214+
? [
215+
"",
216+
"No running server answered, so reachability was not checked. Check the background service with `t3 service status`.",
217+
]
218+
: status.reachability.status === "reachable"
219+
? [
220+
"",
221+
`✓ Other devices can reach this machine · ${formatConnectReachable(status.reachability)}`,
222+
]
223+
: ["", formatReachabilityFailure(status.reachability)]),
204224
...(nextStep ? ["", `Next: ${nextStep}`] : []),
205225
].join("\n");
206226
}
@@ -261,11 +281,12 @@ export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_clie
261281

262282
const withCloudCliSessionToken = <A, E, R>(
263283
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
284+
scope: AuthEnvironmentScope,
264285
run: (token: string) => Effect.Effect<A, E, R>,
265286
) =>
266287
Effect.acquireUseRelease(
267288
environmentAuth.issueSession({
268-
scopes: [AuthRelayWriteScope],
289+
scopes: [scope],
269290
subject: "cloud-cli",
270291
label: "t3 connect cli",
271292
}),
@@ -287,7 +308,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
287308

288309
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
289310
const result = yield* Effect.exit(
290-
withCloudCliSessionToken(environmentAuth, (token) =>
311+
withCloudCliSessionToken(environmentAuth, AuthRelayWriteScope, (token) =>
291312
HttpApiClient.make(EnvironmentHttpApi, {
292313
baseUrl: runtimeState.value.origin,
293314
}).pipe(
@@ -303,6 +324,73 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
303324
: ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
304325
});
305326

327+
// One check probes the endpoint, the tunnel edge, and Tailscale, each with its own timeout.
328+
const CLOUD_CLI_REACHABILITY_TIMEOUT = Duration.seconds(30);
329+
const CLOUD_CLI_REACHABILITY_WAIT = Duration.seconds(60);
330+
const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5);
331+
332+
/** Asks the running server to check T3 Connect now. `null` when no server answers. */
333+
const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () {
334+
const config = yield* ServerConfig.ServerConfig;
335+
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
336+
if (Option.isNone(runtimeState)) return null;
337+
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
338+
return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>
339+
HttpApiClient.make(EnvironmentHttpApi, { baseUrl: runtimeState.value.origin }).pipe(
340+
Effect.flatMap((client) =>
341+
client.connect.checkReachability({ headers: { authorization: `Bearer ${token}` } }),
342+
),
343+
Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),
344+
),
345+
).pipe(Effect.orElseSucceed(() => null));
346+
});
347+
348+
function formatAlertBox(text: string): string {
349+
const lines = text.split("\n");
350+
const width = Math.max(...lines.map((line) => line.length));
351+
const color = process.stdout.isTTY === true && !process.env.NO_COLOR;
352+
const red = (line: string) => (color ? `\x1b[1;31m${line}\x1b[0m` : line);
353+
return [
354+
`┌${"─".repeat(width + 2)}┐`,
355+
...lines.map((line) => `│ ${line.padEnd(width)} │`),
356+
`└${"─".repeat(width + 2)}┘`,
357+
]
358+
.map(red)
359+
.join("\n");
360+
}
361+
362+
/**
363+
* Waits for the server that `t3 connect` just started to prove other devices
364+
* can reach it, so a broken tunnel fails setup instead of looking green.
365+
*/
366+
const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {
367+
yield* Console.log("\nChecking that other devices can reach this machine...");
368+
const deadline =
369+
(yield* Clock.currentTimeMillis) + Duration.toMillis(CLOUD_CLI_REACHABILITY_WAIT);
370+
let last: EnvironmentConnectReachability | null = null;
371+
while (true) {
372+
last = (yield* checkLiveReachability()) ?? last;
373+
if (last?.status === "reachable") {
374+
yield* Console.log(
375+
`✓ Other devices can reach this machine · ${formatConnectReachable(last)}`,
376+
);
377+
return;
378+
}
379+
if ((yield* Clock.currentTimeMillis) >= deadline) break;
380+
yield* Effect.sleep(CLOUD_CLI_REACHABILITY_RETRY);
381+
}
382+
yield* Console.error(
383+
formatAlertBox(
384+
last === null
385+
? "✕ 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`."
386+
: formatReachabilityFailure(last),
387+
),
388+
);
389+
yield* Effect.sync(() => {
390+
process.exitCode = 1;
391+
});
392+
});
393+
306394
type RelayUnlinkResult =
307395
| { readonly status: "not-authenticated" }
308396
| { readonly status: "revoked" }
@@ -551,7 +639,9 @@ const connectStatusCommand = Command.make("status", {
551639
...projectLocationFlags,
552640
json: jsonFlag,
553641
}).pipe(
554-
Command.withDescription("Show persisted T3 Connect and relay client state."),
642+
Command.withDescription(
643+
"Show T3 Connect setup and check that other devices can reach this machine.",
644+
),
555645
Command.withHandler((flags) =>
556646
runCloudCommand(
557647
flags,
@@ -567,6 +657,7 @@ const connectStatusCommand = Command.make("status", {
567657
publishAgentActivity,
568658
revoked,
569659
executable,
660+
linkMode,
570661
] = yield* Effect.all(
571662
[
572663
CliState.readCliDesiredCloudLink,
@@ -576,9 +667,13 @@ const connectStatusCommand = Command.make("status", {
576667
secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
577668
secrets.get(CLOUD_LINK_REVOKED),
578669
relayClient.resolve,
670+
CliState.readCliDesiredLinkMode,
579671
],
580672
{ concurrency: "unbounded" },
581673
);
674+
// A publish-only link has no tunnel for other devices to reach.
675+
const reachability =
676+
desired && linkMode === "managed" ? yield* checkLiveReachability() : null;
582677
const status: CloudCliStatus = {
583678
desired,
584679
authenticated,
@@ -590,6 +685,8 @@ const connectStatusCommand = Command.make("status", {
590685
Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
591686
),
592687
relayClient: executable,
688+
linkMode,
689+
reachability,
593690
};
594691
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
595692
}),
@@ -703,7 +800,7 @@ export const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onb
703800
}
704801
const serveCommand = yield* resolveCliCommand("serve");
705802
yield* Console.log(
706-
`\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
803+
`\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.`,
707804
);
708805
},
709806
);
@@ -724,9 +821,13 @@ export const connectCommand = Command.make("connect", {
724821
}
725822
yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
726823

727-
yield* reportServiceOnboarding(
728-
yield* CliService.recoverServiceOnboardingOffer(CliService.offerServiceDuringOnboarding),
824+
const outcome = yield* CliService.recoverServiceOnboardingOffer(
825+
CliService.offerServiceDuringOnboarding,
729826
);
827+
yield* reportServiceOnboarding(outcome);
828+
if (outcome !== "skipped") {
829+
yield* waitForReachability();
830+
}
730831
}),
731832
),
732833
),

‎apps/server/src/cloud/CloudLink.lifecycle.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
RELAY_URL_SECRET,
4444
} from "./config.ts";
4545
import * as CloudLink from "./CloudLink.ts";
46+
import * as ConnectReachability from "./ConnectReachability.ts";
4647
import { consumeCloudReplayGuards } from "./CloudLink.ts";
4748
import { pendingServiceUpdateExists } from "./updateHandoff.ts";
4849
import {
@@ -154,6 +155,13 @@ describe("reconcileDesiredCloudLink", () => {
154155
expect(error._tag).toBe("CloudLinkAuthorizationMissingError");
155156
}).pipe(
156157
Effect.provide(CloudLink.layer),
158+
Effect.provideService(
159+
ConnectReachability.ConnectReachability,
160+
ConnectReachability.ConnectReachability.of({
161+
check: Effect.die("unused"),
162+
latest: Effect.succeed(Option.none()),
163+
}),
164+
),
157165
Effect.provideService(HttpServer.HttpServer, idleHttpServer),
158166
Effect.provideService(
159167
ServerConfigModule.ServerConfig,
@@ -177,6 +185,8 @@ describe("reconcileDesiredCloudLink", () => {
177185
recoveryRequests: Stream.empty,
178186
requestRecovery: () => Effect.void,
179187
tunnelConnected: Stream.empty,
188+
inspectConnector: Effect.succeed(null),
189+
readinessChanged: Stream.empty,
180190
withLinkStateLock: (effect) => effect,
181191
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
182192
),
@@ -276,6 +286,13 @@ describe("releaseManagedTunnelOnShutdown", () => {
276286
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
277287
effect.pipe(
278288
Effect.provide(CloudLink.layer),
289+
Effect.provideService(
290+
ConnectReachability.ConnectReachability,
291+
ConnectReachability.ConnectReachability.of({
292+
check: Effect.die("unused"),
293+
latest: Effect.succeed(Option.none()),
294+
}),
295+
),
279296
Effect.provideService(HttpServer.HttpServer, {
280297
...idleHttpServer,
281298
address: harness.address ?? idleHttpServer.address,
@@ -308,6 +325,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
308325
recoveryRequests: Stream.empty,
309326
requestRecovery: () => Effect.void,
310327
tunnelConnected: Stream.empty,
328+
inspectConnector: Effect.succeed(null),
329+
readinessChanged: Stream.empty,
311330
withLinkStateLock: (effect) => effect,
312331
}),
313332
),

‎apps/server/src/cloud/CloudLink.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
1616
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
1717
import * as CliTokenManager from "./CliTokenManager.ts";
1818
import * as CloudLink from "./CloudLink.ts";
19+
import * as ConnectReachability from "./ConnectReachability.ts";
1920
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
2021
import {
2122
HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
@@ -94,6 +95,9 @@ const withService = <A, E>(
9495
}),
9596
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }),
9697
Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
98+
Layer.mock(ConnectReachability.ConnectReachability)({
99+
latest: Effect.succeed(Option.none()),
100+
}),
97101
Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
98102
Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
99103
Layer.mock(HttpServer.HttpServer)({

‎apps/server/src/cloud/CloudLink.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ import {
9696
RELAY_URL_SECRET,
9797
} from "./config.ts";
9898
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
99+
import * as ConnectReachability from "./ConnectReachability.ts";
99100
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
100101
import { relayUrlConfig } from "./publicConfig.ts";
101102
import {
@@ -529,6 +530,7 @@ const make = Effect.gen(function* () {
529530
const secrets = yield* ServerSecretStore.ServerSecretStore;
530531
const environment = yield* ServerEnvironment.ServerEnvironment;
531532
const endpointRuntime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
533+
const reachability = yield* ConnectReachability.ConnectReachability;
532534
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
533535
const cliTokenManager = yield* CliTokenManager.CloudCliTokenManager;
534536
const httpClient = yield* HttpClient.HttpClient;
@@ -1314,6 +1316,7 @@ const make = Effect.gen(function* () {
13141316
publishAgentActivity,
13151317
holdWebhooks,
13161318
revoked,
1319+
latestReachability,
13171320
] = yield* Effect.all(
13181321
[
13191322
secrets.get(CLOUD_LINKED_USER_ID),
@@ -1323,8 +1326,9 @@ const make = Effect.gen(function* () {
13231326
secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
13241327
secrets.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET),
13251328
secrets.get(CLOUD_LINK_REVOKED),
1329+
reachability.latest,
13261330
],
1327-
{ concurrency: 7 },
1331+
{ concurrency: 8 },
13281332
);
13291333
return {
13301334
linked: Option.isSome(cloudUserId),
@@ -1338,6 +1342,7 @@ const make = Effect.gen(function* () {
13381342
: false,
13391343
holdWebhooksWhileOffline:
13401344
Option.isSome(holdWebhooks) && bytesToString(holdWebhooks.value) === "true",
1345+
...(Option.isSome(latestReachability) ? { reachability: latestReachability.value } : {}),
13411346
} satisfies EnvironmentCloudLinkStateResult;
13421347
});
13431348

0 commit comments

Comments
 (0)