Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

presentation.ts

220 lines7.7 KB

1import type { ServerConfig } from "@t3tools/contracts";
2import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
3import * as Option from "effect/Option";
4import { mFallback, msg } from "gt-i18n";
5import type { M } from "gt-i18n";
6​
7import { type MarkedText, resolveMarkedText } from "../errors/translatable.ts";
8import type { ConnectionCatalogEntry } from "./catalog.ts";
9import type { ConnectionTarget, SupervisorConnectionState } from "./model.ts";
10import { connectionRouteId, connectionRoutes, routeHttpBaseUrl } from "./routes.ts";
11​
12export type EnvironmentConnectionPhase =
13 | "available"
14 | "offline"
15 | "connecting"
16 | "reconnecting"
17 | "connected"
18 | "error"
19 | "unsupported";
20​
21export interface EnvironmentConnectionPresentation {
22 readonly phase: EnvironmentConnectionPhase;
23 readonly error: string | null;
24 /** `error` as marked text, when the failure carries it. Read both through `connectionErrorText`. */
25 readonly i18nError?: MarkedText;
26 readonly traceId: string | null;
27 /**
28 * Set while reconnecting because the host has not approved this device yet. `error` then
29 * says where to approve it and shows the code, and is not a failure.
30 */
31 readonly awaitingApproval?: true;
33​
34/**
35 * Provider statuses are pushed every few minutes with fresh `checkedAt` stamps, and every root
36 * coordinator reads environment presentations. Leaving them out keeps a presentation stable
37 * across those pushes; provider readers subscribe to the server's providers atom instead.
38 */
39export type EnvironmentServerConfig = Omit<ServerConfig, "providers">;
40​
41export interface EnvironmentPresentation {
42 readonly entry: ConnectionCatalogEntry;
43 readonly connection: EnvironmentConnectionPresentation;
44 readonly serverConfig: EnvironmentServerConfig | null;
45 /** See `SupervisorConnectionState.refusedRouteIds`. */
46 readonly refusedRouteIds: ReadonlyArray<string>;
48​
49function failureError(
50 failure: SupervisorConnectionState["lastFailure"],
51): Pick<EnvironmentConnectionPresentation, "error" | "i18nError" | "traceId"> {
52 return {
53 error: failure?.message ?? null,
54 ...(failure?.i18nMessage !== undefined ? { i18nError: failure.i18nMessage } : {}),
55 traceId: failure?.traceId ?? null,
56 };
58​
59export function presentConnectionState(
60 state: SupervisorConnectionState,
61): EnvironmentConnectionPresentation {
62 if (
63 (state.phase === "connecting" || state.phase === "backoff") &&
64 state.lastFailure?.reason === "approval-pending"
65 ) {
66 return {
67 phase: "reconnecting",
68 ...failureError(state.lastFailure),
69 awaitingApproval: true,
70 };
71 }
72 switch (state.phase) {
73 case "available":
74 return { phase: "available", error: null, traceId: null };
75 case "offline":
76 return { phase: "offline", error: null, traceId: null };
77 case "connecting":
78 return {
79 phase: state.attempt <= 1 && state.lastFailure === null ? "connecting" : "reconnecting",
80 ...failureError(state.lastFailure),
81 };
82 case "connected":
83 return { phase: "connected", error: null, traceId: null };
84 case "backoff":
85 return {
86 phase: "reconnecting",
87 ...failureError(state.lastFailure),
88 };
89 case "blocked":
90 return {
91 phase: state.lastFailure?.reason === "unsupported" ? "unsupported" : "error",
92 ...failureError(state.lastFailure),
93 };
94 }
96​
97/** The connection's error in the active language, or null when it has none. */
98export function connectionErrorText(
99 connection: Pick<EnvironmentConnectionPresentation, "error" | "i18nError">,
100 resolve: M = mFallback,
101): string | null {
102 if (connection.error === null) return null;
103 return connection.i18nError !== undefined
104 ? resolveMarkedText(connection.i18nError, resolve)
105 : connection.error;
107​
108export function connectionStatusText(
109 connection: EnvironmentConnectionPresentation,
110 resolve: M = mFallback,
111): string {
112 const error = connectionErrorText(connection, resolve);
113 switch (connection.phase) {
114 case "available":
115 return resolve(msg({ context: "connection status" })`Available`);
116 case "offline":
117 return resolve(msg({ context: "connection status" })`Offline`);
118 case "connecting":
119 return resolve(msg("Connecting..."));
120 case "reconnecting":
121 if (connection.awaitingApproval) {
122 return error ?? resolve(msg("Waiting for approval on the host"));
123 }
124 return error
125 ? resolve(msg`Failed to connect. Reconnecting... Reason: ${{ error }}`)
126 : resolve(msg("Reconnecting..."));
127 case "connected":
128 return resolve(msg({ context: "connection status" })`Connected`);
129 case "unsupported":
130 return resolve(msg("Client not supported"));
131 case "error":
132 return error
133 ? resolve(msg`Connection failed. Reason: ${{ error }}`)
134 : resolve(msg("Connection failed"));
135 }
137​
138export function connectionStatusTitle(
139 connection: EnvironmentConnectionPresentation,
140 resolve: M = mFallback,
141): string {
142 if (connection.awaitingApproval) {
143 return resolve(msg("Waiting for approval"));
144 }
145 if (connection.phase === "reconnecting" && connection.error) {
146 return resolve(msg("Failed to connect. Reconnecting..."));
147 }
148 return connectionStatusText({ ...connection, error: null }, resolve);
150​
151/**
152 * The T3 Connect address wins whenever it is known: it works for agents anywhere, while the
153 * connected route is often a LAN or loopback address. SSH routes ride a local forward that
154 * disappears with the client, so they have no stable address.
155 */
156export function environmentMcpUrl(input: {
157 readonly entry: ConnectionCatalogEntry;
158 readonly relayHttpBaseUrl?: string | undefined;
159 readonly connectedTarget?: ConnectionTarget | null | undefined;
160}): string | null {
161 const relayMcpUrl = input.relayHttpBaseUrl ? mcpUrlFromBase(input.relayHttpBaseUrl) : null;
162 if (relayMcpUrl !== null) return relayMcpUrl;
163 const connectedRouteId = input.connectedTarget ? connectionRouteId(input.connectedTarget) : null;
164 const routes = connectionRoutes(input.entry);
165 const connectedRoute = routes.find(
166 (route) => connectionRouteId(route.target) === connectedRouteId,
167 );
168 for (const route of connectedRoute ? [connectedRoute, ...routes] : routes) {
169 const httpBaseUrl = routeHttpBaseUrl(route);
170 const mcpUrl = httpBaseUrl === null ? null : mcpUrlFromBase(httpBaseUrl);
171 if (mcpUrl !== null) return mcpUrl;
172 }
173 return null;
175​
176/**
177 * The MCP address for the environment this app runs. Agents only sign in over https or
178 * loopback, so a plain-http LAN address is not offered.
179 */
180export function localEnvironmentMcpUrl(input: {
181 readonly entry: ConnectionCatalogEntry;
182}): string | null {
183 const mcpUrl = environmentMcpUrl({ entry: input.entry });
184 return mcpUrl !== null && isAgentSignInMcpUrl(mcpUrl) ? mcpUrl : null;
186​
187function isAgentSignInMcpUrl(mcpUrl: string): boolean {
188 const url = new URL(mcpUrl);
189 return url.protocol === "https:" || isLocalLoopbackHost(url.hostname);
191​
192function mcpUrlFromBase(httpBaseUrl: string): string | null {
193 let url: URL;
194 try {
195 url = new URL(httpBaseUrl);
196 } catch {
197 return null;
198 }
199 url.pathname = "/mcp";
200 url.search = "";
201 url.hash = "";
202 return url.toString();
204​
205export function connectionCatalogDisplayUrl(entry: ConnectionCatalogEntry): string | null {
206 switch (entry.target._tag) {
207 case "PrimaryConnectionTarget":
208 return entry.target.httpBaseUrl;
209 case "RelayConnectionTarget":
210 return null;
211 case "BearerConnectionTarget":
212 return Option.isSome(entry.profile) && entry.profile.value._tag === "BearerConnectionProfile"
213 ? entry.profile.value.httpBaseUrl
214 : null;
215 case "SshConnectionTarget":
216 return Option.isSome(entry.profile) && entry.profile.value._tag === "SshConnectionProfile"
217 ? `${entry.profile.value.target.username}@${entry.profile.value.target.hostname}`
218 : null;
219 }