Open History to see the last commit
1import {
2 t3ConnectTroubleshootingUrl,
3 type T3ConnectTroubleshootingSection,
4} from "@t3tools/contracts";
5import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
6import * as DateTime from "effect/DateTime";
7
8import type {
9 ConnectionAttemptError,
10 ConnectionFailureCause,
11 ConnectionHop,
12 SupervisorConnectionState,
13} from "./model.ts";
14import { mFallback, msg } from "gt-i18n";
15import type { M } from "gt-i18n";
16
17export type ConnectionHopResult = "ok" | "failed" | "unchecked";
18
19export interface ConnectionDiagnosisHop {
20 readonly hop: ConnectionHop;
21 readonly label: string;
22 readonly result: ConnectionHopResult;
23}
24
25export interface ConnectionDiagnosis {
26 /** Names the part that failed, e.g. "Mac mini's tunnel is offline". */
27 readonly headline: string;
28 readonly hops: ReadonlyArray<ConnectionDiagnosisHop>;
29 readonly steps: ReadonlyArray<string>;
30 readonly facts: ReadonlyArray<readonly [label: string, value: string]>;
31 /** The troubleshooting guide section for this failure. Null for direct routes, except a pending T3 Connect sign-in. */
32 readonly moreInfoUrl: string | null;
33}
34
35export interface ConnectionDiagnosisInput {
36 readonly hostLabel: string;
37 readonly state: SupervisorConnectionState;
38 /** The environment's usual route, used when the failure does not name one. */
39 readonly via: "relay" | "direct";
40 /** The relay's last health check, which can name a cause before any connect attempt. */
41 readonly relayStatus?: Pick<
42 RelayEnvironmentStatusResponse,
43 "status" | "endpointFailure" | "endpointStatus" | "offlineReason"
44 > | null;
45 readonly clientVersion?: string | undefined;
46 readonly serverVersion?: string | null | undefined;
47}
48
49interface Located {
50 readonly hop: ConnectionHop;
51 readonly cause:
52 | ConnectionFailureCause
53 | "offline"
54 | "outdated"
55 | "released"
56 | "session_pending"
57 | null;
58 /** The failure named no hop, so the hops before this one were never probed. */
59 readonly guessed?: true;
60}
61
62const NOT_ANSWERING: ReadonlySet<ConnectionFailureCause> = new Set([
63 "origin_unreachable",
64 "invalid_response",
65]);
66
67function locate(input: ConnectionDiagnosisInput): Located | null {
68 const failure = input.state.lastFailure;
69 if (input.state.network === "offline" || input.state.phase === "offline") {
70 return { hop: "device", cause: "offline" };
71 }
72 if (failure?._tag === "ConnectionBlockedError" && failure.serverUpdateRequired) {
73 return { hop: "server", cause: "outdated" };
74 }
75 if (failure?.reason === "session-pending") {
76 return { hop: "device", cause: "session_pending" };
77 }
78 if (failure?.hop !== undefined) {
79 return { hop: failure.hop, cause: failure.failureCause ?? null };
80 }
81 if (failure !== null) {
82 const unreachable =
83 failure.reason === "network" ||
84 failure.reason === "timeout" ||
85 failure.reason === "transport";
86 const via = failure.via ?? input.via;
87 return {
88 hop: unreachable && via === "relay" ? "tunnel" : "server",
89 cause: null,
90 guessed: true,
91 };
92 }
93 const status = input.relayStatus;
94 if (status?.status !== "offline") return null;
95 if (status.offlineReason === "tunnel_released") return { hop: "tunnel", cause: "released" };
96 const cause = status.endpointFailure ?? null;
97 return { hop: cause !== null && NOT_ANSWERING.has(cause) ? "server" : "tunnel", cause };
98}
99
100function headline(
101 host: string,
102 located: Located,
103 failure: ConnectionAttemptError | null,
104 resolve: M,
105): string {
106 switch (located.cause) {
107 case "offline":
108 return resolve(msg("This device is offline"));
109 case "session_pending":
110 return resolve(msg("This device is still loading its T3 Connect sign-in"));
111 case "approval_pending":
112 return resolve(msg`${{ host }} is waiting for someone to approve this device`);
113 case "outdated":
114 return resolve(msg`${{ host }} runs an older T3 Code`);
115 case "clock_skew":
116 return resolve(msg("This device's clock is off"));
117 case "not_linked":
118 return resolve(msg`${{ host }} is not linked to your T3 Connect account`);
119 case "relay_error":
120 return resolve(msg("T3 Connect returned an error"));
121 case "tunnel_pending":
122 return resolve(msg`${{ host }}'s tunnel is still being set up`);
123 case "tunnel_not_enabled":
124 return resolve(msg`T3 Connect is not turned on for ${{ host }}`);
125 case "released":
126 case "tunnel_down":
127 return resolve(msg`${{ host }}'s tunnel is offline`);
128 case "origin_unreachable":
129 return resolve(msg`Tunnel works, but T3 Code on ${{ host }} did not answer`);
130 case "invalid_response":
131 return resolve(msg`T3 Code on ${{ host }} sent an unexpected answer`);
132 case "dns":
133 return resolve(msg`${{ host }}'s tunnel address did not resolve`);
134 case "tls":
135 return resolve(msg`Secure connection to ${{ host }}'s tunnel failed`);
136 case "refused":
137 return resolve(msg`${{ host }}'s tunnel refused the connection`);
138 case "timeout":
139 return resolve(msg`${{ host }} did not answer in time`);
140 case "unknown":
141 case null:
142 break;
143 }
144 switch (located.hop) {
145 case "device":
146 return resolve(msg("This device could not prepare the connection"));
147 case "relay":
148 return failure?.reason === "authentication"
149 ? resolve(msg("T3 Connect did not accept this device's sign-in"))
150 : resolve(msg("This device can't reach T3 Connect"));
151 case "tunnel":
152 // The relay already reached the host when this device fails on its own.
153 return failure?.reason === "network" ||
154 failure?.reason === "transport" ||
155 failure?.reason === "timeout"
156 ? resolve(msg`This device can't reach ${{ host }}'s tunnel`)
157 : resolve(msg`T3 Connect could not reach ${{ host }}'s tunnel`);
158 case "server":
159 return failure?.reason === "authentication" || failure?.reason === "permission"
160 ? resolve(msg`T3 Code on ${{ host }} did not accept this device`)
161 : resolve(msg`T3 Code on ${{ host }} did not answer`);
162 }
163}
164
165function steps(
166 host: string,
167 located: Located,
168 failure: ConnectionAttemptError | null,
169 resolve: M,
170): string[] {
171 const checkHost = resolve(
172 msg`On ${{ host }}, check Settings > Sharing & access or run \`t3 connect status\`.`,
173 );
174 switch (located.cause) {
175 case "offline":
176 return [resolve(msg("Connect this device to the internet. T3 Code reconnects on its own."))];
177 case "session_pending":
178 return [
179 resolve(msg("Wait a moment. T3 Code retries on its own.")),
180 resolve(msg("If it keeps waiting, reload or restart T3 Code on this device.")),
181 ];
182 case "approval_pending": {
183 const code =
184 failure?._tag === "ConnectionTransientError" ? failure.verificationCode : undefined;
185 return [
186 code
187 ? resolve(
188 msg`On a device already connected to ${{ host }}, open Settings > Sharing & access and approve the device showing ${{ code }}.`,
189 )
190 : resolve(
191 msg`On a device already connected to ${{ host }}, open Settings > Sharing & access and approve this device.`,
192 ),
193 resolve(
194 msg`Or run \`t3 auth connect-device approve ${{ code: code ?? "<code>" }}\` on ${{ host }}.`,
195 ),
196 ];
197 }
198 case "outdated":
199 return [resolve(msg`Update T3 Code on ${{ host }}.`)];
200 case "clock_skew":
201 return [
202 resolve(
203 msg`Turn on automatic date and time on this device and on ${{ host }}, then retry.`,
204 ),
205 ];
206 case "not_linked":
207 return [
208 resolve(
209 msg("Check that this device is signed in to the same T3 Connect account as the host."),
210 ),
211 resolve(msg`On ${{ host }}, open Settings > Sharing & access and turn T3 Connect on.`),
212 ];
213 case "tunnel_pending":
214 return [resolve(msg("Wait a minute. T3 Code retries on its own.")), checkHost];
215 case "relay_error":
216 return [
217 resolve(msg("Wait a few minutes. T3 Code retries on its own.")),
218 resolve(msg("If it keeps failing, copy the diagnostics and report it.")),
219 ];
220 case "tunnel_not_enabled":
221 return [
222 resolve(msg`On ${{ host }}, open Settings > Sharing & access and turn T3 Connect on.`),
223 ];
224 case "released":
225 case "tunnel_down":
226 return [
227 resolve(msg`Make sure ${{ host }} is awake and T3 Code is running on it.`),
228 checkHost,
229 resolve(
230 msg`A VPN or Tailscale exit node on ${{ host }} can block the tunnel (port 7844). Turn it off or allow the tunnel.`,
231 ),
232 ];
233 case "origin_unreachable":
234 case "invalid_response":
235 return [resolve(msg`Open or restart T3 Code on ${{ host }}.`), checkHost];
236 // The relay saw these on its way to the host, so the fix is on the host.
237 case "dns":
238 case "tls":
239 case "refused":
240 case "timeout":
241 case "unknown":
242 return [resolve(msg`Make sure ${{ host }} is awake and online.`), checkHost];
243 case null:
244 break;
245 }
246 switch (located.hop) {
247 case "device":
248 return [
249 resolve(msg("Restart T3 Code on this device.")),
250 resolve(msg`If it keeps failing, remove ${{ host }} from this device and add it again.`),
251 ];
252 case "relay":
253 return failure?.reason === "authentication"
254 ? [resolve(msg("Sign out of T3 Connect and sign in again."))]
255 : [
256 resolve(msg("Check this device's internet connection.")),
257 resolve(msg("A VPN, firewall, or ad blocker on this device can block T3 Connect.")),
258 ];
259 case "tunnel":
260 return failure?.reason === "network" ||
261 failure?.reason === "transport" ||
262 failure?.reason === "timeout"
263 ? [
264 resolve(msg("A VPN, firewall, or DNS filter on this device can block the tunnel.")),
265 resolve(msg("Try another network, or add a direct route such as a Tailscale address.")),
266 ]
267 : [resolve(msg`Make sure ${{ host }} is awake and online.`), checkHost];
268 case "server":
269 return failure?.reason === "authentication"
270 ? [
271 resolve(
272 msg`This device's sign-in to ${{ host }} expired or was revoked. Pair it again with a new pairing link from ${{ host }}.`,
273 ),
274 ]
275 : [
276 resolve(msg`Make sure T3 Code is running on ${{ host }}.`),
277 resolve(msg("Retry. If it keeps failing, copy the diagnostics.")),
278 ];
279 }
280}
281
282function helpSection(
283 located: Located,
284 failure: ConnectionAttemptError | null,
285): T3ConnectTroubleshootingSection {
286 switch (located.cause) {
287 case "offline":
288 return "this-device-cant-reach-t3-connect";
289 case "outdated":
290 return "the-host-runs-an-older-t3-code";
291 case "clock_skew":
292 return "the-clock-is-off";
293 case "session_pending":
294 case "approval_pending":
295 case "not_linked":
296 case "tunnel_not_enabled":
297 return "sign-in-account-or-link-problems";
298 case "relay_error":
299 return "t3-connect-returned-an-error";
300 case "released":
301 case "tunnel_down":
302 case "tunnel_pending":
303 return "the-hosts-tunnel-is-offline";
304 case "origin_unreachable":
305 case "invalid_response":
306 return "the-tunnel-works-but-t3-code-does-not-answer";
307 case "dns":
308 case "tls":
309 case "refused":
310 case "timeout":
311 case "unknown":
312 return "the-t3-connect-address-does-not-resolve-or-answer";
313 case null:
314 break;
315 }
316 const onThisDevice =
317 failure?.reason === "network" ||
318 failure?.reason === "transport" ||
319 failure?.reason === "timeout";
320 switch (located.hop) {
321 case "device":
322 return "this-device-cant-reach-t3-connect";
323 case "relay":
324 return failure?.reason === "authentication"
325 ? "sign-in-account-or-link-problems"
326 : "this-device-cant-reach-t3-connect";
327 case "tunnel":
328 return onThisDevice ? "this-device-cant-reach-t3-connect" : "the-hosts-tunnel-is-offline";
329 case "server":
330 return failure?.reason === "authentication" || failure?.reason === "permission"
331 ? "sign-in-account-or-link-problems"
332 : "the-tunnel-works-but-t3-code-does-not-answer";
333 }
334}
335
336const T3_CONNECT_NAME = "T3 Connect";
337
338const HOP_ORDER = {
339 relay: ["device", "relay", "tunnel", "server"],
340 direct: ["device", "server"],
341} as const;
342
343function hopLabel(hop: ConnectionHop, host: string, resolve: M): string {
344 switch (hop) {
345 case "device":
346 return resolve(msg("This device"));
347 case "relay":
348 return T3_CONNECT_NAME;
349 case "tunnel":
350 return resolve(msg`${{ host }} tunnel`);
351 case "server":
352 return resolve(msg`T3 Code on ${{ host }}`);
353 }
354}
355
356/**
357 * Turns a connection state into what failed, in order, and what to try. Returns
358 * null when nothing has failed. Web and mobile render this same model.
359 */
360export function presentConnectionDiagnosis(
361 input: ConnectionDiagnosisInput,
362 resolve: M = mFallback,
363): ConnectionDiagnosis | null {
364 const located = locate(input);
365 if (located === null) return null;
366 const host = input.hostLabel;
367 const failure = input.state.lastFailure;
368 const relayPath =
369 located.hop === "relay" ||
370 located.hop === "tunnel" ||
371 (failure === null && input.relayStatus?.status === "offline") ||
372 (failure?.via ?? input.via) === "relay";
373 const order: ReadonlyArray<ConnectionHop> = HOP_ORDER[relayPath ? "relay" : "direct"];
374 const failedIndex = order.indexOf(located.hop);
375 const hops = order.map((hop, index): ConnectionDiagnosisHop => ({
376 hop,
377 label: hopLabel(hop, host, resolve),
378 result:
379 index === failedIndex
380 ? "failed"
381 : index < failedIndex && located.guessed !== true
382 ? "ok"
383 : "unchecked",
384 }));
385
386 // The relay health check only explains the state when no attempt has failed yet.
387 const httpStatus = failure !== null ? failure.httpStatus : input.relayStatus?.endpointStatus;
388 const facts: Array<readonly [string, string]> = [];
389 const add = (label: string, value: string | number | null | undefined) => {
390 if (value !== null && value !== undefined && value !== "") facts.push([label, String(value)]);
391 };
392 add(
393 resolve(msg({ context: "diagnostics field label" })`Cause`),
394 located.cause ?? failure?.reason,
395 );
396 add(resolve(msg("HTTP status")), httpStatus);
397 add(
398 resolve(msg({ context: "diagnostics field label" })`Attempts`),
399 input.state.attempt > 0 ? input.state.attempt : null,
400 );
401 add(
402 resolve(msg("Next retry")),
403 input.state.retryAt === null
404 ? null
405 : DateTime.formatIso(DateTime.makeUnsafe(input.state.retryAt)),
406 );
407 add(
408 resolve(msg({ context: "diagnostics field label" })`Route`),
409 relayPath ? "T3 Connect" : resolve(msg({ context: "connection route" })`Direct`),
410 );
411 add(resolve(msg("App version")), input.clientVersion);
412 add(resolve(msg("Host version")), input.serverVersion);
413 add(resolve(msg({ context: "diagnostics field label" })`Error`), failure?.detail);
414 add(resolve(msg("Trace ID")), failure?.traceId);
415
416 return {
417 headline: headline(host, located, failure, resolve),
418 hops,
419 steps: steps(host, located, failure, resolve),
420 facts,
421 moreInfoUrl:
422 relayPath || located.cause === "session_pending"
423 ? t3ConnectTroubleshootingUrl(helpSection(located, failure))
424 : null,
425 };
426}
427
428const HOP_MARK = { ok: "ok", failed: "FAILED", unchecked: "not checked" } as const;
429
430/** One plain-text block for bug reports. */
431export function connectionDiagnosisText(hostLabel: string, diagnosis: ConnectionDiagnosis): string {
432 return [
433 `T3 Code connection to ${hostLabel}: ${diagnosis.headline}`,
434 "",
435 ...diagnosis.hops.map((hop) => `${hop.label}: ${HOP_MARK[hop.result]}`),
436 "",
437 ...diagnosis.facts.map(([label, value]) => `${label}: ${value}`),
438 ...(diagnosis.moreInfoUrl ? ["", `More info: ${diagnosis.moreInfoUrl}`] : []),
439 ].join("\n");
440}