The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
feat: connect to a linked environment from its read-only thread (#39439)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 20, 2026 at 12:15 UTC
d7f6b3efcac375160bbe20e28276be853eaf7315
52 files changed
+1518
-64
apps/mobile/src/connection/onboarding.ts
+8
@@ -44,3 +44,11 @@ export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime
44
Effect.flatMap((onboarding) => onboarding.updateBearer(input)),
45
),
46
});
47
+
48
+export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, {
49
+ label: "mobile:connection:reaches-environment",
50
+ execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) =>
51
+ ConnectionOnboarding.ConnectionOnboarding.pipe(
52
+ Effect.flatMap((onboarding) => onboarding.reaches(input)),
53
+ ),
54
+});
apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+24
-7
@@ -30,6 +30,7 @@ import { SymbolView } from "../../components/ui/AppSymbol";
30
import { hasCloudPublicConfig } from "../cloud/publicConfig";
31
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
32
import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
33
+import { linkedEnvironmentPrefillAtom } from "./linkedEnvironmentPrefill";
34
import { splitEnvironmentSections } from "./environmentSections";
35
import { leaveSettingsPage } from "../settings/settings-navigation";
36
import { workspaceHasColumns } from "../layout/workspace/workspace-selection-store";
@@ -40,6 +41,8 @@ type ConnectionsNewRouteParams = {
41
readonly pairingUrl?: string;
42
readonly autoConnect?: string;
43
readonly routeFor?: EnvironmentId;
44
+ /** A linked machine this app chose to pair with; its details come from app state, never the link. */
45
+ readonly linked?: string;
46
};
47
48
export function ConnectionsNewRouteScreen({
@@ -48,12 +51,15 @@ export function ConnectionsNewRouteScreen({
51
const params = route.params ?? {};
52
// Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
53
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
54
+ const known = useAtomValue(linkedEnvironmentPrefillAtom);
55
+ const linked = known !== null && known.environmentId === params.linked ? known : null;
56
// A new prefill link replaces whatever the form held.
57
return (
58
<PairingForm
54
- key={routePairingUrl}
59
+ key={`${routePairingUrl}:${linked?.environmentId ?? ""}`}
60
routePairingUrl={routePairingUrl}
56
- routeFor={params.routeFor}
61
+ routeFor={params.routeFor ?? linked?.environmentId}
62
+ linked={linked}
63
/>
64
);
65
}
@@ -61,9 +67,11 @@ export function ConnectionsNewRouteScreen({
67
function PairingForm({
68
routePairingUrl,
69
routeFor,
70
+ linked,
71
}: {
72
readonly routePairingUrl: string;
73
readonly routeFor: EnvironmentId | undefined;
74
+ readonly linked: { readonly label: string; readonly host: string | null } | null;
75
}) {
76
const gt = useGT();
77
const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } =
@@ -71,7 +79,7 @@ function PairingForm({
79
const navigation = useNavigation();
80
const insets = useSafeAreaInsets();
81
const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl));
74
- const [hostInput, setHostInput] = useState(initialPairing.host);
82
+ const [hostInput, setHostInput] = useState(linked?.host ?? initialPairing.host);
83
const [codeInput, setCodeInput] = useState(initialPairing.code);
84
const [isSubmitting, setIsSubmitting] = useState(false);
85
const [submitError, setSubmitError] = useState<string | null>(null);
@@ -188,7 +196,11 @@ function PairingForm({
196
197
return (
198
<SettingsScreen
191
- title={gt("Add environment")}
199
+ title={
200
+ linked
201
+ ? gt("Connect to {environment}", { environment: linked.label })
202
+ : gt("Add environment")
203
+ }
204
actions={[
205
{
206
accessibilityLabel: connecting
@@ -263,9 +275,14 @@ function PairingForm({
275
)}
276
>
277
{pairingConnectionError ??
266
- gt(
267
- "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
268
- )}
278
+ (linked
279
+ ? gt(
280
+ "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
281
+ { environment: linked.label },
282
+ )
283
+ : gt(
284
+ "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
285
+ ))}
286
</Text>
287
</View>
288
apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts
new
+12
@@ -0,0 +1,12 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import { Atom } from "effect/reactivity";
3
+
4
+/**
5
+ * A linked machine the add-environment screen opens for, with what the environment that links to
6
+ * it said about it. Set only by this app; a route names the machine and never supplies an address.
7
+ */
8
+export const linkedEnvironmentPrefillAtom = Atom.make<{
9
+ readonly environmentId: EnvironmentId;
10
+ readonly label: string;
11
+ readonly host: string | null;
12
+} | null>(null).pipe(Atom.withLabel("linked-environment-prefill"));
apps/mobile/src/features/threads/LinkedThreadSheet.tsx
+63
-3
@@ -1,4 +1,9 @@
1
-import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
1
+import {
2
+ StackActions,
3
+ useIsFocused,
4
+ useNavigation,
5
+ type StaticScreenProps,
6
+} from "@react-navigation/native";
7
import {
8
isLinkedThreadWorking,
9
linkedThreadFailure,
@@ -31,11 +36,12 @@ import {
36
type ThreadFeedActivity,
37
type ThreadFeedEntry,
38
} from "../../lib/threadActivity";
34
-import { useLinkedThreadView } from "../../state/linkedThread";
39
+import { useConnectLinkedEnvironment, useLinkedThreadView } from "../../state/linkedThread";
40
import { peerLinkEnvironment } from "../../state/peerLinks";
41
import { useEnvironmentQuery } from "../../state/query";
42
import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
43
import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar";
44
+import { useOpenLinkedThread } from "./useOpenLinkedThread";
45
46
type LinkedThreadRouteParams = {
47
readonly viaEnvironmentId: string;
@@ -290,6 +296,21 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) {
296
// Follows new items only while the reader is already at the end.
297
const atEnd = useRef(true);
298
const working = projection !== null && isLinkedThreadWorking(projection);
299
+ const connection = useConnectLinkedEnvironment(target);
300
+ const connectState = connection.state;
301
+ const openThread = useOpenLinkedThread();
302
+ const connect = async () => {
303
+ const outcome = await connection.connect();
304
+ if (outcome.type === "unreachable") return;
305
+ // This sheet closes either way: the thread opens where the app is now connected, or the
306
+ // add-environment screen takes its place.
307
+ if (outcome.type === "connected") {
308
+ navigation.goBack();
309
+ openThread({ environmentId: target.environmentId, threadId: target.threadId });
310
+ return;
311
+ }
312
+ navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId }));
313
+ };
314
return (
315
<View collapsable={false} className="flex-1 bg-sheet">
316
<SheetHeader
@@ -355,7 +376,46 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) {
376
className="gap-2 px-3 pt-1.5"
377
style={{ paddingBottom: Math.max(insets.bottom, 10) + 6 }}
378
>
358
- <LinkedThreadComposer label={label} via={via} working={working} />
379
+ <LinkedThreadComposer
380
+ label={label}
381
+ via={via}
382
+ working={working}
383
+ action={
384
+ <Button
385
+ tone="secondary"
386
+ label={gt("Connect to interact")}
387
+ loading={connectState.phase === "connecting"}
388
+ onPress={() => void connect()}
389
+ />
390
+ }
391
+ notice={
392
+ connectState.phase === "connecting" ? (
393
+ <Text
394
+ accessibilityLiveRegion="polite"
395
+ className="px-2 text-xs text-foreground-muted"
396
+ >
397
+ {gt("Connecting to {environment}...", { environment: label })}
398
+ </Text>
399
+ ) : connectState.phase === "unreachable" ? (
400
+ <View
401
+ accessibilityLiveRegion="polite"
402
+ className="gap-1 rounded-2xl border border-danger-border bg-danger px-3.5 py-3"
403
+ >
404
+ <Text className="font-t3-medium text-sm text-danger-foreground">
405
+ {gt("{label} is not reachable from this device", {
406
+ label: connectState.label,
407
+ })}
408
+ </Text>
409
+ <Text className="text-sm text-danger-foreground">
410
+ <T>
411
+ Join a network it is on, such as its Tailscale network, and try again. You can
412
+ keep reading here.
413
+ </T>
414
+ </Text>
415
+ </View>
416
+ ) : null
417
+ }
418
+ />
419
</View>
420
</ScreenContent>
421
</View>
apps/mobile/src/i18n/translations/de.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "T3 Code auf {host} war zu beschäftigt, um zu antworten.",
458
"5c5941732d5dfac6": "Die Kopplungsdaten sind ungültig.",
459
"b8ca23ad7dda376e": "Diese Adresse führt zu {host}, einem anderen Rechner. Füge sie stattdessen als eigene Umgebung hinzu.",
460
+ "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
461
"693cb5c4fb40f109": "Nur gespeicherte Bearer-Umgebungen können bearbeitet werden.",
462
"5f5844b910cb1544": "Die gespeicherten Bearer-Zugangsdaten sind nicht verfügbar.",
463
"51b0133f1ed3cf5c": "Die Bezeichnung der Umgebung darf nicht leer sein.",
463
- "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
464
"3aa15bfbe1920376": "Aktualisiere T3 Code auf {host} manuell; es kann sich nicht selbst aktualisieren.",
465
"71907f57b7ec64d5": "{host} ist nicht mit einer kompatiblen T3-Code-Version zurückgekommen.",
466
"e77ac580a4ddcd3b": "Verfügbar",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "Einstellungen öffnen",
1970
"41e3df8a7b6d5d9d": "Ungültiger QR-Code",
1971
"c28525066e29c024": "Der gescannte QR-Code wurde nicht erkannt.",
1972
+ "8a333daf9b7fd03f": "Mit {environment} verbinden",
1973
"53c162d8868a1d0e": "Umgebung hinzufügen",
1974
"403dd9b445331000": "Wird verbunden",
1975
"44bbcfd33b751bd6": "Adresse",
1976
"42fd195574793f9e": "Code",
1977
"51b31345c7bed6f0": "Kopplungscode",
1978
+ "e1cb1c8599e84e26": "Erstelle auf {environment} einen Kopplungscode, in dessen Einstellungen → Freigabe & Zugriff oder mit `t3 auth pairing create`, und gib ihn hier ein.",
1979
"7d6f419f8ab7f779": "Für Rechner in deinem lokalen Netzwerk oder Tailnet. Der Rechner behält seine eigenen Anbieter-Anmeldedaten.",
1980
"36f32bd159bdc0d1": "QR-Code scannen",
1981
"11fd02455d938901": "Scanne den Code von {command} oder aus den Verbindungseinstellungen am Desktop",
@@ -4158,8 +4160,11 @@
4160
"009e2ca841fdc1ef": "diese Umgebung",
4161
"596842e9e887232b": "Wird von {label} gelesen …",
4162
"ff889c17671b40af": "Frühere laden",
4163
+ "d49e5c66faa5d153": "Verbinden, um zu interagieren",
4164
+ "93e690821c726e13": "{label} ist von diesem Gerät aus nicht erreichbar",
4165
"0014ce0aaf1bd68a": "Schreibgeschützt",
4166
"048b8a737af895ac": "Noch nichts in diesem Thread.",
4167
+ "d148218513d9950a": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.",
4168
"1410155e503a917f": "{denial} Wechsle den Modus dieses Threads, um fortzufahren.",
4169
"81ceeceeb521bba6": "Zu {mode} wechseln",
4170
"6ebd73c7bfb58bb7": "App",
apps/mobile/src/i18n/translations/en.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "T3 Code on {host} was too busy to answer.",
458
"5c5941732d5dfac6": "The pairing details are invalid.",
459
"b8ca23ad7dda376e": "That address reaches {host}, a different machine. Add it as its own environment instead.",
460
+ "0c0150a90b582a7a": "The environment URL is invalid.",
461
"693cb5c4fb40f109": "Only saved bearer environments can be edited.",
462
"5f5844b910cb1544": "The saved bearer credential is unavailable.",
463
"51b0133f1ed3cf5c": "Environment label cannot be empty.",
463
- "0c0150a90b582a7a": "The environment URL is invalid.",
464
"3aa15bfbe1920376": "Update T3 Code on {host} manually; it cannot update itself.",
465
"71907f57b7ec64d5": "{host} did not come back on a compatible T3 Code version.",
466
"e77ac580a4ddcd3b": "Available",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "Open Settings",
1970
"41e3df8a7b6d5d9d": "Invalid QR code",
1971
"c28525066e29c024": "Scanned QR code was not recognized.",
1972
+ "8a333daf9b7fd03f": "Connect to {environment}",
1973
"53c162d8868a1d0e": "Add environment",
1974
"403dd9b445331000": "Connecting",
1975
"44bbcfd33b751bd6": "Address",
1976
"42fd195574793f9e": "Code",
1977
"51b31345c7bed6f0": "Pairing code",
1978
+ "e1cb1c8599e84e26": "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
1979
"7d6f419f8ab7f779": "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
1980
"36f32bd159bdc0d1": "Scan QR code",
1981
"11fd02455d938901": "Scan the code from {command} or desktop Connections settings",
@@ -4159,8 +4161,11 @@
4161
"009e2ca841fdc1ef": "this environment",
4162
"596842e9e887232b": "Reading from {label}…",
4163
"ff889c17671b40af": "Load earlier",
4164
+ "d49e5c66faa5d153": "Connect to interact",
4165
+ "93e690821c726e13": "{label} is not reachable from this device",
4166
"0014ce0aaf1bd68a": "Read-only",
4167
"048b8a737af895ac": "Nothing in this thread yet.",
4168
+ "d148218513d9950a": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.",
4169
"1410155e503a917f": "{denial} Switch this thread's mode to continue.",
4170
"81ceeceeb521bba6": "Switch to {mode}",
4171
"6ebd73c7bfb58bb7": "App",
apps/mobile/src/i18n/translations/es.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "T3 Code en {host} estaba demasiado ocupado para responder.",
458
"5c5941732d5dfac6": "Los datos de emparejamiento no son válidos.",
459
"b8ca23ad7dda376e": "Esa dirección lleva a {host}, otra máquina. Añádela como un entorno propio.",
460
+ "0c0150a90b582a7a": "La URL del entorno no es válida.",
461
"693cb5c4fb40f109": "Solo se pueden editar los entornos bearer guardados.",
462
"5f5844b910cb1544": "La credencial bearer guardada no está disponible.",
463
"51b0133f1ed3cf5c": "La etiqueta del entorno no puede estar vacía.",
463
- "0c0150a90b582a7a": "La URL del entorno no es válida.",
464
"3aa15bfbe1920376": "Actualiza T3 Code en {host} manualmente; no puede actualizarse solo.",
465
"71907f57b7ec64d5": "{host} no volvió con una versión compatible de T3 Code.",
466
"e77ac580a4ddcd3b": "Disponible",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "Abrir Ajustes",
1970
"41e3df8a7b6d5d9d": "Código QR no válido",
1971
"c28525066e29c024": "No se reconoció el código QR escaneado.",
1972
+ "8a333daf9b7fd03f": "Conectar con {environment}",
1973
"53c162d8868a1d0e": "Añadir entorno",
1974
"403dd9b445331000": "Conectando",
1975
"44bbcfd33b751bd6": "Dirección",
1976
"42fd195574793f9e": "Código",
1977
"51b31345c7bed6f0": "Código de emparejamiento",
1978
+ "e1cb1c8599e84e26": "Crea un código de emparejamiento en {environment}, en sus Ajustes → Compartir y acceso o con `t3 auth pairing create`, e introdúcelo aquí.",
1979
"7d6f419f8ab7f779": "Para máquinas de tu red local o tailnet. La máquina conserva sus propias credenciales de proveedores.",
1980
"36f32bd159bdc0d1": "Escanear código QR",
1981
"11fd02455d938901": "Escanea el código de {command} o de los ajustes de Conexiones del escritorio",
@@ -4153,8 +4155,11 @@
4155
"009e2ca841fdc1ef": "este entorno",
4156
"596842e9e887232b": "Leyendo desde {label}…",
4157
"ff889c17671b40af": "Cargar anteriores",
4158
+ "d49e5c66faa5d153": "Conectar para interactuar",
4159
+ "93e690821c726e13": "No se puede acceder a {label} desde este dispositivo",
4160
"0014ce0aaf1bd68a": "Solo lectura",
4161
"048b8a737af895ac": "Aún no hay nada en este hilo.",
4162
+ "d148218513d9950a": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.",
4163
"1410155e503a917f": "{denial} Cambia el modo de este hilo para continuar.",
4164
"81ceeceeb521bba6": "Cambiar a {mode}",
4165
"6ebd73c7bfb58bb7": "App",
apps/mobile/src/i18n/translations/fr.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "T3 Code sur {host} était trop occupé pour répondre.",
458
"5c5941732d5dfac6": "Les informations d’appairage ne sont pas valides.",
459
"b8ca23ad7dda376e": "Cette adresse mène à {host}, une autre machine. Ajoutez-la plutôt comme environnement distinct.",
460
+ "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
461
"693cb5c4fb40f109": "Seuls les environnements bearer enregistrés peuvent être modifiés.",
462
"5f5844b910cb1544": "Les identifiants bearer enregistrés ne sont pas disponibles.",
463
"51b0133f1ed3cf5c": "Le libellé de l’environnement ne peut pas être vide.",
463
- "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
464
"3aa15bfbe1920376": "Mettez à jour T3 Code sur {host} manuellement ; il ne peut pas se mettre à jour seul.",
465
"71907f57b7ec64d5": "{host} n’est pas revenu sur une version compatible de T3 Code.",
466
"e77ac580a4ddcd3b": "Disponible",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "Ouvrir les Réglages",
1970
"41e3df8a7b6d5d9d": "Code QR non valide",
1971
"c28525066e29c024": "Le code QR scanné n’a pas été reconnu.",
1972
+ "8a333daf9b7fd03f": "Se connecter à {environment}",
1973
"53c162d8868a1d0e": "Ajouter un environnement",
1974
"403dd9b445331000": "Connexion",
1975
"44bbcfd33b751bd6": "Adresse",
1976
"42fd195574793f9e": "Code",
1977
"51b31345c7bed6f0": "Code d’appairage",
1978
+ "e1cb1c8599e84e26": "Créez un code d’appairage sur {environment}, dans ses Paramètres → Partage et accès ou avec `t3 auth pairing create`, puis saisissez-le ici.",
1979
"7d6f419f8ab7f779": "Pour les machines de votre réseau local ou de votre tailnet. La machine garde ses propres identifiants de fournisseur.",
1980
"36f32bd159bdc0d1": "Scanner un code QR",
1981
"11fd02455d938901": "Scannez le code de {command} ou des paramètres Connexions du bureau",
@@ -4153,8 +4155,11 @@
4155
"009e2ca841fdc1ef": "cet environnement",
4156
"596842e9e887232b": "Lecture depuis {label}…",
4157
"ff889c17671b40af": "Charger les précédents",
4158
+ "d49e5c66faa5d153": "Se connecter pour interagir",
4159
+ "93e690821c726e13": "{label} n’est pas accessible depuis cet appareil",
4160
"0014ce0aaf1bd68a": "Lecture seule",
4161
"048b8a737af895ac": "Rien dans ce fil pour l’instant.",
4162
+ "d148218513d9950a": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.",
4163
"1410155e503a917f": "{denial} Changez le mode de ce fil pour continuer.",
4164
"81ceeceeb521bba6": "Passer en {mode}",
4165
"6ebd73c7bfb58bb7": "App",
apps/mobile/src/i18n/translations/ja.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "{host} の T3 Code はビジー状態で応答できませんでした。",
458
"5c5941732d5dfac6": "ペアリングの詳細が無効です。",
459
"b8ca23ad7dda376e": "そのアドレスは別のマシンである {host} につながります。代わりに独立した環境として追加してください。",
460
+ "0c0150a90b582a7a": "環境の URL が無効です。",
461
"693cb5c4fb40f109": "編集できるのは保存済みのベアラー環境のみです。",
462
"5f5844b910cb1544": "保存済みのベアラー資格情報は利用できません。",
463
"51b0133f1ed3cf5c": "環境のラベルは空にできません。",
463
- "0c0150a90b582a7a": "環境の URL が無効です。",
464
"3aa15bfbe1920376": "{host} の T3 Code は自動で更新できないため、手動で更新してください。",
465
"71907f57b7ec64d5": "{host} は互換性のある T3 Code のバージョンで復帰しませんでした。",
466
"e77ac580a4ddcd3b": "利用可能",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "設定を開く",
1970
"41e3df8a7b6d5d9d": "無効な QR コード",
1971
"c28525066e29c024": "スキャンした QR コードを認識できませんでした。",
1972
+ "8a333daf9b7fd03f": "{environment} に接続",
1973
"53c162d8868a1d0e": "環境を追加",
1974
"403dd9b445331000": "接続中",
1975
"44bbcfd33b751bd6": "アドレス",
1976
"42fd195574793f9e": "コード",
1977
"51b31345c7bed6f0": "ペアリングコード",
1978
+ "e1cb1c8599e84e26": "{environment} の設定 → 共有とアクセス、または `t3 auth pairing create` でペアリングコードを作成し、ここに入力してください。",
1979
"7d6f419f8ab7f779": "ローカルネットワークや tailnet 上のマシン向けです。マシンはプロバイダーの認証情報を自身で保持します。",
1980
"36f32bd159bdc0d1": "QR コードをスキャン",
1981
"11fd02455d938901": "{command} またはデスクトップの接続設定に表示されるコードをスキャンしてください",
@@ -4149,8 +4151,11 @@
4151
"009e2ca841fdc1ef": "この環境",
4152
"596842e9e887232b": "{label} から読み取り中…",
4153
"ff889c17671b40af": "以前のものを読み込む",
4154
+ "d49e5c66faa5d153": "接続して操作する",
4155
+ "93e690821c726e13": "このデバイスから {label} に接続できません",
4156
"0014ce0aaf1bd68a": "読み取り専用",
4157
"048b8a737af895ac": "このスレッドにはまだ何もありません。",
4158
+ "d148218513d9950a": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。",
4159
"1410155e503a917f": "{denial} 続行するには、このスレッドのモードを切り替えてください。",
4160
"81ceeceeb521bba6": "{mode} に切り替え",
4161
"6ebd73c7bfb58bb7": "アプリ",
apps/mobile/src/i18n/translations/ko.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "{host}의 T3 Code가 너무 바빠서 응답하지 못했습니다.",
458
"5c5941732d5dfac6": "페어링 정보가 올바르지 않습니다.",
459
"b8ca23ad7dda376e": "이 주소는 다른 머신인 {host}에 연결됩니다. 대신 별도의 환경으로 추가하세요.",
460
+ "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
461
"693cb5c4fb40f109": "저장된 bearer 환경만 편집할 수 있습니다.",
462
"5f5844b910cb1544": "저장된 bearer 자격 증명을 사용할 수 없습니다.",
463
"51b0133f1ed3cf5c": "환경 레이블은 비워 둘 수 없습니다.",
463
- "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
464
"3aa15bfbe1920376": "{host}의 T3 Code는 스스로 업데이트할 수 없으니 직접 업데이트하세요.",
465
"71907f57b7ec64d5": "{host}이(가) 호환되는 T3 Code 버전으로 돌아오지 않았습니다.",
466
"e77ac580a4ddcd3b": "사용 가능",
@@ -1970,11 +1970,13 @@
1970
"28ae2c5e144a8c02": "설정 열기",
1971
"41e3df8a7b6d5d9d": "잘못된 QR 코드",
1972
"c28525066e29c024": "스캔한 QR 코드를 인식할 수 없습니다.",
1973
+ "8a333daf9b7fd03f": "{environment}에 연결",
1974
"53c162d8868a1d0e": "환경 추가",
1975
"403dd9b445331000": "연결 중",
1976
"44bbcfd33b751bd6": "주소",
1977
"42fd195574793f9e": "코드",
1978
"51b31345c7bed6f0": "페어링 코드",
1979
+ "e1cb1c8599e84e26": "{environment}의 설정 → 공유 및 액세스에서 또는 `t3 auth pairing create`로 페어링 코드를 만든 다음 여기에 입력하세요.",
1980
"7d6f419f8ab7f779": "로컬 네트워크나 tailnet에 있는 머신용입니다. 머신은 자체 제공자 자격 증명을 유지합니다.",
1981
"36f32bd159bdc0d1": "QR 코드 스캔",
1982
"11fd02455d938901": "{command} 또는 데스크톱 연결 설정의 코드를 스캔하세요",
@@ -4153,8 +4155,11 @@
4155
"009e2ca841fdc1ef": "이 환경",
4156
"596842e9e887232b": "{label}에서 읽는 중…",
4157
"ff889c17671b40af": "이전 항목 불러오기",
4158
+ "d49e5c66faa5d153": "연결하여 상호작용",
4159
+ "93e690821c726e13": "이 기기에서 {label}에 연결할 수 없습니다",
4160
"0014ce0aaf1bd68a": "읽기 전용",
4161
"048b8a737af895ac": "이 스레드에는 아직 아무것도 없습니다.",
4162
+ "d148218513d9950a": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.",
4163
"1410155e503a917f": "{denial} 계속하려면 이 스레드의 모드를 전환하세요.",
4164
"81ceeceeb521bba6": "{mode}(으)로 전환",
4165
"6ebd73c7bfb58bb7": "앱",
apps/mobile/src/i18n/translations/pt-BR.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "O T3 Code em {host} estava ocupado demais para responder.",
458
"5c5941732d5dfac6": "Os detalhes de pareamento são inválidos.",
459
"b8ca23ad7dda376e": "Esse endereço leva a {host}, outra máquina. Adicione-a como um ambiente próprio.",
460
+ "0c0150a90b582a7a": "A URL do ambiente é inválida.",
461
"693cb5c4fb40f109": "Só é possível editar ambientes bearer salvos.",
462
"5f5844b910cb1544": "A credencial bearer salva não está disponível.",
463
"51b0133f1ed3cf5c": "O rótulo do ambiente não pode ficar vazio.",
463
- "0c0150a90b582a7a": "A URL do ambiente é inválida.",
464
"3aa15bfbe1920376": "Atualize o T3 Code em {host} manualmente; ele não consegue se atualizar sozinho.",
465
"71907f57b7ec64d5": "{host} não voltou em uma versão compatível do T3 Code.",
466
"e77ac580a4ddcd3b": "Disponível",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "Abrir Ajustes",
1970
"41e3df8a7b6d5d9d": "QR code inválido",
1971
"c28525066e29c024": "O QR code escaneado não foi reconhecido.",
1972
+ "8a333daf9b7fd03f": "Conectar a {environment}",
1973
"53c162d8868a1d0e": "Adicionar ambiente",
1974
"403dd9b445331000": "Conectando",
1975
"44bbcfd33b751bd6": "Endereço",
1976
"42fd195574793f9e": "Código",
1977
"51b31345c7bed6f0": "Código de pareamento",
1978
+ "e1cb1c8599e84e26": "Crie um código de pareamento em {environment}, em Configurações → Compartilhamento e acesso ou com `t3 auth pairing create`, e insira-o aqui.",
1979
"7d6f419f8ab7f779": "Para máquinas na sua rede local ou tailnet. A máquina mantém as próprias credenciais dos provedores.",
1980
"36f32bd159bdc0d1": "Escanear QR code",
1981
"11fd02455d938901": "Escaneie o código de {command} ou das configurações de Conexões do desktop",
@@ -4153,8 +4155,11 @@
4155
"009e2ca841fdc1ef": "este ambiente",
4156
"596842e9e887232b": "Lendo de {label}…",
4157
"ff889c17671b40af": "Carregar anteriores",
4158
+ "d49e5c66faa5d153": "Conectar para interagir",
4159
+ "93e690821c726e13": "{label} não está acessível a partir deste dispositivo",
4160
"0014ce0aaf1bd68a": "Somente leitura",
4161
"048b8a737af895ac": "Ainda não há nada nesta thread.",
4162
+ "d148218513d9950a": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.",
4163
"1410155e503a917f": "{denial} Mude o modo desta thread para continuar.",
4164
"81ceeceeb521bba6": "Mudar para {mode}",
4165
"6ebd73c7bfb58bb7": "App",
apps/mobile/src/i18n/translations/ru.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "T3 Code на {host} был слишком занят, чтобы ответить.",
458
"5c5941732d5dfac6": "Данные сопряжения недействительны.",
459
"b8ca23ad7dda376e": "Этот адрес ведёт к {host}, другому компьютеру. Добавьте его как отдельное окружение.",
460
+ "0c0150a90b582a7a": "URL окружения недействителен.",
461
"693cb5c4fb40f109": "Изменять можно только сохранённые окружения с bearer-токеном.",
462
"5f5844b910cb1544": "Сохранённые bearer-учётные данные недоступны.",
463
"51b0133f1ed3cf5c": "Название окружения не может быть пустым.",
463
- "0c0150a90b582a7a": "URL окружения недействителен.",
464
"3aa15bfbe1920376": "Обновите T3 Code на {host} вручную: он не может обновиться сам.",
465
"71907f57b7ec64d5": "{host} не вернулся с совместимой версией T3 Code.",
466
"e77ac580a4ddcd3b": "Доступно",
@@ -1993,11 +1993,13 @@
1993
"28ae2c5e144a8c02": "Открыть настройки",
1994
"41e3df8a7b6d5d9d": "Недействительный QR-код",
1995
"c28525066e29c024": "Отсканированный QR-код не распознан.",
1996
+ "8a333daf9b7fd03f": "Подключиться к {environment}",
1997
"53c162d8868a1d0e": "Добавить окружение",
1998
"403dd9b445331000": "Подключение",
1999
"44bbcfd33b751bd6": "Адрес",
2000
"42fd195574793f9e": "Код",
2001
"51b31345c7bed6f0": "Код сопряжения",
2002
+ "e1cb1c8599e84e26": "Создайте код сопряжения на {environment} в разделе «Настройки → Общий доступ» или командой `t3 auth pairing create` и введите его здесь.",
2003
"7d6f419f8ab7f779": "Для машин в вашей локальной сети или tailnet. Машина хранит собственные учётные данные провайдеров.",
2004
"36f32bd159bdc0d1": "Сканировать QR-код",
2005
"11fd02455d938901": "Отсканируйте код из {command} или из настроек подключений в десктопном приложении",
@@ -4207,8 +4209,11 @@
4209
"009e2ca841fdc1ef": "это окружение",
4210
"596842e9e887232b": "Чтение с {label}…",
4211
"ff889c17671b40af": "Загрузить более ранние",
4212
+ "d49e5c66faa5d153": "Подключиться для взаимодействия",
4213
+ "93e690821c726e13": "{label} недоступно с этого устройства",
4214
"0014ce0aaf1bd68a": "Только чтение",
4215
"048b8a737af895ac": "В этом треде пока ничего нет.",
4216
+ "d148218513d9950a": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.",
4217
"1410155e503a917f": "{denial} Чтобы продолжить, переключите режим этого треда.",
4218
"81ceeceeb521bba6": "Переключиться на {mode}",
4219
"6ebd73c7bfb58bb7": "Приложение",
apps/mobile/src/i18n/translations/sv.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "T3 Code på {host} var för upptagen för att svara.",
458
"5c5941732d5dfac6": "Uppgifterna för parkopplingen är ogiltiga.",
459
"b8ca23ad7dda376e": "Den adressen leder till {host}, en annan dator. Lägg till den som en egen miljö i stället.",
460
+ "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
461
"693cb5c4fb40f109": "Bara sparade bearer-miljöer kan redigeras.",
462
"5f5844b910cb1544": "Den sparade bearer-uppgiften är inte tillgänglig.",
463
"51b0133f1ed3cf5c": "Miljöns etikett får inte vara tom.",
463
- "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
464
"3aa15bfbe1920376": "Uppdatera T3 Code på {host} manuellt; det kan inte uppdatera sig självt.",
465
"71907f57b7ec64d5": "{host} kom inte tillbaka med en kompatibel version av T3 Code.",
466
"e77ac580a4ddcd3b": "Tillgänglig",
@@ -1969,11 +1969,13 @@
1969
"28ae2c5e144a8c02": "Öppna Inställningar",
1970
"41e3df8a7b6d5d9d": "Ogiltig QR-kod",
1971
"c28525066e29c024": "Den skannade QR-koden kändes inte igen.",
1972
+ "8a333daf9b7fd03f": "Anslut till {environment}",
1973
"53c162d8868a1d0e": "Lägg till miljö",
1974
"403dd9b445331000": "Ansluter",
1975
"44bbcfd33b751bd6": "Adress",
1976
"42fd195574793f9e": "Kod",
1977
"51b31345c7bed6f0": "Parkopplingskod",
1978
+ "e1cb1c8599e84e26": "Skapa en parkopplingskod på {environment}, i dess Inställningar → Delning och åtkomst eller med `t3 auth pairing create`, och ange den här.",
1979
"7d6f419f8ab7f779": "För datorer i ditt lokala nätverk eller tailnet. Datorn behåller sina egna leverantörsuppgifter.",
1980
"36f32bd159bdc0d1": "Skanna QR-kod",
1981
"11fd02455d938901": "Skanna koden från {command} eller inställningen Anslutningar på skrivbordet",
@@ -4159,8 +4161,11 @@
4161
"009e2ca841fdc1ef": "den här miljön",
4162
"596842e9e887232b": "Läser från {label}…",
4163
"ff889c17671b40af": "Läs in tidigare",
4164
+ "d49e5c66faa5d153": "Anslut för att interagera",
4165
+ "93e690821c726e13": "{label} kan inte nås från den här enheten",
4166
"0014ce0aaf1bd68a": "Skrivskyddad",
4167
"048b8a737af895ac": "Inget i den här tråden ännu.",
4168
+ "d148218513d9950a": "Anslut till ett nätverk som den finns på, till exempel dess Tailscale-nätverk, och försök igen. Du kan fortsätta läsa här.",
4169
"1410155e503a917f": "{denial} Byt trådens läge för att fortsätta.",
4170
"81ceeceeb521bba6": "Byt till {mode}",
4171
"6ebd73c7bfb58bb7": "App",
apps/mobile/src/i18n/translations/zh.json
+6
-1
@@ -457,10 +457,10 @@
457
"93e37fedae7eaa5b": "{host} 上的 T3 Code 太忙,未能响应。",
458
"5c5941732d5dfac6": "配对信息无效。",
459
"b8ca23ad7dda376e": "该地址指向另一台机器 {host}。请将其添加为独立环境。",
460
+ "0c0150a90b582a7a": "环境 URL 无效。",
461
"693cb5c4fb40f109": "只能编辑已保存的 bearer 环境。",
462
"5f5844b910cb1544": "已保存的 bearer 凭据不可用。",
463
"51b0133f1ed3cf5c": "环境名称不能为空。",
463
- "0c0150a90b582a7a": "环境 URL 无效。",
464
"3aa15bfbe1920376": "请手动更新 {host} 上的 T3 Code;它无法自行更新。",
465
"71907f57b7ec64d5": "{host} 重启后未运行兼容的 T3 Code 版本。",
466
"e77ac580a4ddcd3b": "可用",
@@ -1971,11 +1971,13 @@
1971
"28ae2c5e144a8c02": "打开设置",
1972
"41e3df8a7b6d5d9d": "二维码无效",
1973
"c28525066e29c024": "无法识别扫描的二维码。",
1974
+ "8a333daf9b7fd03f": "连接到 {environment}",
1975
"53c162d8868a1d0e": "添加环境",
1976
"403dd9b445331000": "正在连接",
1977
"44bbcfd33b751bd6": "地址",
1978
"42fd195574793f9e": "配对码",
1979
"51b31345c7bed6f0": "配对码",
1980
+ "e1cb1c8599e84e26": "在 {environment} 的设置 → 共享与访问中或使用 `t3 auth pairing create` 创建配对码,然后在此输入。",
1981
"7d6f419f8ab7f779": "适用于本地网络或 tailnet 中的机器。该机器保留自己的提供方凭据。",
1982
"36f32bd159bdc0d1": "扫描二维码",
1983
"11fd02455d938901": "扫描 {command} 或桌面端“连接”设置中的二维码",
@@ -4156,8 +4158,11 @@
4158
"009e2ca841fdc1ef": "此环境",
4159
"596842e9e887232b": "正在从 {label} 读取…",
4160
"ff889c17671b40af": "加载更早的内容",
4161
+ "d49e5c66faa5d153": "连接以进行交互",
4162
+ "93e690821c726e13": "无法从此设备访问 {label}",
4163
"0014ce0aaf1bd68a": "只读",
4164
"048b8a737af895ac": "此会话中还没有内容。",
4165
+ "d148218513d9950a": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。",
4166
"1410155e503a917f": "{denial} 切换此会话的模式以继续。",
4167
"81ceeceeb521bba6": "切换到 {mode}",
4168
"6ebd73c7bfb58bb7": "应用",
apps/mobile/src/state/linkedThread.ts
+67
-2
@@ -1,10 +1,18 @@
1
-import { useAtomValue } from "@effect/atom-react";
2
-import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread";
1
+import { useAtomSet, useAtomValue } from "@effect/atom-react";
2
+import {
3
+ connectLinkedEnvironment,
4
+ type LinkedThreadTarget,
5
+} from "@t3tools/client-runtime/linked-thread";
6
import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts";
7
+import { useState } from "react";
8
9
+import { connectPairingUrl, reachesEnvironment } from "../connection/onboarding";
10
+import { linkedEnvironmentPrefillAtom } from "../features/connection/linkedEnvironmentPrefill";
11
+import { buildPairingUrl } from "../features/connection/pairing";
12
import { useEnvironments } from "./environments";
13
import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
14
import { useEnvironmentQuery } from "./query";
15
+import { useAtomCommand } from "./use-atom-command";
16
17
/**
18
* What places a delegated task's thread: this app's own connections, and the links `environmentId`
@@ -32,6 +40,63 @@ export function useLinkedThreadReach(
40
return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) };
41
}
42
43
+export type LinkedEnvironmentConnectState =
44
+ | { readonly phase: "idle" | "connecting" }
45
+ | { readonly phase: "unreachable"; readonly label: string };
46
+
47
+/**
48
+ * Connects this app to the environment `target` lives in. One step when the linking environment
49
+ * can get a pairing for this app; otherwise the caller opens the add-environment screen, which
50
+ * reads what was learned about the machine.
51
+ */
52
+export function useConnectLinkedEnvironment(target: LinkedThreadTarget) {
53
+ const setPrefill = useAtomSet(linkedEnvironmentPrefillAtom);
54
+ const mayPair = useAtomValue(
55
+ peerLinkEnvironment.pairClient.permissionAtom(target.viaEnvironmentId),
56
+ );
57
+ const quiet = { reportFailure: false, reportDefect: false } as const;
58
+ const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
59
+ const reaches = useAtomCommand(reachesEnvironment, quiet);
60
+ const pair = useAtomCommand(connectPairingUrl, quiet);
61
+ const [state, setState] = useState<LinkedEnvironmentConnectState>({ phase: "idle" });
62
+ const connect = async () => {
63
+ setState({ phase: "connecting" });
64
+ const outcome = await connectLinkedEnvironment({
65
+ label: target.label,
66
+ requestPairing: async () => {
67
+ // Without it the linking environment refuses; the user can still pair by hand.
68
+ if (!mayPair) return null;
69
+ const result = await requestPairing({
70
+ environmentId: target.viaEnvironmentId,
71
+ input: { environmentId: target.environmentId },
72
+ });
73
+ return result._tag === "Success" ? result.value : null;
74
+ },
75
+ reaches: async (host) => {
76
+ const result = await reaches({ host, environmentId: target.environmentId });
77
+ return result._tag === "Success" && result.value;
78
+ },
79
+ pair: async ({ host, pairingCode }) => {
80
+ const result = await pair({
81
+ pairingUrl: buildPairingUrl(host, pairingCode),
82
+ expectedEnvironmentId: target.environmentId,
83
+ });
84
+ return result._tag === "Success";
85
+ },
86
+ });
87
+ setState(
88
+ outcome.type === "unreachable"
89
+ ? { phase: "unreachable", label: outcome.label }
90
+ : { phase: "idle" },
91
+ );
92
+ if (outcome.type === "manual") {
93
+ setPrefill({ environmentId: target.environmentId, label: outcome.label, host: outcome.host });
94
+ }
95
+ return outcome;
96
+ };
97
+ return { state, connect };
98
+}
99
+
100
/**
101
* The thread of `target`, streamed through the environment that links to it. The stream runs only
102
* while `active`; what it last showed stays, so coming back to the screen shows it at once.
apps/server/src/auth/RpcAuthorization.test.ts
+53
@@ -288,6 +288,59 @@ it.effect("reads a linked environment's thread only for a client that may read t
288
}).pipe(Effect.scoped),
289
);
290
291
+it.effect("pairs a client with a linked environment only for one that may hand out access", () =>
292
+ Effect.gen(function* () {
293
+ const group = WsRpcGroup.omit(
294
+ ...[...WsRpcGroup.requests.keys()].filter(
295
+ (
296
+ tag,
297
+ ): tag is Exclude<
298
+ keyof typeof RPC_REQUIRED_SCOPES,
299
+ typeof WS_METHODS.peerLinksPairClient
300
+ > => tag !== WS_METHODS.peerLinksPairClient,
301
+ ),
302
+ );
303
+ let asked = 0;
304
+ const environmentId = EnvironmentId.make("environment-box");
305
+ const handlers = group.toLayerHandler(WS_METHODS.peerLinksPairClient, () =>
306
+ Effect.sync(() => {
307
+ asked++;
308
+ return {
309
+ type: "unsupported" as const,
310
+ reason: "link_access" as const,
311
+ environmentId,
312
+ label: "Box",
313
+ urls: [],
314
+ };
315
+ }),
316
+ );
317
+ // Running agents and reading the access list do not include handing access out.
318
+ const operator = yield* RpcTest.makeClient(group).pipe(
319
+ Effect.provide(
320
+ Layer.merge(
321
+ handlers,
322
+ RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
323
+ ),
324
+ ),
325
+ );
326
+ expect(
327
+ yield* operator[WS_METHODS.peerLinksPairClient]({ environmentId }).pipe(Effect.flip),
328
+ ).toMatchObject({
329
+ _tag: "EnvironmentAuthorizationError",
330
+ requiredPermission: AuthAccessWriteScope,
331
+ });
332
+ expect(asked).toBe(0);
333
+
334
+ const manager = yield* RpcTest.makeClient(group).pipe(
335
+ Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthAccessWriteScope]))),
336
+ );
337
+ expect((yield* manager[WS_METHODS.peerLinksPairClient]({ environmentId })).type).toBe(
338
+ "unsupported",
339
+ );
340
+ expect(asked).toBe(1);
341
+ }).pipe(Effect.scoped),
342
+);
343
+
344
it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
345
"enforces read permission on stream %s",
346
(method) =>
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -298,6 +298,7 @@ export const make = Effect.gen(function* () {
298
mcpModeLimitHeader: true,
299
linkFence: true,
300
linkThreadStream: true,
301
+ linkClientPairing: true,
302
mcpApprovalCodes: true,
303
peerLinkPairingCodes: true,
304
mcpHostedApproval: true,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -73,6 +73,7 @@ const RPC_AGGREGATES = {
73
[WS_METHODS.peerLinksSubscribeThread]: "peerLinks",
74
[WS_METHODS.peerLinksThreadHistoryPage]: "peerLinks",
75
[WS_METHODS.peerLinksThreadItem]: "peerLinks",
76
+ [WS_METHODS.peerLinksPairClient]: "peerLinks",
77
[WS_METHODS.serverGetSettings]: "server",
78
[WS_METHODS.serverUpdateSettings]: "server",
79
[WS_METHODS.serverSearchAcpRegistry]: "server",
apps/server/src/peer/PeerClientPairing.test.ts
new
+275
@@ -0,0 +1,275 @@
1
+import { NodeHttpServer } from "@effect/platform-node";
2
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
+import {
4
+ AuthAccessWriteScope,
5
+ type AuthEnvironmentScope,
6
+ type AuthMcpClientAccess,
7
+ AuthOrchestrationOperateScope,
8
+ AuthOrchestrationReadScope,
9
+ AuthRelayConfigureScope,
10
+ AuthStandardClientScopes,
11
+ AuthTerminalOperateScope,
12
+ type ExecutionEnvironmentDescriptor,
13
+ ProviderInstanceId,
14
+ ThreadId,
15
+} from "@t3tools/contracts";
16
+import { expect, it } from "@effect/vitest";
17
+import * as Context from "effect/Context";
18
+import * as Effect from "effect/Effect";
19
+import * as Layer from "effect/Layer";
20
+import * as Ref from "effect/Ref";
21
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
22
+import * as HttpBody from "effect/http/HttpBody";
23
+import * as HttpClient from "effect/http/HttpClient";
24
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
25
+import * as TestClock from "effect/testing/TestClock";
26
+import { Toolkit } from "effect/ai";
27
+
28
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
29
+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30
+import * as McpHttpServer from "../mcp/McpHttpServer.ts";
31
+import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
32
+import * as McpToolAccess from "../mcp/McpToolAccess.ts";
33
+import * as ServerSettings from "../serverSettings.ts";
34
+import * as PeerClientPairing from "./PeerClientPairing.ts";
35
+import * as PeerLinks from "./PeerLinks.ts";
36
+import {
37
+ descriptorOf,
38
+ layerEnvironmentAuth,
39
+ layerLinkingEnvironment,
40
+ linkTo,
41
+ type ServedPeer,
42
+ servePeer,
43
+} from "./PeerLinks.testkit.ts";
44
+
45
+const laptop = descriptorOf("environment-laptop", "Laptop");
46
+const box = descriptorOf("environment-box", "Box", { linkClientPairing: true });
47
+const NoTools = Toolkit.make();
48
+
49
+const serveBox = (descriptor: ExecutionEnvironmentDescriptor = box) =>
50
+ servePeer(
51
+ descriptor,
52
+ McpHttpServer.toolkitRegistration(NoTools, McpToolAccess.toLayer(NoTools, {})),
53
+ );
54
+
55
+/** The laptop: its links, its own clients, and what answers a client asking to pair with a link. */
56
+const makeLaptop = Effect.gen(function* () {
57
+ const linking = yield* Layer.build(layerLinkingEnvironment(laptop));
58
+ const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-here-auth-"));
59
+ const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
60
+ const pairing = yield* PeerClientPairing.layer.pipe(
61
+ Layer.provide(Layer.succeedContext(linking)),
62
+ Layer.provide(Layer.succeed(EnvironmentAuth.EnvironmentAuth, auth)),
63
+ Layer.provide(FetchHttpClient.layer),
64
+ Layer.build,
65
+ );
66
+ return {
67
+ links: Context.get(linking, PeerLinks.PeerLinks),
68
+ settings: Context.get(linking, ServerSettings.ServerSettingsService),
69
+ pairing: Context.get(pairing, PeerClientPairing.PeerClientPairing),
70
+ /** A client paired with the laptop, such as a phone. */
71
+ client: (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
72
+ auth.issueSession({ scopes, label: "Phone" }),
73
+ };
74
+});
75
+
76
+const metadata = { deviceType: "mobile" as const };
77
+
78
+/** Asks the box's route directly, as anything holding `bearer` could, and answers its status. */
79
+const askBox = (b: ServedPeer, bearer: string | undefined, headers: Record<string, string> = {}) =>
80
+ HttpClient.execute(
81
+ HttpClientRequest.post(`${b.url}/api/peer-link/client-pairing`).pipe(
82
+ HttpClientRequest.setHeaders({
83
+ ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }),
84
+ ...headers,
85
+ }),
86
+ HttpClientRequest.setBody(
87
+ HttpBody.text(
88
+ JSON.stringify({ scopes: AuthStandardClientScopes, clientLabel: "Phone" }),
89
+ "application/json",
90
+ ),
91
+ ),
92
+ ),
93
+ ).pipe(
94
+ Effect.map((response) => response.status),
95
+ Effect.provide(FetchHttpClient.layer),
96
+ );
97
+
98
+const linkTokenOf = (a: Effect.Success<typeof makeLaptop>) =>
99
+ a.links.resolve(box.environmentId).pipe(Effect.map((resolved) => resolved.token));
100
+
101
+it.effect(
102
+ "a full-access link gets a client one pairing, with no more than the client holds here",
103
+ () =>
104
+ Effect.scoped(
105
+ Effect.gen(function* () {
106
+ const b = yield* serveBox();
107
+ const a = yield* makeLaptop;
108
+ yield* linkTo(a.links, b, "full-access");
109
+ // Holds less than a pairing code grants, and one scope no pairing code grants.
110
+ const held = [
111
+ AuthOrchestrationReadScope,
112
+ AuthOrchestrationOperateScope,
113
+ AuthAccessWriteScope,
114
+ AuthRelayConfigureScope,
115
+ ];
116
+ const phone = yield* a.client(held);
117
+
118
+ const result = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
119
+ if (result.type !== "credential") return yield* Effect.die(result);
120
+ expect(result).toMatchObject({
121
+ environmentId: box.environmentId,
122
+ label: "Box",
123
+ urls: [b.url],
124
+ });
125
+ // The box's Connections says where the pairing came from, and can revoke it.
126
+ expect(yield* b.auth.listPairingLinks()).toMatchObject([{ label: "Phone · via Laptop" }]);
127
+
128
+ const session = yield* b.auth.exchangeBootstrapCredentialForAccessToken(
129
+ result.credential,
130
+ undefined,
131
+ metadata,
132
+ );
133
+ expect(new Set(session.scope.split(" "))).toEqual(
134
+ new Set([
135
+ AuthOrchestrationReadScope,
136
+ AuthOrchestrationOperateScope,
137
+ AuthAccessWriteScope,
138
+ ]),
139
+ );
140
+ expect(session.scope).not.toContain(AuthTerminalOperateScope);
141
+ const again = yield* b.auth
142
+ .exchangeBootstrapCredentialForAccessToken(result.credential, undefined, metadata)
143
+ .pipe(Effect.flip);
144
+ expect(again._tag).toBe("ServerAuthInvalidCredentialError");
145
+
146
+ // One the client never redeems is gone within minutes.
147
+ const unused = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
148
+ if (unused.type !== "credential") return yield* Effect.die(unused);
149
+ yield* TestClock.adjust("3 minutes");
150
+ const late = yield* b.auth
151
+ .exchangeBootstrapCredentialForAccessToken(unused.credential, undefined, metadata)
152
+ .pipe(Effect.flip);
153
+ expect(late._tag).toBe("ServerAuthInvalidCredentialError");
154
+ }),
155
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
156
+);
157
+
158
+it.effect.each(["read-only", "approval-required", "auto"] as const)(
159
+ "a %s link cannot pair a client, even when the linking environment is bypassed",
160
+ (access: AuthMcpClientAccess) =>
161
+ Effect.scoped(
162
+ Effect.gen(function* () {
163
+ const b = yield* serveBox();
164
+ const a = yield* makeLaptop;
165
+ yield* linkTo(a.links, b, access);
166
+ const phone = yield* a.client(AuthStandardClientScopes);
167
+
168
+ expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
169
+ type: "unsupported",
170
+ reason: "link_access",
171
+ environmentId: box.environmentId,
172
+ label: "Box",
173
+ urls: [b.url],
174
+ });
175
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
176
+
177
+ expect(yield* askBox(b, yield* linkTokenOf(a))).toBe(403);
178
+ expect(yield* b.auth.listPairingLinks()).toEqual([]);
179
+ }),
180
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
181
+);
182
+
183
+it.effect("only a full-access link's own session reaches the box's pairing route", () =>
184
+ Effect.scoped(
185
+ Effect.gen(function* () {
186
+ const b = yield* serveBox();
187
+ const a = yield* makeLaptop;
188
+ yield* linkTo(a.links, b, "full-access");
189
+ const linkToken = yield* linkTokenOf(a);
190
+
191
+ // An outside agent approved at full access is not a link.
192
+ const agent = yield* b.auth.issueMcpClientSession({
193
+ label: "Outside agent",
194
+ access: "full-access",
195
+ peerLink: false,
196
+ client: { deviceType: "bot" },
197
+ });
198
+ expect(yield* askBox(b, agent.token)).toBe(403);
199
+
200
+ // An agent's thread credential, which a link-started agent holds too, is not a session.
201
+ const registry = yield* McpSessionRegistry.layer.pipe(
202
+ Layer.provide(
203
+ Layer.succeed(ServerEnvironment.ServerEnvironment, {
204
+ getEnvironmentId: Effect.succeed(box.environmentId),
205
+ getDescriptor: Effect.succeed(box),
206
+ }),
207
+ ),
208
+ Layer.provide(NodeCrypto.layer),
209
+ Layer.build,
210
+ );
211
+ const thread = yield* Context.get(registry, McpSessionRegistry.McpSessionRegistry).issue({
212
+ threadId: ThreadId.make("thread:box-link-started"),
213
+ providerInstanceId: ProviderInstanceId.make("codex"),
214
+ });
215
+ expect(yield* askBox(b, thread.config.authorizationHeader.slice("Bearer ".length))).toBe(401);
216
+
217
+ // The box's own administrator client pairs devices from Connections, not from here.
218
+ const owner = yield* b.auth.issueSession({ scopes: AuthStandardClientScopes });
219
+ expect(yield* askBox(b, owner.token)).toBe(401);
220
+ expect(yield* askBox(b, undefined)).toBe(401);
221
+ // A page in a browser never holds a link's token.
222
+ expect(yield* askBox(b, linkToken, { origin: "https://example.com" })).toBe(403);
223
+ expect(yield* b.auth.listPairingLinks()).toEqual([]);
224
+
225
+ expect(yield* askBox(b, linkToken)).toBe(200);
226
+ }),
227
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
228
+);
229
+
230
+it.effect("pairs no client while Linked environments is off on either side", () =>
231
+ Effect.scoped(
232
+ Effect.gen(function* () {
233
+ const b = yield* serveBox();
234
+ const a = yield* makeLaptop;
235
+ yield* linkTo(a.links, b, "full-access");
236
+ const phone = yield* a.client(AuthStandardClientScopes);
237
+ const linkToken = yield* linkTokenOf(a);
238
+
239
+ yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
240
+ expect(yield* askBox(b, linkToken)).toBe(403);
241
+ expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toMatchObject({
242
+ type: "unsupported",
243
+ reason: "refused",
244
+ });
245
+ yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
246
+
247
+ yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
248
+ const off = yield* a.pairing
249
+ .request({ environmentId: box.environmentId }, phone)
250
+ .pipe(Effect.flip);
251
+ expect(off.reason).toBe("disabled");
252
+ expect(yield* b.auth.listPairingLinks()).toEqual([]);
253
+ }),
254
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
255
+);
256
+
257
+it.effect("a linked environment from before client pairing is never asked", () =>
258
+ Effect.scoped(
259
+ Effect.gen(function* () {
260
+ const b = yield* serveBox(descriptorOf("environment-box", "Box"));
261
+ const a = yield* makeLaptop;
262
+ yield* linkTo(a.links, b, "full-access");
263
+ const phone = yield* a.client(AuthStandardClientScopes);
264
+
265
+ expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
266
+ type: "unsupported",
267
+ reason: "version",
268
+ environmentId: box.environmentId,
269
+ label: "Box",
270
+ urls: [b.url],
271
+ });
272
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
273
+ }),
274
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
275
+);
apps/server/src/peer/PeerClientPairing.ts
new
+231
@@ -0,0 +1,231 @@
1
+import {
2
+ type AuthEnvironmentScope,
3
+ type AuthSessionId,
4
+ AuthStandardClientScopes,
5
+ EnvironmentHttpApi,
6
+ type PeerLinkClientPairingCredential,
7
+ type PeerLinkClientPairingInput,
8
+ type PeerLinkClientPairingRequest,
9
+ type PeerLinkClientPairingResult,
10
+ PeerLinkError,
11
+} from "@t3tools/contracts";
12
+import * as Context from "effect/Context";
13
+import * as DateTime from "effect/DateTime";
14
+import * as Duration from "effect/Duration";
15
+import * as Effect from "effect/Effect";
16
+import * as Layer from "effect/Layer";
17
+import * as Option from "effect/Option";
18
+import * as Schema from "effect/Schema";
19
+import * as HttpClient from "effect/http/HttpClient";
20
+import * as HttpApi from "effect/http-api/HttpApi";
21
+import * as HttpApiClient from "effect/http-api/HttpApiClient";
22
+
23
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
24
+import * as ServerSettings from "../serverSettings.ts";
25
+import * as PeerLinks from "./PeerLinks.ts";
26
+
27
+/** Long enough for the client to reach the linked environment and redeem it, and no longer. */
28
+const CLIENT_PAIRING_TTL = Duration.minutes(3);
29
+const CLIENT_LABEL_MAX_LENGTH = 80;
30
+
31
+const ClientPairingApi = HttpApi.make(EnvironmentHttpApi.identifier)
32
+ .add(EnvironmentHttpApi.groups.peerLink)
33
+ .annotateMerge(EnvironmentHttpApi.annotations);
34
+
35
+/** Why the linked environment will not mint a client pairing for this caller. */
36
+export class PeerClientPairingRefused extends Schema.TaggedError<PeerClientPairingRefused>()(
37
+ "PeerClientPairingRefused",
38
+ {
39
+ reason: Schema.Literals(["disabled", "not_a_full_access_link", "no_scopes", "policy"]),
40
+ message: Schema.String,
41
+ },
42
+) {}
43
+
44
+/**
45
+ * The linked side: mints a one-time pairing credential for a client of the environment that
46
+ * links here, when that environment asks over its link.
47
+ */
48
+export class PeerClientPairingIssuer extends Context.Service<
49
+ PeerClientPairingIssuer,
50
+ {
51
+ readonly issue: (
52
+ caller: EnvironmentAuth.McpClientSession,
53
+ request: PeerLinkClientPairingRequest,
54
+ ) => Effect.Effect<
55
+ PeerLinkClientPairingCredential,
56
+ PeerClientPairingRefused | EnvironmentAuth.ServerAuthInternalError
57
+ >;
58
+ }
59
+>()("t3/peer/PeerClientPairing/PeerClientPairingIssuer") {}
60
+
61
+/**
62
+ * The linking side: gets a client of this environment a pairing credential for an environment
63
+ * this one links to, so the client can connect there itself.
64
+ */
65
+export class PeerClientPairing extends Context.Service<
66
+ PeerClientPairing,
67
+ {
68
+ readonly request: (
69
+ input: PeerLinkClientPairingInput,
70
+ client: {
71
+ readonly sessionId: AuthSessionId;
72
+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
73
+ },
74
+ ) => Effect.Effect<PeerLinkClientPairingResult, PeerLinkError>;
75
+ }
76
+>()("t3/peer/PeerClientPairing") {}
77
+
78
+const makeIssuer = Effect.gen(function* () {
79
+ const auth = yield* EnvironmentAuth.EnvironmentAuth;
80
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
81
+ const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
82
+ const enabled = serverSettings.getSettings.pipe(
83
+ Effect.map((settings) => settings.linkedEnvironmentsEnabled),
84
+ Effect.orElseSucceed(() => false),
85
+ );
86
+
87
+ const issue: PeerClientPairingIssuer["Service"]["issue"] = Effect.fn(
88
+ "PeerClientPairingIssuer.issue",
89
+ )(function* (caller, request) {
90
+ if (!(yield* enabled)) {
91
+ return yield* new PeerClientPairingRefused({
92
+ reason: "disabled",
93
+ message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
94
+ });
95
+ }
96
+ // A full-access link's agents already run as this machine's user and could run
97
+ // `t3 auth pairing create` themselves, so minting here adds no power. Any lower link would
98
+ // gain more than it holds, and so would one an administrator's ceiling holds below full access.
99
+ if (
100
+ !caller.peerLink ||
101
+ caller.access !== "full-access" ||
102
+ (maxRuntimeMode !== undefined && maxRuntimeMode !== "full-access")
103
+ ) {
104
+ return yield* new PeerClientPairingRefused({
105
+ reason: "not_a_full_access_link",
106
+ message: "Only a full-access link may pair a client here.",
107
+ });
108
+ }
109
+ // Never more than the client holds where it asked, nor more than a pairing code grants.
110
+ const scopes = AuthStandardClientScopes.filter((scope) => request.scopes.includes(scope));
111
+ if (scopes.length === 0) {
112
+ return yield* new PeerClientPairingRefused({
113
+ reason: "no_scopes",
114
+ message: "The client holds no access a pairing could carry.",
115
+ });
116
+ }
117
+ const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX)
118
+ ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length)
119
+ : caller.label;
120
+ const clientLabel = Array.from(request.clientLabel).slice(0, CLIENT_LABEL_MAX_LENGTH).join("");
121
+ const issued = yield* auth
122
+ .createPairingLink({
123
+ scopes,
124
+ ttl: CLIENT_PAIRING_TTL,
125
+ label: `${clientLabel} · via ${via}`,
126
+ })
127
+ .pipe(
128
+ Effect.catchTags({
129
+ ManagedPolicyRefusedError: (error) =>
130
+ Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message })),
131
+ }),
132
+ );
133
+ return { credential: issued.credential, expiresAt: issued.expiresAt };
134
+ });
135
+
136
+ return PeerClientPairingIssuer.of({ issue });
137
+});
138
+
139
+export const layerIssuer = Layer.effect(PeerClientPairingIssuer, makeIssuer);
140
+
141
+const make = Effect.gen(function* () {
142
+ const links = yield* PeerLinks.PeerLinks;
143
+ const auth = yield* EnvironmentAuth.EnvironmentAuth;
144
+ const httpClient = yield* HttpClient.HttpClient;
145
+
146
+ /** What this environment's Connections calls the client that asked. */
147
+ const clientLabelOf = (sessionId: AuthSessionId) =>
148
+ auth.listClientSessions(sessionId).pipe(
149
+ Effect.map((sessions) => {
150
+ const client = sessions.find((session) => session.sessionId === sessionId)?.client;
151
+ return (
152
+ client?.label ??
153
+ ([client?.browser, client?.os].filter((part) => part !== undefined).join(" on ") ||
154
+ "T3 Code client")
155
+ );
156
+ }),
157
+ Effect.orElseSucceed(() => "T3 Code client"),
158
+ );
159
+
160
+ const request: PeerClientPairing["Service"]["request"] = Effect.fn("PeerClientPairing.request")(
161
+ function* (input, client) {
162
+ if (!(yield* links.enabled)) {
163
+ return yield* new PeerLinkError({
164
+ reason: "disabled",
165
+ message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
166
+ });
167
+ }
168
+ const stored = yield* links.get(input.environmentId);
169
+ if (Option.isNone(stored)) {
170
+ return yield* new PeerLinkError({
171
+ reason: "unknown_link",
172
+ message: "This environment is no longer linked to that one.",
173
+ });
174
+ }
175
+ const { environmentId, label, urls, access, expiresAt } = stored.value;
176
+ if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) {
177
+ return yield* new PeerLinkError({
178
+ reason: "expired",
179
+ message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`,
180
+ });
181
+ }
182
+ const unsupported = (
183
+ reason: Extract<PeerLinkClientPairingResult, { type: "unsupported" }>["reason"],
184
+ name = label,
185
+ ): PeerLinkClientPairingResult => ({
186
+ type: "unsupported",
187
+ environmentId,
188
+ label: name,
189
+ urls,
190
+ reason,
191
+ });
192
+ // The linked environment refuses this too; asking would only spend a round trip.
193
+ if (access !== "full-access") return unsupported("link_access");
194
+ const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option);
195
+ if (Option.isNone(resolved)) return unsupported("unreachable");
196
+ const peer = resolved.value;
197
+ if (peer.capabilities.linkClientPairing !== true) {
198
+ return unsupported("version", peer.link.label);
199
+ }
200
+ const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe(
201
+ Effect.provideService(HttpClient.HttpClient, httpClient),
202
+ );
203
+ return yield* api.peerLink
204
+ .clientPairing({
205
+ headers: { authorization: `Bearer ${peer.token}` },
206
+ payload: { scopes: client.scopes, clientLabel: yield* clientLabelOf(client.sessionId) },
207
+ })
208
+ .pipe(
209
+ Effect.timeout(PeerLinks.probeTimeout(peer.url)),
210
+ Effect.map((issued): PeerLinkClientPairingResult => ({
211
+ type: "credential",
212
+ environmentId,
213
+ label: peer.link.label,
214
+ urls,
215
+ credential: issued.credential,
216
+ expiresAt: issued.expiresAt,
217
+ })),
218
+ // No cause is logged or returned: a response this version cannot read may hold the credential.
219
+ Effect.catchTags({
220
+ HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
221
+ TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
222
+ }),
223
+ Effect.orElseSucceed(() => unsupported("refused", peer.link.label)),
224
+ );
225
+ },
226
+ );
227
+
228
+ return PeerClientPairing.of({ request });
229
+});
230
+
231
+export const layer = Layer.effect(PeerClientPairing, make);
apps/server/src/peer/PeerLinks.testkit.ts
+19
-12
@@ -32,6 +32,8 @@ import * as ServerHttp from "../http.ts";
32
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
33
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
34
import * as Sqlite from "../persistence/Sqlite.ts";
35
+import * as PeerHttp from "./http.ts";
36
+import * as PeerClientPairing from "./PeerClientPairing.ts";
37
import * as PeerLinks from "./PeerLinks.ts";
38
import * as ServerSettings from "../serverSettings.ts";
39
import * as PeerMcpClient from "./PeerMcpClient.ts";
@@ -39,7 +41,8 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
41
42
class PeerTestApi extends HttpApi.make("environment")
43
.add(EnvironmentHttpApi.groups.metadata)
42
- .add(EnvironmentHttpApi.groups.mcpOAuth) {}
44
+ .add(EnvironmentHttpApi.groups.mcpOAuth)
45
+ .add(EnvironmentHttpApi.groups.peerLink) {}
46
47
export const descriptorOf = (
48
environmentId: string,
@@ -58,6 +61,19 @@ export const descriptorOf = (
61
},
62
});
63
64
+/** An environment's own sessions and pairing links, on a database and secret store of its own. */
65
+export const layerEnvironmentAuth = (prefix: string) =>
66
+ EnvironmentAuth.layer.pipe(
67
+ Layer.provide(ManagedPolicy.layerTest()),
68
+ Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
69
+ Layer.provide(Sqlite.layerMemory),
70
+ Layer.provideMerge(ServerSecretStore.layer),
71
+ Layer.provideMerge(ServerEnvironment.layerIdentity),
72
+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix })),
73
+ Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
74
+ Layer.fresh,
75
+ );
76
+
77
/**
78
* The environment a link points at, as it runs: its descriptor, MCP OAuth,
79
* and `/mcp` with `tools` behind the real client authenticator, on a real
@@ -81,17 +97,7 @@ export const servePeer = <E, R, E2 = never, R2 = never>(
97
getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
98
getDescriptor: Ref.get(descriptor),
99
});
84
- const authContext = yield* EnvironmentAuth.layer.pipe(
85
- Layer.provide(ManagedPolicy.layerTest()),
86
- Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
87
- Layer.provide(Sqlite.layerMemory),
88
- Layer.provideMerge(ServerSecretStore.layer),
89
- Layer.provideMerge(ServerEnvironment.layerIdentity),
90
- Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
91
- Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
92
- Layer.fresh,
93
- Layer.build,
94
- );
100
+ const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-peer-"));
101
const layerRecordBearers = HttpRouter.middleware(
102
(httpEffect) =>
103
Effect.gen(function* () {
@@ -131,6 +137,7 @@ export const servePeer = <E, R, E2 = never, R2 = never>(
137
),
138
),
139
),
140
+ Layer.provide(PeerHttp.layer.pipe(Layer.provide(PeerClientPairing.layerIssuer))),
141
Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
142
Layer.provide(AuthHttp.layerAuthenticatedAuth),
143
),
apps/server/src/peer/PeerLinks.ts
+4
-1
@@ -84,6 +84,9 @@ export interface ResolvedPeerLink {
84
readonly capabilities: ExecutionEnvironmentCapabilities;
85
}
86
87
+/** What a link's session is called in the peer's Connections, before this environment's label. */
88
+export const LINK_CLIENT_NAME_PREFIX = "T3 Code · ";
89
+
90
export const LINKED_ENVIRONMENTS_OFF =
91
"Linked environments is off on this machine. Turn it on in Settings → Labs.";
92
@@ -552,7 +555,7 @@ const make = Effect.gen(function* () {
555
message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
556
});
557
}
555
- const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);
558
+ const issued = yield* signIn(primary, input, `${LINK_CLIENT_NAME_PREFIX}${self.label}`);
559
const now = yield* DateTime.now;
560
const linked: PeerLink = {
561
environmentId: peer.environmentId,
apps/server/src/peer/http.ts
new
+76
@@ -0,0 +1,76 @@
1
+import {
2
+ EnvironmentHttpApi,
3
+ EnvironmentHttpForbiddenError,
4
+ EnvironmentHttpInternalServerError,
5
+ EnvironmentHttpUnauthorizedError,
6
+} from "@t3tools/contracts";
7
+import * as Effect from "effect/Effect";
8
+import { HttpServerRequest, HttpServerResponse } from "effect/http";
9
+import * as HttpEffect from "effect/http/HttpEffect";
10
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
11
+
12
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13
+import * as PeerClientPairing from "./PeerClientPairing.ts";
14
+
15
+// The response is a credential.
16
+const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
17
+ Effect.succeed(
18
+ HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),
19
+ ),
20
+);
21
+
22
+/**
23
+ * A link session is accepted on `/mcp` and here, nowhere else. This is a route and not an MCP
24
+ * tool so that no agent's tool list can hold it: thread credentials never authenticate here.
25
+ */
26
+export const layer = HttpApiBuilder.group(
27
+ EnvironmentHttpApi,
28
+ "peerLink",
29
+ Effect.fnUntraced(function* (handlers) {
30
+ const auth = yield* EnvironmentAuth.EnvironmentAuth;
31
+ const issuer = yield* PeerClientPairing.PeerClientPairingIssuer;
32
+ return handlers.handle(
33
+ "clientPairing",
34
+ Effect.fn("environment.peerLink.clientPairing")(function* (args) {
35
+ const request = yield* HttpServerRequest.HttpServerRequest;
36
+ yield* noStore;
37
+ // A browser never holds a link's token; refuse one before reading credentials, as `/mcp` does.
38
+ if (request.headers.origin !== undefined) {
39
+ return yield* new EnvironmentHttpForbiddenError({
40
+ message: "This route does not accept browser requests.",
41
+ });
42
+ }
43
+ const caller = yield* auth.authenticateMcpClient(request).pipe(
44
+ Effect.mapError((error) =>
45
+ EnvironmentAuth.isServerAuthCredentialError(error)
46
+ ? new EnvironmentHttpUnauthorizedError({
47
+ message: "Only a linked environment's session is accepted here.",
48
+ })
49
+ : new EnvironmentHttpInternalServerError({
50
+ message: "The session could not be checked.",
51
+ }),
52
+ ),
53
+ );
54
+ return yield* issuer.issue(caller, args.payload).pipe(
55
+ Effect.catchTags({
56
+ PeerClientPairingRefused: (error) =>
57
+ Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
58
+ }),
59
+ Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
60
+ Effect.logError("Could not mint a client pairing for a linked environment.", {
61
+ cause,
62
+ }).pipe(
63
+ Effect.andThen(
64
+ Effect.fail(
65
+ new EnvironmentHttpInternalServerError({
66
+ message: "The pairing could not be created.",
67
+ }),
68
+ ),
69
+ ),
70
+ ),
71
+ ),
72
+ );
73
+ }),
74
+ );
75
+ }),
76
+);
apps/server/src/server.ts
+4
-1
@@ -92,6 +92,8 @@ import * as TerminalManager from "./terminal/Manager.ts";
92
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
93
import * as PeerForwarding from "./peer/PeerForwarding.ts";
94
import * as RemoteDelegation from "./peer/RemoteDelegation.ts";
95
+import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
96
+import * as PeerClientPairingHttp from "./peer/http.ts";
97
import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
98
import * as PeerLinks from "./peer/PeerLinks.ts";
99
import * as PeerMcpClient from "./peer/PeerMcpClient.ts";
@@ -850,6 +852,7 @@ const layerMakeRoutes = Layer.mergeAll(
852
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
853
Layer.provide(AuthHttp.layer),
854
Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
855
+ Layer.provide(PeerClientPairingHttp.layer.pipe(Layer.provide(PeerClientPairing.layerIssuer))),
856
Layer.provide(CloudHttp.layer),
857
Layer.provide(OrchestrationHttp.layer),
858
Layer.provide(PullRequestHttp.layer),
@@ -901,7 +904,7 @@ const layerMakeRoutes = Layer.mergeAll(
904
Layer.provide(PreviewBrowser.layer),
905
// Links to other environments, shared by clients (WebSocket) and agents (/mcp).
906
Layer.provide(
904
- Layer.merge(PeerForwarding.layer, PeerThreadRelay.layer).pipe(
907
+ Layer.mergeAll(PeerForwarding.layer, PeerThreadRelay.layer, PeerClientPairing.layer).pipe(
908
Layer.provideMerge(PeerMcpClient.layer),
909
Layer.provideMerge(PeerLinks.layer),
910
),
apps/server/src/ws.test.ts
+2
@@ -102,6 +102,7 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
102
import * as RpcAuthorization from "./auth/RpcAuthorization.ts";
103
import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
104
import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts";
105
+import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
106
import * as PeerLinks from "./peer/PeerLinks.ts";
107
import * as PortScanner from "./preview/PortScanner.ts";
108
import * as PreviewManager from "./preview/Manager.ts";
@@ -850,6 +851,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
851
Layer.mock(PeerLinks.PeerLinks)({}),
852
Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
853
Layer.mock(PeerThreadRelay.PeerThreadRelay)({}),
854
+ Layer.mock(PeerClientPairing.PeerClientPairing)({}),
855
Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }),
856
Layer.mock(PreviewManager.PreviewManager)({}),
857
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
apps/server/src/ws.ts
+6
@@ -6,6 +6,7 @@ import * as Context from "effect/Context";
6
import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest";
7
import * as SecureRandom from "effect/crypto/SecureRandom";
8
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
9
+import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
10
import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
11
import * as PeerLinks from "./peer/PeerLinks.ts";
12
import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts";
@@ -1562,6 +1563,7 @@ export const layerWsRpc = (
1563
const peerLinks = yield* PeerLinks.PeerLinks;
1564
const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
1565
const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay;
1566
+ const peerClientPairing = yield* PeerClientPairing.PeerClientPairing;
1567
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
1568
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
1569
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -2720,6 +2722,8 @@ export const layerWsRpc = (
2722
Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
2723
Effect.andThen(peerThreadRelay.item(input)),
2724
),
2725
+ [WS_METHODS.peerLinksPairClient]: (input) =>
2726
+ peerClientPairing.request(input, currentSession),
2727
[WS_METHODS.peerLinksAnswerRequest]: (input) =>
2728
Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
2729
Effect.andThen(peerLinkRequests.answer(input)),
@@ -3632,6 +3636,7 @@ export const layer = Layer.unwrap(
3636
const peerLinks = yield* PeerLinks.PeerLinks;
3637
const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
3638
const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay;
3639
+ const peerClientPairing = yield* PeerClientPairing.PeerClientPairing;
3640
const sql = yield* SqlClient.SqlClient;
3641
return HttpRouter.add(
3642
"GET",
@@ -3733,6 +3738,7 @@ export const layer = Layer.unwrap(
3738
Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)),
3739
Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)),
3740
Layer.provide(Layer.succeed(PeerThreadRelay.PeerThreadRelay, peerThreadRelay)),
3741
+ Layer.provide(Layer.succeed(PeerClientPairing.PeerClientPairing, peerClientPairing)),
3742
Layer.provide(
3743
SourceControlDiscovery.layer.pipe(
3744
Layer.provide(
apps/web/src/components/chat/LinkedThreadPane.tsx
+78
-4
@@ -1,13 +1,17 @@
1
import { isLinkedThreadWorking, linkedThreadFailure } from "@t3tools/client-runtime/linked-thread";
2
import type { ScopedThreadRef } from "@t3tools/contracts";
3
import { T, useGT, useMessages, Var } from "gt-react";
4
-import { EyeIcon } from "lucide-react";
4
+import { EyeIcon, PlugIcon } from "lucide-react";
5
import { useState, type ReactNode } from "react";
6
7
import { useStableCallback } from "../../hooks/useStableCallback";
8
import { type LinkedThreadSurface, linkedThreadTitle } from "../../linkedThreadSurface";
9
import { useEnvironment } from "../../state/environments";
10
-import { linkedThreadItemSource, useLinkedThreadView } from "../../state/linkedThreadView";
10
+import {
11
+ linkedThreadItemSource,
12
+ useConnectLinkedEnvironment,
13
+ useLinkedThreadView,
14
+} from "../../state/linkedThreadView";
15
import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
16
import { Button } from "../ui/button";
17
import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
@@ -18,6 +22,7 @@ import {
22
ReadOnlyComposerStatus,
23
} from "./ReadOnlyComposerBar";
24
import { Spinner } from "../ui/spinner";
25
+import { toastManager } from "../ui/toast";
26
import type { MessagesTimelineHistoryControls } from "./MessagesTimeline";
27
import { ReadOnlyThreadTimeline } from "./ReadOnlyThreadTimeline";
28
@@ -86,6 +91,63 @@ export function LinkedThreadPane(props: {
91
const [turnItemSource] = useState(() => linkedThreadItemSource(surface));
92
const label = surface.label;
93
const projection = view?.thread.projection ?? null;
94
+ const connection = useConnectLinkedEnvironment(panelRef, surface);
95
+ const connectState = connection.state;
96
+ const connecting = connectState.phase === "connecting";
97
+ const connect = async () => {
98
+ const outcome = await connection.connect();
99
+ if (outcome.type === "connected") {
100
+ toastManager.add({
101
+ type: "success",
102
+ title: gt("Connected to {label}", { label }),
103
+ description: gt("This device is paired with it and can use its threads."),
104
+ });
105
+ }
106
+ };
107
+ const connectNotice: ComposerBannerStackItem | null =
108
+ connectState.phase === "connecting"
109
+ ? {
110
+ id: "connecting",
111
+ variant: "info",
112
+ icon: <Spinner size="sm" />,
113
+ title: gt("Connecting to {label}…", { label }),
114
+ }
115
+ : connectState.phase === "unreachable"
116
+ ? {
117
+ id: "unreachable",
118
+ variant: "warning",
119
+ icon: <PlugIcon />,
120
+ title: gt("{label} is not reachable from this device", { label: connectState.label }),
121
+ description: gt(
122
+ "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.",
123
+ ),
124
+ }
125
+ : connectState.phase === "manual"
126
+ ? {
127
+ id: "manual",
128
+ variant: "info",
129
+ icon: <PlugIcon />,
130
+ title: gt("{label} needs a pairing code", { label: connectState.prefill.label }),
131
+ description: gt("Create one on it, then add it to this device as an environment."),
132
+ actions: (
133
+ <Button
134
+ size="xs"
135
+ variant="ghost"
136
+ onClick={() => connection.addWithCode(connectState.prefill)}
137
+ >
138
+ <T>Enter code</T>
139
+ </Button>
140
+ ),
141
+ }
142
+ : null;
143
+ const connectAction = (
144
+ <Button size="sm" variant="outline" disabled={connecting} onClick={() => void connect()}>
145
+ <PlugIcon aria-hidden />
146
+ <span className="@max-[320px]/composer-surface:sr-only">
147
+ <T>Connect to interact</T>
148
+ </span>
149
+ </Button>
150
+ );
151
const failure = error === null ? null : linkedThreadFailure(error, { via, label }, m);
152
const retryAction = failure?.retryable ? (
153
<AlertAction>
@@ -136,7 +198,13 @@ export function LinkedThreadPane(props: {
198
</Alert>
199
)}
200
</div>
139
- <LinkedThreadComposer label={label} via={via} working={false} />
201
+ <LinkedThreadComposer
202
+ label={label}
203
+ via={via}
204
+ working={false}
205
+ notice={connectNotice}
206
+ action={connectAction}
207
+ />
208
</>
209
) : (
210
<ReadOnlyThreadTimeline
@@ -163,7 +231,13 @@ export function LinkedThreadPane(props: {
231
</Alert>
232
</div>
233
)}
166
- <LinkedThreadComposer label={label} via={via} working={working} />
234
+ <LinkedThreadComposer
235
+ label={label}
236
+ via={via}
237
+ working={working}
238
+ notice={connectNotice}
239
+ action={connectAction}
240
+ />
241
</>
242
)}
243
</ReadOnlyThreadTimeline>
apps/web/src/components/settings/AddEnvironmentDialog.tsx
+16
-4
@@ -53,6 +53,7 @@ import {
53
import { useEnvironmentQuery } from "~/state/query";
54
import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts";
55
import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
56
+import type { AddEnvironmentPrefill } from "~/state/linkedThreadView";
57
import { useAtomCommand } from "../../state/use-atom-command";
58
import { primaryServerKeybindingsAtom } from "~/state/server";
59
import {
@@ -77,6 +78,7 @@ const sshHostSuggestionValue = (target: DesktopDiscoveredSshHost) =>
78
79
export function AddEnvironmentDialog({
80
open,
81
+ prefill = null,
82
routeTarget,
83
error,
84
savedEnvironments,
@@ -84,6 +86,8 @@ export function AddEnvironmentDialog({
86
onErrorChange,
87
}: {
88
readonly open: boolean;
89
+ /** A machine the user chose elsewhere to pair with; they supply only the pairing code. */
90
+ readonly prefill?: AddEnvironmentPrefill | null;
91
readonly routeTarget: EnvironmentPresentation | null;
92
readonly error: string | null;
93
readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;
@@ -119,7 +123,7 @@ export function AddEnvironmentDialog({
123
return keys;
124
})();
125
const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote");
122
- const [savedBackendHost, setSavedBackendHost] = useState("");
126
+ const [savedBackendHost, setSavedBackendHost] = useState(prefill?.host ?? "");
127
const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
128
const [savedBackendSshHost, setSavedBackendSshHost] = useState("");
129
const [savedBackendSshUsername, setSavedBackendSshUsername] = useState("");
@@ -243,9 +247,10 @@ export function AddEnvironmentDialog({
247
return;
248
}
249
250
+ const expected = routeTarget ?? prefill;
251
const result = await connectPairing({
252
...remotePairingInput,
248
- ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
253
+ ...(expected ? { expectedEnvironmentId: expected.environmentId } : {}),
254
});
255
if (result._tag === "Failure") {
256
if (!isAtomCommandInterrupted(result)) {
@@ -683,14 +688,21 @@ export function AddEnvironmentDialog({
688
<DialogTitle>
689
{routeTarget
690
? gt("Add a route to {environment}", { environment: routeTarget.label })
686
- : gt("Add Environment")}
691
+ : prefill
692
+ ? gt("Connect to {environment}", { environment: prefill.label })
693
+ : gt("Add Environment")}
694
</DialogTitle>
695
<DialogDescription>
696
{routeTarget
697
? gt(
698
"Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine.",
699
)
693
- : gt("Pair another environment to this client.")}
700
+ : prefill
701
+ ? gt(
702
+ "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
703
+ { environment: prefill.label },
704
+ )
705
+ : gt("Pair another environment to this client.")}
706
</DialogDescription>
707
</DialogHeader>
708
<DialogPanel>
apps/web/src/components/settings/ConnectionsSettings.tsx
+8
-2
@@ -4,7 +4,7 @@ import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels
4
import { SessionPermissions } from "./SessionPermissions";
5
import { useSearch } from "@tanstack/react-router";
6
import { ChevronRightIcon, EllipsisIcon } from "lucide-react";
7
-import { useAtomValue } from "@effect/atom-react";
7
+import { useAtom, useAtomValue } from "@effect/atom-react";
8
import { type ReactNode, useState } from "react";
9
import { T, useGT, useMessages, Var } from "gt-react";
10
import {
@@ -50,6 +50,7 @@ import { ConnectDeviceApprovalSettings } from "./ConnectDeviceApprovalSettings";
50
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
51
import { FoldedSettingsSection } from "./FoldedSettingsSection";
52
import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";
53
+import { addEnvironmentPrefillAtom } from "~/state/linkedThreadView";
54
import { usePeerLinkHosts } from "~/state/peerLinks";
55
import { LoadBalancingSettings } from "./LoadBalancingSettings";
56
import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";
@@ -356,12 +357,15 @@ function ConnectionsSettingsContent({
357
const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
358
const [routeTarget, setRouteTarget] = useState<EnvironmentPresentation | null>(null);
359
const [savedBackendError, setSavedBackendError] = useState<string | null>(null);
360
+ // Set by a read-only linked thread whose machine this client is about to pair with.
361
+ const [addPrefill, setAddPrefill] = useAtom(addEnvironmentPrefillAtom);
362
const handleAddBackendDialogOpenChange = (open: boolean) => {
363
setAddBackendDialogOpen(open);
364
if (open) {
365
setRouteTarget(null);
366
} else {
367
setSavedBackendError(null);
368
+ setAddPrefill(null);
369
}
370
};
371
const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] =
@@ -1814,7 +1818,9 @@ function ConnectionsSettingsContent({
1818
<ServerUpdatesAction targets={savedServerUpdateTargets} variant="ghost-muted" />
1819
) : null}
1820
<AddEnvironmentDialog
1817
- open={addBackendDialogOpen}
1821
+ key={addPrefill?.environmentId ?? "any"}
1822
+ open={addBackendDialogOpen || addPrefill !== null}
1823
+ prefill={addPrefill}
1824
routeTarget={routeTarget}
1825
error={savedBackendError}
1826
savedEnvironments={savedEnvironments}
apps/web/src/connection/onboarding.ts
+9
-1
@@ -3,7 +3,7 @@ import {
3
createAtomCommandScheduler,
4
createRuntimeCommand,
5
} from "@t3tools/client-runtime/state/runtime";
6
-import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
6
+import type { DesktopSshEnvironmentTarget, EnvironmentId } from "@t3tools/contracts";
7
import * as Effect from "effect/Effect";
8
9
import { connectionAtomRuntime } from "./runtime";
@@ -35,3 +35,11 @@ export const connectSshEnvironment = createRuntimeCommand(connectionAtomRuntime,
35
Effect.flatMap((onboarding) => onboarding.registerSsh(input)),
36
),
37
});
38
+
39
+export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, {
40
+ label: "web:connection:reaches-environment",
41
+ execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) =>
42
+ ConnectionOnboarding.ConnectionOnboarding.pipe(
43
+ Effect.flatMap((onboarding) => onboarding.reaches(input)),
44
+ ),
45
+});
apps/web/src/i18n/translations/de.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "T3 Code auf {host} war zu beschäftigt, um zu antworten.",
459
"5c5941732d5dfac6": "Die Kopplungsdaten sind ungültig.",
460
"b8ca23ad7dda376e": "Diese Adresse führt zu {host}, einem anderen Rechner. Füge sie stattdessen als eigene Umgebung hinzu.",
461
+ "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
462
"693cb5c4fb40f109": "Nur gespeicherte Bearer-Umgebungen können bearbeitet werden.",
463
"5f5844b910cb1544": "Die gespeicherten Bearer-Zugangsdaten sind nicht verfügbar.",
464
"51b0133f1ed3cf5c": "Die Bezeichnung der Umgebung darf nicht leer sein.",
464
- "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
465
"3aa15bfbe1920376": "Aktualisiere T3 Code auf {host} manuell; es kann sich nicht selbst aktualisieren.",
466
"71907f57b7ec64d5": "{host} ist nicht mit einer kompatiblen T3-Code-Version zurückgekommen.",
467
"e77ac580a4ddcd3b": "Verfügbar",
@@ -3623,7 +3623,15 @@
3623
"009e2ca841fdc1ef": "diese Umgebung",
3624
"8cb2e5692c4f05ab": "Öffne diesen Thread auf {label}, um diese Darstellung zu sehen.",
3625
"745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.",
3626
+ "4ab24e2807a0d82f": "Mit {label} verbunden",
3627
+ "b797c7beccf2dc46": "Dieses Gerät ist damit gekoppelt und kann seine Threads verwenden.",
3628
+ "d8c4a71a728fcf68": "Verbindung mit {label} wird hergestellt…",
3629
+ "93e690821c726e13": "{label} ist von diesem Gerät aus nicht erreichbar",
3630
+ "a5424a5a76e10aa3": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.",
3631
+ "1942567fd95da447": "{label} benötigt einen Kopplungscode",
3632
+ "0f62d432499e13f9": "Erstelle dort einen und füge es diesem Gerät als Umgebung hinzu.",
3633
"0014ce0aaf1bd68a": "Schreibgeschützt",
3634
+ "10ca916def8211d4": "Code eingeben",
3635
"d0bda35aeec66684": [
3636
"Wird von ",
3637
{
@@ -3634,6 +3642,7 @@
3642
" gelesen …"
3643
],
3644
"c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.",
3645
+ "a446e3bda256c2b3": "Verbinden, um zu interagieren",
3646
"eb6e0584cf4a2a1d": "Sprache: {language}",
3647
"d76c606a3c519b78": "Zeilenumbruch deaktivieren",
3648
"2b683498cee8c8a7": "Zeilen umbrechen",
@@ -7303,8 +7312,10 @@
7312
"53c162d8868a1d0e": "Umgebung hinzufügen",
7313
"53339e47accf021a": "Hosts durchsuchen oder devbox eingeben",
7314
"d808738388ab80b0": "Route zu {environment} hinzufügen",
7315
+ "8a333daf9b7fd03f": "Mit {environment} verbinden",
7316
"7662025844bf543f": "Umgebung hinzufügen",
7317
"65b1d784a5e84254": "Kopple diesen Rechner erneut über eine andere Adresse, etwa seinen Tailscale-Namen. Er wird den vorhandenen Routen hinzugefügt, statt einen zweiten Rechner anzulegen.",
7318
+ "e1cb1c8599e84e26": "Erstelle auf {environment} einen Kopplungscode, in dessen Einstellungen → Freigabe & Zugriff oder mit `t3 auth pairing create`, und gib ihn hier ein.",
7319
"1bea4864d46d70d0": "Eine weitere Umgebung mit diesem Client koppeln.",
7320
"9b24ef052b321e57": "Gib einen Backend-Host und einen Kopplungscode ein.",
7321
"3e20f17f71edf0ad": "Lokale SSH-Konfiguration, Agent und Tunnel für das Backend verwenden.",
apps/web/src/i18n/translations/en.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "T3 Code on {host} was too busy to answer.",
459
"5c5941732d5dfac6": "The pairing details are invalid.",
460
"b8ca23ad7dda376e": "That address reaches {host}, a different machine. Add it as its own environment instead.",
461
+ "0c0150a90b582a7a": "The environment URL is invalid.",
462
"693cb5c4fb40f109": "Only saved bearer environments can be edited.",
463
"5f5844b910cb1544": "The saved bearer credential is unavailable.",
464
"51b0133f1ed3cf5c": "Environment label cannot be empty.",
464
- "0c0150a90b582a7a": "The environment URL is invalid.",
465
"3aa15bfbe1920376": "Update T3 Code on {host} manually; it cannot update itself.",
466
"71907f57b7ec64d5": "{host} did not come back on a compatible T3 Code version.",
467
"e77ac580a4ddcd3b": "Available",
@@ -3622,7 +3622,15 @@
3622
"009e2ca841fdc1ef": "this environment",
3623
"8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.",
3624
"745a0b899008618c": "Could not load earlier turns. Try again.",
3625
+ "4ab24e2807a0d82f": "Connected to {label}",
3626
+ "b797c7beccf2dc46": "This device is paired with it and can use its threads.",
3627
+ "d8c4a71a728fcf68": "Connecting to {label}…",
3628
+ "93e690821c726e13": "{label} is not reachable from this device",
3629
+ "a5424a5a76e10aa3": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.",
3630
+ "1942567fd95da447": "{label} needs a pairing code",
3631
+ "0f62d432499e13f9": "Create one on it, then add it to this device as an environment.",
3632
"0014ce0aaf1bd68a": "Read-only",
3633
+ "10ca916def8211d4": "Enter code",
3634
"d0bda35aeec66684": [
3635
"Reading from ",
3636
{
@@ -3633,6 +3641,7 @@
3641
"…"
3642
],
3643
"c3e8cd9bf44e2f43": "Showing what was read before.",
3644
+ "a446e3bda256c2b3": "Connect to interact",
3645
"eb6e0584cf4a2a1d": "Language: {language}",
3646
"d76c606a3c519b78": "Disable line wrap",
3647
"2b683498cee8c8a7": "Wrap lines",
@@ -7311,8 +7320,10 @@
7320
"53c162d8868a1d0e": "Add environment",
7321
"53339e47accf021a": "Search hosts or type devbox",
7322
"d808738388ab80b0": "Add a route to {environment}",
7323
+ "8a333daf9b7fd03f": "Connect to {environment}",
7324
"7662025844bf543f": "Add Environment",
7325
"65b1d784a5e84254": "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine.",
7326
+ "e1cb1c8599e84e26": "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
7327
"1bea4864d46d70d0": "Pair another environment to this client.",
7328
"9b24ef052b321e57": "Enter a backend host and pairing code.",
7329
"3e20f17f71edf0ad": "Use local SSH config, agent, and tunnels for the backend.",
apps/web/src/i18n/translations/es.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "T3 Code en {host} estaba demasiado ocupado para responder.",
459
"5c5941732d5dfac6": "Los datos de emparejamiento no son válidos.",
460
"b8ca23ad7dda376e": "Esa dirección lleva a {host}, otra máquina. Añádela como un entorno propio.",
461
+ "0c0150a90b582a7a": "La URL del entorno no es válida.",
462
"693cb5c4fb40f109": "Solo se pueden editar los entornos bearer guardados.",
463
"5f5844b910cb1544": "La credencial bearer guardada no está disponible.",
464
"51b0133f1ed3cf5c": "La etiqueta del entorno no puede estar vacía.",
464
- "0c0150a90b582a7a": "La URL del entorno no es válida.",
465
"3aa15bfbe1920376": "Actualiza T3 Code en {host} manualmente; no puede actualizarse solo.",
466
"71907f57b7ec64d5": "{host} no volvió con una versión compatible de T3 Code.",
467
"e77ac580a4ddcd3b": "Disponible",
@@ -3622,7 +3622,15 @@
3622
"009e2ca841fdc1ef": "este entorno",
3623
"8cb2e5692c4f05ab": "Abre este hilo en {label} para ver este elemento visual.",
3624
"745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.",
3625
+ "4ab24e2807a0d82f": "Conectado a {label}",
3626
+ "b797c7beccf2dc46": "Este dispositivo está emparejado con él y puede usar sus hilos.",
3627
+ "d8c4a71a728fcf68": "Conectando con {label}…",
3628
+ "93e690821c726e13": "No se puede acceder a {label} desde este dispositivo",
3629
+ "a5424a5a76e10aa3": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.",
3630
+ "1942567fd95da447": "{label} necesita un código de emparejamiento",
3631
+ "0f62d432499e13f9": "Crea uno allí y añádelo a este dispositivo como entorno.",
3632
"0014ce0aaf1bd68a": "Solo lectura",
3633
+ "10ca916def8211d4": "Introducir código",
3634
"d0bda35aeec66684": [
3635
"Leyendo desde ",
3636
{
@@ -3633,6 +3641,7 @@
3641
"…"
3642
],
3643
"c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.",
3644
+ "a446e3bda256c2b3": "Conectar para interactuar",
3645
"eb6e0584cf4a2a1d": "Lenguaje: {language}",
3646
"d76c606a3c519b78": "Desactivar ajuste de línea",
3647
"2b683498cee8c8a7": "Ajustar líneas",
@@ -7304,8 +7313,10 @@
7313
"53c162d8868a1d0e": "Añadir entorno",
7314
"53339e47accf021a": "Busca hosts o escribe devbox",
7315
"d808738388ab80b0": "Añadir una ruta a {environment}",
7316
+ "8a333daf9b7fd03f": "Conectar con {environment}",
7317
"7662025844bf543f": "Añadir entorno",
7318
"65b1d784a5e84254": "Vuelve a emparejar esta máquina con otra dirección, como su nombre de Tailscale. Se une a las rutas existentes en lugar de añadir una segunda máquina.",
7319
+ "e1cb1c8599e84e26": "Crea un código de emparejamiento en {environment}, en sus Ajustes → Compartir y acceso o con `t3 auth pairing create`, e introdúcelo aquí.",
7320
"1bea4864d46d70d0": "Empareja otro entorno con este cliente.",
7321
"9b24ef052b321e57": "Introduce un host de backend y un código de emparejamiento.",
7322
"3e20f17f71edf0ad": "Usa la configuración SSH local, el agente y los túneles para el backend.",
apps/web/src/i18n/translations/fr.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "T3 Code sur {host} était trop occupé pour répondre.",
459
"5c5941732d5dfac6": "Les informations d’appairage ne sont pas valides.",
460
"b8ca23ad7dda376e": "Cette adresse mène à {host}, une autre machine. Ajoutez-la plutôt comme environnement distinct.",
461
+ "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
462
"693cb5c4fb40f109": "Seuls les environnements bearer enregistrés peuvent être modifiés.",
463
"5f5844b910cb1544": "Les identifiants bearer enregistrés ne sont pas disponibles.",
464
"51b0133f1ed3cf5c": "Le libellé de l’environnement ne peut pas être vide.",
464
- "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
465
"3aa15bfbe1920376": "Mettez à jour T3 Code sur {host} manuellement ; il ne peut pas se mettre à jour seul.",
466
"71907f57b7ec64d5": "{host} n’est pas revenu sur une version compatible de T3 Code.",
467
"e77ac580a4ddcd3b": "Disponible",
@@ -3622,7 +3622,15 @@
3622
"009e2ca841fdc1ef": "cet environnement",
3623
"8cb2e5692c4f05ab": "Ouvrez ce fil sur {label} pour voir ce visuel.",
3624
"745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.",
3625
+ "4ab24e2807a0d82f": "Connecté à {label}",
3626
+ "b797c7beccf2dc46": "Cet appareil y est appairé et peut utiliser ses fils.",
3627
+ "d8c4a71a728fcf68": "Connexion à {label}…",
3628
+ "93e690821c726e13": "{label} n’est pas accessible depuis cet appareil",
3629
+ "a5424a5a76e10aa3": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.",
3630
+ "1942567fd95da447": "{label} nécessite un code d’appairage",
3631
+ "0f62d432499e13f9": "Créez-en un dessus, puis ajoutez-le à cet appareil comme environnement.",
3632
"0014ce0aaf1bd68a": "Lecture seule",
3633
+ "10ca916def8211d4": "Saisir le code",
3634
"d0bda35aeec66684": [
3635
"Lecture depuis ",
3636
{
@@ -3633,6 +3641,7 @@
3641
"…"
3642
],
3643
"c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.",
3644
+ "a446e3bda256c2b3": "Se connecter pour interagir",
3645
"eb6e0584cf4a2a1d": "Langage : {language}",
3646
"d76c606a3c519b78": "Désactiver le retour à la ligne",
3647
"2b683498cee8c8a7": "Retour à la ligne",
@@ -7305,8 +7314,10 @@
7314
"53c162d8868a1d0e": "Ajouter un environnement",
7315
"53339e47accf021a": "Rechercher des hôtes ou saisir devbox",
7316
"d808738388ab80b0": "Ajouter une route vers {environment}",
7317
+ "8a333daf9b7fd03f": "Se connecter à {environment}",
7318
"7662025844bf543f": "Ajouter un environnement",
7319
"65b1d784a5e84254": "Appairez à nouveau cette machine via une autre adresse, comme son nom Tailscale. Elle rejoint les routes existantes au lieu d’ajouter une deuxième machine.",
7320
+ "e1cb1c8599e84e26": "Créez un code d’appairage sur {environment}, dans ses Paramètres → Partage et accès ou avec `t3 auth pairing create`, puis saisissez-le ici.",
7321
"1bea4864d46d70d0": "Appairez un autre environnement à ce client.",
7322
"9b24ef052b321e57": "Saisissez un hôte de backend et un code d’appairage.",
7323
"3e20f17f71edf0ad": "Utiliser la configuration SSH locale, l’agent et les tunnels pour le backend.",
apps/web/src/i18n/translations/ja.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "{host} の T3 Code はビジー状態で応答できませんでした。",
459
"5c5941732d5dfac6": "ペアリングの詳細が無効です。",
460
"b8ca23ad7dda376e": "そのアドレスは別のマシンである {host} につながります。代わりに独立した環境として追加してください。",
461
+ "0c0150a90b582a7a": "環境の URL が無効です。",
462
"693cb5c4fb40f109": "編集できるのは保存済みのベアラー環境のみです。",
463
"5f5844b910cb1544": "保存済みのベアラー資格情報は利用できません。",
464
"51b0133f1ed3cf5c": "環境のラベルは空にできません。",
464
- "0c0150a90b582a7a": "環境の URL が無効です。",
465
"3aa15bfbe1920376": "{host} の T3 Code は自動で更新できないため、手動で更新してください。",
466
"71907f57b7ec64d5": "{host} は互換性のある T3 Code のバージョンで復帰しませんでした。",
467
"e77ac580a4ddcd3b": "利用可能",
@@ -3617,7 +3617,15 @@
3617
"009e2ca841fdc1ef": "この環境",
3618
"8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。",
3619
"745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。",
3620
+ "4ab24e2807a0d82f": "{label} に接続しました",
3621
+ "b797c7beccf2dc46": "このデバイスはペアリング済みで、そのスレッドを利用できます。",
3622
+ "d8c4a71a728fcf68": "{label} に接続しています…",
3623
+ "93e690821c726e13": "このデバイスから {label} に接続できません",
3624
+ "a5424a5a76e10aa3": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。",
3625
+ "1942567fd95da447": "{label} にはペアリングコードが必要です",
3626
+ "0f62d432499e13f9": "そのマシンで作成し、このデバイスに環境として追加してください。",
3627
"0014ce0aaf1bd68a": "読み取り専用",
3628
+ "10ca916def8211d4": "コードを入力",
3629
"d0bda35aeec66684": [
3630
"読み取り中: ",
3631
{
@@ -3628,6 +3636,7 @@
3636
"…"
3637
],
3638
"c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。",
3639
+ "a446e3bda256c2b3": "接続して操作する",
3640
"eb6e0584cf4a2a1d": "言語: {language}",
3641
"d76c606a3c519b78": "行の折り返しを無効にする",
3642
"2b683498cee8c8a7": "行を折り返す",
@@ -7271,8 +7280,10 @@
7280
"53c162d8868a1d0e": "環境を追加",
7281
"53339e47accf021a": "ホストを検索、または devbox と入力",
7282
"d808738388ab80b0": "{environment} へのルートを追加",
7283
+ "8a333daf9b7fd03f": "{environment} に接続",
7284
"7662025844bf543f": "環境を追加",
7285
"65b1d784a5e84254": "このマシンを別のアドレス (Tailscale の名前など) でもう一度ペアリングします。2 台目のマシンとして追加されるのではなく、既存のルートに加わります。",
7286
+ "e1cb1c8599e84e26": "{environment} の設定 → 共有とアクセス、または `t3 auth pairing create` でペアリングコードを作成し、ここに入力してください。",
7287
"1bea4864d46d70d0": "このクライアントに別の環境をペアリングします。",
7288
"9b24ef052b321e57": "バックエンドのホストとペアリングコードを入力してください。",
7289
"3e20f17f71edf0ad": "バックエンドにはローカルの SSH 構成、エージェント、トンネルを使用します。",
apps/web/src/i18n/translations/ko.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "{host}의 T3 Code가 너무 바빠서 응답하지 못했습니다.",
459
"5c5941732d5dfac6": "페어링 정보가 올바르지 않습니다.",
460
"b8ca23ad7dda376e": "이 주소는 다른 머신인 {host}에 연결됩니다. 대신 별도의 환경으로 추가하세요.",
461
+ "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
462
"693cb5c4fb40f109": "저장된 bearer 환경만 편집할 수 있습니다.",
463
"5f5844b910cb1544": "저장된 bearer 자격 증명을 사용할 수 없습니다.",
464
"51b0133f1ed3cf5c": "환경 레이블은 비워 둘 수 없습니다.",
464
- "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
465
"3aa15bfbe1920376": "{host}의 T3 Code는 스스로 업데이트할 수 없으니 직접 업데이트하세요.",
466
"71907f57b7ec64d5": "{host}이(가) 호환되는 T3 Code 버전으로 돌아오지 않았습니다.",
467
"e77ac580a4ddcd3b": "사용 가능",
@@ -3617,7 +3617,15 @@
3617
"009e2ca841fdc1ef": "이 환경",
3618
"8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.",
3619
"745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.",
3620
+ "4ab24e2807a0d82f": "{label}에 연결됨",
3621
+ "b797c7beccf2dc46": "이 기기가 페어링되어 해당 스레드를 사용할 수 있습니다.",
3622
+ "d8c4a71a728fcf68": "{label}에 연결하는 중…",
3623
+ "93e690821c726e13": "이 기기에서 {label}에 연결할 수 없습니다",
3624
+ "a5424a5a76e10aa3": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.",
3625
+ "1942567fd95da447": "{label}에 페어링 코드가 필요합니다",
3626
+ "0f62d432499e13f9": "해당 머신에서 코드를 만든 다음 이 기기에 환경으로 추가하세요.",
3627
"0014ce0aaf1bd68a": "읽기 전용",
3628
+ "10ca916def8211d4": "코드 입력",
3629
"d0bda35aeec66684": [
3630
"읽는 중: ",
3631
{
@@ -3628,6 +3636,7 @@
3636
"…"
3637
],
3638
"c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.",
3639
+ "a446e3bda256c2b3": "연결하여 상호작용",
3640
"eb6e0584cf4a2a1d": "언어: {language}",
3641
"d76c606a3c519b78": "줄 바꿈 끄기",
3642
"2b683498cee8c8a7": "줄 바꿈",
@@ -7274,8 +7283,10 @@
7283
"53c162d8868a1d0e": "환경 추가",
7284
"53339e47accf021a": "호스트 검색 또는 devbox 입력",
7285
"d808738388ab80b0": "{environment}에 경로 추가",
7286
+ "8a333daf9b7fd03f": "{environment}에 연결",
7287
"7662025844bf543f": "환경 추가",
7288
"65b1d784a5e84254": "Tailscale 이름 같은 다른 주소로 이 머신을 다시 페어링하세요. 두 번째 머신을 추가하는 대신 기존 경로에 합쳐집니다.",
7289
+ "e1cb1c8599e84e26": "{environment}의 설정 → 공유 및 액세스에서 또는 `t3 auth pairing create`로 페어링 코드를 만든 다음 여기에 입력하세요.",
7290
"1bea4864d46d70d0": "이 클라이언트에 다른 환경을 페어링합니다.",
7291
"9b24ef052b321e57": "백엔드 호스트와 페어링 코드를 입력하세요.",
7292
"3e20f17f71edf0ad": "백엔드에 로컬 SSH 구성, 에이전트, 터널을 사용합니다.",
apps/web/src/i18n/translations/pt-BR.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "O T3 Code em {host} estava ocupado demais para responder.",
459
"5c5941732d5dfac6": "Os detalhes de pareamento são inválidos.",
460
"b8ca23ad7dda376e": "Esse endereço leva a {host}, outra máquina. Adicione-a como um ambiente próprio.",
461
+ "0c0150a90b582a7a": "A URL do ambiente é inválida.",
462
"693cb5c4fb40f109": "Só é possível editar ambientes bearer salvos.",
463
"5f5844b910cb1544": "A credencial bearer salva não está disponível.",
464
"51b0133f1ed3cf5c": "O rótulo do ambiente não pode ficar vazio.",
464
- "0c0150a90b582a7a": "A URL do ambiente é inválida.",
465
"3aa15bfbe1920376": "Atualize o T3 Code em {host} manualmente; ele não consegue se atualizar sozinho.",
466
"71907f57b7ec64d5": "{host} não voltou em uma versão compatível do T3 Code.",
467
"e77ac580a4ddcd3b": "Disponível",
@@ -3622,7 +3622,15 @@
3622
"009e2ca841fdc1ef": "este ambiente",
3623
"8cb2e5692c4f05ab": "Abra este thread em {label} para ver este visual.",
3624
"745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.",
3625
+ "4ab24e2807a0d82f": "Conectado a {label}",
3626
+ "b797c7beccf2dc46": "Este dispositivo está pareado com ele e pode usar suas threads.",
3627
+ "d8c4a71a728fcf68": "Conectando a {label}…",
3628
+ "93e690821c726e13": "{label} não está acessível a partir deste dispositivo",
3629
+ "a5424a5a76e10aa3": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.",
3630
+ "1942567fd95da447": "{label} precisa de um código de pareamento",
3631
+ "0f62d432499e13f9": "Crie um nele e adicione-o a este dispositivo como ambiente.",
3632
"0014ce0aaf1bd68a": "Somente leitura",
3633
+ "10ca916def8211d4": "Inserir código",
3634
"d0bda35aeec66684": [
3635
"Lendo de ",
3636
{
@@ -3633,6 +3641,7 @@
3641
"…"
3642
],
3643
"c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.",
3644
+ "a446e3bda256c2b3": "Conectar para interagir",
3645
"eb6e0584cf4a2a1d": "Linguagem: {language}",
3646
"d76c606a3c519b78": "Desativar quebra de linha",
3647
"2b683498cee8c8a7": "Quebrar linhas",
@@ -7304,8 +7313,10 @@
7313
"53c162d8868a1d0e": "Adicionar ambiente",
7314
"53339e47accf021a": "Pesquise hosts ou digite devbox",
7315
"d808738388ab80b0": "Adicionar uma rota para {environment}",
7316
+ "8a333daf9b7fd03f": "Conectar a {environment}",
7317
"7662025844bf543f": "Adicionar ambiente",
7318
"65b1d784a5e84254": "Pareie esta máquina novamente por outro endereço, como o nome dela no Tailscale. Ele se junta às rotas existentes em vez de adicionar uma segunda máquina.",
7319
+ "e1cb1c8599e84e26": "Crie um código de pareamento em {environment}, em Configurações → Compartilhamento e acesso ou com `t3 auth pairing create`, e insira-o aqui.",
7320
"1bea4864d46d70d0": "Parear outro ambiente com este cliente.",
7321
"9b24ef052b321e57": "Informe o host do backend e um código de pareamento.",
7322
"3e20f17f71edf0ad": "Usa a configuração SSH local, o agent e túneis para o backend.",
apps/web/src/i18n/translations/ru.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "T3 Code на {host} был слишком занят, чтобы ответить.",
459
"5c5941732d5dfac6": "Данные сопряжения недействительны.",
460
"b8ca23ad7dda376e": "Этот адрес ведёт к {host}, другому компьютеру. Добавьте его как отдельное окружение.",
461
+ "0c0150a90b582a7a": "URL окружения недействителен.",
462
"693cb5c4fb40f109": "Изменять можно только сохранённые окружения с bearer-токеном.",
463
"5f5844b910cb1544": "Сохранённые bearer-учётные данные недоступны.",
464
"51b0133f1ed3cf5c": "Название окружения не может быть пустым.",
464
- "0c0150a90b582a7a": "URL окружения недействителен.",
465
"3aa15bfbe1920376": "Обновите T3 Code на {host} вручную: он не может обновиться сам.",
466
"71907f57b7ec64d5": "{host} не вернулся с совместимой версией T3 Code.",
467
"e77ac580a4ddcd3b": "Доступно",
@@ -3622,7 +3622,15 @@
3622
"009e2ca841fdc1ef": "это окружение",
3623
"8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.",
3624
"745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.",
3625
+ "4ab24e2807a0d82f": "Подключено к {label}",
3626
+ "b797c7beccf2dc46": "Это устройство сопряжено с ним и может работать с его тредами.",
3627
+ "d8c4a71a728fcf68": "Подключение к {label}…",
3628
+ "93e690821c726e13": "{label} недоступно с этого устройства",
3629
+ "a5424a5a76e10aa3": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.",
3630
+ "1942567fd95da447": "Для {label} нужен код сопряжения",
3631
+ "0f62d432499e13f9": "Создайте его там и добавьте эту машину на устройство как окружение.",
3632
"0014ce0aaf1bd68a": "Только чтение",
3633
+ "10ca916def8211d4": "Ввести код",
3634
"d0bda35aeec66684": [
3635
"Чтение с ",
3636
{
@@ -3633,6 +3641,7 @@
3641
"…"
3642
],
3643
"c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.",
3644
+ "a446e3bda256c2b3": "Подключиться для взаимодействия",
3645
"eb6e0584cf4a2a1d": "Язык: {language}",
3646
"d76c606a3c519b78": "Отключить перенос строк",
3647
"2b683498cee8c8a7": "Переносить строки",
@@ -7304,8 +7313,10 @@
7313
"53c162d8868a1d0e": "Добавить окружение",
7314
"53339e47accf021a": "Поиск хостов или введите devbox",
7315
"d808738388ab80b0": "Добавить маршрут к {environment}",
7316
+ "8a333daf9b7fd03f": "Подключиться к {environment}",
7317
"7662025844bf543f": "Добавить окружение",
7318
"65b1d784a5e84254": "Выполните сопряжение с этой машиной заново по другому адресу, например по имени в Tailscale. Он добавится к существующим маршрутам, а не создаст вторую машину.",
7319
+ "e1cb1c8599e84e26": "Создайте код сопряжения на {environment} в разделе «Настройки → Общий доступ» или командой `t3 auth pairing create` и введите его здесь.",
7320
"1bea4864d46d70d0": "Выполните сопряжение этого клиента с другим окружением.",
7321
"9b24ef052b321e57": "Введите хост бэкенда и код сопряжения.",
7322
"3e20f17f71edf0ad": "Использовать локальные конфигурацию SSH, агент и туннели для бэкенда.",
apps/web/src/i18n/translations/sv.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "T3 Code på {host} var för upptagen för att svara.",
459
"5c5941732d5dfac6": "Uppgifterna för parkopplingen är ogiltiga.",
460
"b8ca23ad7dda376e": "Den adressen leder till {host}, en annan dator. Lägg till den som en egen miljö i stället.",
461
+ "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
462
"693cb5c4fb40f109": "Bara sparade bearer-miljöer kan redigeras.",
463
"5f5844b910cb1544": "Den sparade bearer-uppgiften är inte tillgänglig.",
464
"51b0133f1ed3cf5c": "Miljöns etikett får inte vara tom.",
464
- "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
465
"3aa15bfbe1920376": "Uppdatera T3 Code på {host} manuellt; det kan inte uppdatera sig självt.",
466
"71907f57b7ec64d5": "{host} kom inte tillbaka med en kompatibel version av T3 Code.",
467
"e77ac580a4ddcd3b": "Tillgänglig",
@@ -3622,7 +3622,15 @@
3622
"009e2ca841fdc1ef": "den här miljön",
3623
"8cb2e5692c4f05ab": "Öppna den här tråden på {label} för att se den här visualiseringen.",
3624
"745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.",
3625
+ "4ab24e2807a0d82f": "Ansluten till {label}",
3626
+ "b797c7beccf2dc46": "Den här enheten är parkopplad med den och kan använda dess trådar.",
3627
+ "d8c4a71a728fcf68": "Ansluter till {label}…",
3628
+ "93e690821c726e13": "{label} kan inte nås från den här enheten",
3629
+ "a5424a5a76e10aa3": "Anslut till ett nätverk som den finns på, till exempel dess Tailscale-nätverk, och försök igen. Du kan fortsätta läsa här.",
3630
+ "1942567fd95da447": "{label} behöver en parkopplingskod",
3631
+ "0f62d432499e13f9": "Skapa en där och lägg till den på den här enheten som en miljö.",
3632
"0014ce0aaf1bd68a": "Skrivskyddad",
3633
+ "10ca916def8211d4": "Ange kod",
3634
"d0bda35aeec66684": [
3635
"Läser från ",
3636
{
@@ -3633,6 +3641,7 @@
3641
"…"
3642
],
3643
"c3e8cd9bf44e2f43": "Visar det som lästes tidigare.",
3644
+ "a446e3bda256c2b3": "Anslut för att interagera",
3645
"eb6e0584cf4a2a1d": "Språk: {language}",
3646
"d76c606a3c519b78": "Inaktivera radbrytning",
3647
"2b683498cee8c8a7": "Bryt rader",
@@ -7310,8 +7319,10 @@
7319
"53c162d8868a1d0e": "Lägg till miljö",
7320
"53339e47accf021a": "Sök värdar eller skriv devbox",
7321
"d808738388ab80b0": "Lägg till en rutt till {environment}",
7322
+ "8a333daf9b7fd03f": "Anslut till {environment}",
7323
"7662025844bf543f": "Lägg till miljö",
7324
"65b1d784a5e84254": "Parkoppla den här datorn igen via en annan adress, till exempel dess Tailscale-namn. Den ansluter till de befintliga rutterna i stället för att lägga till en andra dator.",
7325
+ "e1cb1c8599e84e26": "Skapa en parkopplingskod på {environment}, i dess Inställningar → Delning och åtkomst eller med `t3 auth pairing create`, och ange den här.",
7326
"1bea4864d46d70d0": "Parkoppla en annan miljö med den här klienten.",
7327
"9b24ef052b321e57": "Ange en backend-värd och en parkopplingskod.",
7328
"3e20f17f71edf0ad": "Använd lokal SSH-konfiguration, agent och tunnlar för backenden.",
apps/web/src/i18n/translations/zh.json
+12
-1
@@ -458,10 +458,10 @@
458
"93e37fedae7eaa5b": "{host} 上的 T3 Code 太忙,未能响应。",
459
"5c5941732d5dfac6": "配对信息无效。",
460
"b8ca23ad7dda376e": "该地址指向另一台机器 {host}。请将其添加为独立环境。",
461
+ "0c0150a90b582a7a": "环境 URL 无效。",
462
"693cb5c4fb40f109": "只能编辑已保存的 bearer 环境。",
463
"5f5844b910cb1544": "已保存的 bearer 凭据不可用。",
464
"51b0133f1ed3cf5c": "环境名称不能为空。",
464
- "0c0150a90b582a7a": "环境 URL 无效。",
465
"3aa15bfbe1920376": "请手动更新 {host} 上的 T3 Code;它无法自行更新。",
466
"71907f57b7ec64d5": "{host} 重启后未运行兼容的 T3 Code 版本。",
467
"e77ac580a4ddcd3b": "可用",
@@ -3627,7 +3627,15 @@
3627
"009e2ca841fdc1ef": "此环境",
3628
"8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。",
3629
"745a0b899008618c": "无法加载更早的对话。请重试。",
3630
+ "4ab24e2807a0d82f": "已连接到 {label}",
3631
+ "b797c7beccf2dc46": "此设备已与其配对,可以使用其中的会话。",
3632
+ "d8c4a71a728fcf68": "正在连接 {label}…",
3633
+ "93e690821c726e13": "无法从此设备访问 {label}",
3634
+ "a5424a5a76e10aa3": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。",
3635
+ "1942567fd95da447": "{label} 需要配对码",
3636
+ "0f62d432499e13f9": "在该机器上创建配对码,然后将其作为环境添加到此设备。",
3637
"0014ce0aaf1bd68a": "只读",
3638
+ "10ca916def8211d4": "输入配对码",
3639
"d0bda35aeec66684": [
3640
"正在从 ",
3641
{
@@ -3638,6 +3646,7 @@
3646
" 读取…"
3647
],
3648
"c3e8cd9bf44e2f43": "正在显示之前读取的内容。",
3649
+ "a446e3bda256c2b3": "连接以进行交互",
3650
"eb6e0584cf4a2a1d": "语言:{language}",
3651
"d76c606a3c519b78": "取消自动换行",
3652
"2b683498cee8c8a7": "自动换行",
@@ -7319,8 +7328,10 @@
7328
"53c162d8868a1d0e": "添加环境",
7329
"53339e47accf021a": "搜索主机或输入 devbox",
7330
"d808738388ab80b0": "为 {environment} 添加线路",
7331
+ "8a333daf9b7fd03f": "连接到 {environment}",
7332
"7662025844bf543f": "添加环境",
7333
"65b1d784a5e84254": "使用其他地址(例如 Tailscale 名称)再次配对此机器。该地址将加入现有线路,不会重复添加机器。",
7334
+ "e1cb1c8599e84e26": "在 {environment} 的设置 → 共享与访问中或使用 `t3 auth pairing create` 创建配对码,然后在此输入。",
7335
"1bea4864d46d70d0": "将其他环境与此客户端配对。",
7336
"9b24ef052b321e57": "输入后端主机和配对码。",
7337
"3e20f17f71edf0ad": "使用本地 SSH 配置、认证代理和隧道连接后端。",
apps/web/src/state/linkedThreadView.ts
+107
-2
@@ -1,6 +1,7 @@
1
-import { useAtomValue } from "@effect/atom-react";
2
-import { scopeThreadRef } from "@t3tools/client-runtime/environment";
1
+import { useAtom, useAtomSet, useAtomValue } from "@effect/atom-react";
2
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3
import {
4
+ connectLinkedEnvironment,
5
type LinkedThreadOpen,
6
resolveLinkedThreadOpen,
7
} from "@t3tools/client-runtime/linked-thread";
@@ -10,11 +11,13 @@ import { AsyncResult, Atom } from "effect/reactivity";
11
12
import type { TurnItemSource } from "../components/chat/timelineRowContext";
13
import { useRightPanelStore } from "../rightPanelStore";
14
+import { connectPairing, reachesEnvironment } from "../connection/onboarding";
15
import type { LinkedThreadSurface } from "../linkedThreadSurface";
16
import { buildThreadRouteParams } from "../threadRoutes";
17
import { useEnvironment } from "./environments";
18
import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
19
import { useEnvironmentQuery } from "./query";
20
+import { useAtomCommand } from "./use-atom-command";
21
22
/**
23
* How a click opens a thread that the thread `panelRef` says is on a linked environment: in place
@@ -127,6 +130,108 @@ export function useLinkedThreadView(
130
};
131
}
132
133
+/** A linked environment the add-environment dialog opens for, with what is known about it filled in. */
134
+export interface AddEnvironmentPrefill {
135
+ readonly environmentId: EnvironmentId;
136
+ readonly label: string;
137
+ readonly host: string | null;
138
+}
139
+
140
+export const addEnvironmentPrefillAtom = Atom.make<AddEnvironmentPrefill | null>(null).pipe(
141
+ Atom.withLabel("add-environment-prefill"),
142
+);
143
+
144
+export type LinkedEnvironmentConnectState =
145
+ | { readonly phase: "idle" | "connecting" }
146
+ | { readonly phase: "unreachable"; readonly label: string }
147
+ /** The user pairs with a code of their own; `prefill` reopens the dialog for it. */
148
+ | { readonly phase: "manual"; readonly prefill: AddEnvironmentPrefill };
149
+
150
+// Kept like the tab's reads, so the tab still says what happened after a visit to Settings.
151
+const linkedEnvironmentConnectAtom = Atom.family((key: string) =>
152
+ Atom.make<LinkedEnvironmentConnectState>({ phase: "idle" }).pipe(
153
+ Atom.setIdleTTL(5 * 60_000),
154
+ Atom.withLabel(`linked-environment-connect:${key}`),
155
+ ),
156
+);
157
+
158
+/**
159
+ * Connects this client to the environment `surface`'s thread lives in. One step when the linking
160
+ * environment can get a pairing for this client: the thread then opens there and the tab closes.
161
+ * Otherwise the add-environment dialog opens for that machine.
162
+ */
163
+export function useConnectLinkedEnvironment(
164
+ panelRef: ScopedThreadRef,
165
+ surface: LinkedThreadSurface,
166
+) {
167
+ const navigate = useNavigate();
168
+ const setPrefill = useAtomSet(addEnvironmentPrefillAtom);
169
+ const mayPair = useAtomValue(
170
+ peerLinkEnvironment.pairClient.permissionAtom(surface.viaEnvironmentId),
171
+ );
172
+ const quiet = { reportFailure: false, reportDefect: false } as const;
173
+ const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
174
+ const reaches = useAtomCommand(reachesEnvironment, quiet);
175
+ const pair = useAtomCommand(connectPairing, quiet);
176
+ const [state, setState] = useAtom(
177
+ linkedEnvironmentConnectAtom(`${scopedThreadKey(panelRef)}:${surface.id}`),
178
+ );
179
+ const addWithCode = (prefill: AddEnvironmentPrefill) => {
180
+ setPrefill(prefill);
181
+ void navigate({ to: "/settings/connections" });
182
+ };
183
+ const connect = async () => {
184
+ setState({ phase: "connecting" });
185
+ const outcome = await connectLinkedEnvironment({
186
+ label: surface.label,
187
+ requestPairing: async () => {
188
+ // Without it the linking environment refuses; the user can still pair by hand.
189
+ if (!mayPair) return null;
190
+ const result = await requestPairing({
191
+ environmentId: surface.viaEnvironmentId,
192
+ input: { environmentId: surface.environmentId },
193
+ });
194
+ return result._tag === "Success" ? result.value : null;
195
+ },
196
+ reaches: async (host) => {
197
+ const result = await reaches({ host, environmentId: surface.environmentId });
198
+ return result._tag === "Success" && result.value;
199
+ },
200
+ pair: async ({ host, pairingCode }) => {
201
+ const result = await pair({
202
+ host,
203
+ pairingCode,
204
+ expectedEnvironmentId: surface.environmentId,
205
+ });
206
+ return result._tag === "Success";
207
+ },
208
+ });
209
+ if (outcome.type === "unreachable") {
210
+ setState({ phase: "unreachable", label: outcome.label });
211
+ return outcome;
212
+ }
213
+ if (outcome.type === "connected") {
214
+ setState({ phase: "idle" });
215
+ // The thread opens where every thread on a connected environment does, so its tab is done.
216
+ useRightPanelStore.getState().closeSurface(panelRef, surface.id);
217
+ void navigate({
218
+ to: "/$environmentId/$threadId",
219
+ params: buildThreadRouteParams(scopeThreadRef(surface.environmentId, surface.threadId)),
220
+ });
221
+ return outcome;
222
+ }
223
+ const prefill = {
224
+ environmentId: surface.environmentId,
225
+ label: outcome.label,
226
+ host: outcome.host,
227
+ };
228
+ setState({ phase: "manual", prefill });
229
+ addWithCode(prefill);
230
+ return outcome;
231
+ };
232
+ return { state, connect, addWithCode };
233
+}
234
+
235
/** Where a linked thread's expanded rows read an item in full: through the linking environment. */
236
export const linkedThreadItemSource = (
237
target: Pick<LinkedThreadSurface, "viaEnvironmentId" | "environmentId">,
docs/internals/environment-auth.md
+13
-1
@@ -79,7 +79,8 @@ declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts)
79
where every tool must declare who may call it to compile. Any other grant adds
80
`orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions, and for a
81
[peer link](remote.md#peer-links)'s session alone the thread routes in
82
-[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read. Every other HTTP and WebSocket
82
+[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read, and the
83
+client pairing described below. Every other HTTP and WebSocket
84
path rejects that subject, because the RPC surface would let the agent act
85
above its ceiling. Inside MCP the credential sets the limits and tool
86
parameters only pick targets; see
@@ -91,6 +92,17 @@ discovery: the handlers still refuse such a call with
92
`thread_credential_required`. A secret card belongs to a thread's run, so an
93
outside agent that needs a secret starts a thread and lets that agent ask.
94
95
+A full-access [peer link](../../apps/server/src/peer/PeerClientPairing.ts) may
96
+mint a one-time pairing for a client of the environment that holds it. Its
97
+agents already run as this machine's user and could run `t3 auth pairing create`,
98
+so this adds no authority; a narrower link would gain some, so it is refused
99
+here, on the linked side, whatever the linking side sent. The pairing carries
100
+the client's scopes on the linking environment intersected with a normal
101
+pairing's. A person starts it: the linking environment exposes it as a WebSocket
102
+RPC behind `access:write`, and the linked side as an HTTP route that accepts only
103
+a link's session. It is not an MCP tool, because a tool is reachable by whatever
104
+holds a thread credential, and hiding one from tool listings is only discovery.
105
+
106
Issuer and resource URLs come from the request's Host and
107
`X-Forwarded-Proto`, so one server answers over loopback, Tailscale Serve and a
108
T3 Connect tunnel. A proxy that rewrites Host or drops the protocol header
docs/user/remote-access.md
+10
-1
@@ -487,7 +487,16 @@ it opens as a tab in the right panel, beside the thread you are in, and shows
487
the same timeline as any other thread.
488
489
- The view is marked **Read-only** with both machines' names. To reply, approve
490
- or stop the thread, connect this app to that machine.
490
+ or stop the thread, choose **Connect to interact**. When the link has full
491
+ access, this app pairs with that machine in one step and opens the thread
492
+ there; you need permission to manage access on the machine you are connected
493
+ to. Otherwise the add-environment form opens for that machine and asks for a
494
+ pairing code you create on it.
495
+- This app connects to that machine directly, so it must be able to reach one of
496
+ the addresses the link uses. If it cannot, the view says so and stays
497
+ read-only. The new connection appears in that machine's **Settings → Sharing &
498
+ access**, named after this device and the machine it came through, and is
499
+ revoked there like any other.
500
- Files, images and published visuals stay on that machine and do not load
501
here. A command's output shows as of when you open its row.
502
- If this app is already connected to that machine, the thread opens there as
packages/client-runtime/src/connection/onboarding.ts
+32
@@ -83,6 +83,11 @@ export class ConnectionOnboarding extends Context.Service<
83
readonly updateBearer: (
84
input: BearerConnectionUpdateInput,
85
) => Effect.Effect<void, ConnectionAttemptError | Persistence.ConnectionPersistenceError>;
86
+ /** Whether `host` answers this device as `environmentId`. Nothing is sent but the question. */
87
+ readonly reaches: (input: {
88
+ readonly host: string;
89
+ readonly environmentId: EnvironmentId;
90
+ }) => Effect.Effect<boolean>;
91
}
92
>()("@t3tools/client-runtime/connection/onboarding/ConnectionOnboarding") {}
93
@@ -214,6 +219,27 @@ const registerPairingConnection = Effect.fn(
219
return registration.target.environmentId;
220
});
221
222
+const REACHABILITY_TIMEOUT_MS = 6_000;
223
+
224
+const reachesEnvironment = Effect.fn("clientRuntime.connection.onboarding.reachesEnvironment")(
225
+ function* (input: { readonly host: string; readonly environmentId: EnvironmentId }) {
226
+ const httpBaseUrl = yield* Effect.try({
227
+ try: () => normalizeHttpBaseUrl(input.host),
228
+ catch: () =>
229
+ new ConnectionBlockedError({
230
+ reason: "configuration",
231
+ ...translatableDetail(msg("The environment URL is invalid.")),
232
+ }),
233
+ });
234
+ const descriptor = yield* fetchRemoteEnvironmentDescriptor({
235
+ httpBaseUrl,
236
+ timeoutMs: REACHABILITY_TIMEOUT_MS,
237
+ });
238
+ return descriptor.environmentId === input.environmentId;
239
+ },
240
+ Effect.orElseSucceed(() => false),
241
+);
242
+
243
const isBearerProfile = Schema.is(BearerConnectionProfile);
244
245
const updateBearerConnection = Effect.fn(
@@ -378,6 +404,12 @@ export const make = Effect.gen(function* () {
404
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
405
Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
406
),
407
+ reaches: Effect.fnUntraced(
408
+ function* (input) {
409
+ return yield* reachesEnvironment(input);
410
+ },
411
+ Effect.provideService(HttpClient.HttpClient, httpClient),
412
+ ),
413
});
414
});
415
packages/client-runtime/src/linkedThread.test.ts
+80
-1
@@ -1,9 +1,12 @@
1
import {
2
+ EnvironmentId,
3
EventId,
4
type OrchestrationV2ThreadHistoryPage,
5
type OrchestrationV2ThreadStreamItem,
6
+ type PeerLinkClientPairingResult,
7
} from "@t3tools/contracts";
6
-import { expect, it } from "@effect/vitest";
8
+import { describe, expect, it } from "@effect/vitest";
9
+import * as DateTime from "effect/DateTime";
10
import * as Effect from "effect/Effect";
11
import * as Fiber from "effect/Fiber";
12
import * as Queue from "effect/Queue";
@@ -11,6 +14,7 @@ import * as Stream from "effect/Stream";
14
import { TestClock } from "effect/testing";
15
16
import {
17
+ connectLinkedEnvironment,
18
followLinkedThread,
19
keepLinkedThreadView,
20
LINKED_THREAD_RETRY_MS,
@@ -158,3 +162,78 @@ it.effect("loads the turns before a snapshot's window once per request", () =>
162
expect(asked).toEqual(["cursor-1"]);
163
}).pipe(Effect.scoped),
164
);
165
+
166
+describe("connectLinkedEnvironment", () => {
167
+ const lan = "http://192.168.1.20:3773";
168
+ const tailnet = "https://vm.tail.ts.net";
169
+ const target = {
170
+ environmentId: EnvironmentId.make("environment-vm"),
171
+ label: "VM",
172
+ urls: [lan, tailnet],
173
+ };
174
+ const credential: PeerLinkClientPairingResult = {
175
+ type: "credential",
176
+ ...target,
177
+ credential: "ONE-TIME",
178
+ expiresAt: DateTime.makeUnsafe(0),
179
+ };
180
+ const connect = (
181
+ pairing: PeerLinkClientPairingResult | null,
182
+ reachable: ReadonlyArray<string>,
183
+ paired = true,
184
+ ) => {
185
+ const pairs: Array<{ host: string; pairingCode: string }> = [];
186
+ return connectLinkedEnvironment({
187
+ label: "vm (saved name)",
188
+ requestPairing: async () => pairing,
189
+ reaches: async (host) => reachable.includes(host),
190
+ pair: async (input) => {
191
+ pairs.push(input);
192
+ return paired;
193
+ },
194
+ }).then((outcome) => ({ outcome, pairs }));
195
+ };
196
+
197
+ it("redeems the pairing at the first address this device reaches", async () => {
198
+ expect(await connect(credential, [tailnet])).toEqual({
199
+ outcome: { type: "connected" },
200
+ pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
201
+ });
202
+ expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan);
203
+ });
204
+
205
+ it("says the machine is out of reach, and spends nothing, when no address answers", async () => {
206
+ expect(await connect(credential, [])).toEqual({
207
+ outcome: { type: "unreachable", label: "VM" },
208
+ pairs: [],
209
+ });
210
+ });
211
+
212
+ it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => {
213
+ const unsupported: PeerLinkClientPairingResult = {
214
+ type: "unsupported",
215
+ reason: "link_access",
216
+ ...target,
217
+ };
218
+ const manual = (host: string | null) => ({
219
+ outcome: { type: "manual", label: "VM", host },
220
+ pairs: [],
221
+ });
222
+ expect(await connect(unsupported, [tailnet])).toEqual(manual(tailnet));
223
+ // An address the user can correct beats an empty field.
224
+ expect(await connect(unsupported, [])).toEqual(manual(lan));
225
+ expect(await connect({ ...unsupported, urls: [] }, [])).toEqual(manual(null));
226
+ // The linking environment never answered, so only the client's own name is known.
227
+ expect((await connect(null, [lan])).outcome).toEqual({
228
+ type: "manual",
229
+ label: "vm (saved name)",
230
+ host: null,
231
+ });
232
+ // The one-time pairing was refused where it was redeemed.
233
+ expect((await connect(credential, [lan], false)).outcome).toEqual({
234
+ type: "manual",
235
+ label: "VM",
236
+ host: lan,
237
+ });
238
+ });
239
+});
packages/client-runtime/src/linkedThread.ts
+41
@@ -3,6 +3,7 @@ import type {
3
OrchestrationV2ThreadHistoryPage,
4
OrchestrationV2ThreadProjection,
5
OrchestrationV2ThreadStreamItem,
6
+ PeerLinkClientPairingResult,
7
ThreadId,
8
} from "@t3tools/contracts";
9
import * as Effect from "effect/Effect";
@@ -56,6 +57,46 @@ export function resolveLinkedThreadOpen(input: {
57
return input.own === undefined ? "unavailable" : "direct";
58
}
59
60
+export type LinkedEnvironmentConnection =
61
+ /** This client paired with the linked environment and saved it. */
62
+ | { readonly type: "connected" }
63
+ /** No address the linking environment knows answers from this device. */
64
+ | { readonly type: "unreachable"; readonly label: string }
65
+ /** The user pairs with a code of their own, in the add-environment flow, with this filled in. */
66
+ | { readonly type: "manual"; readonly label: string; readonly host: string | null };
67
+
68
+/**
69
+ * Connects this client to a linked environment. The linking environment asks it for a one-time
70
+ * pairing over a full-access link, and the client redeems that at an address it can reach itself.
71
+ * Anything short of that leaves the user to pair by hand.
72
+ */
73
+export async function connectLinkedEnvironment(options: {
74
+ readonly label: string;
75
+ /** Asks the linking environment for a pairing; null when it could not answer. */
76
+ readonly requestPairing: () => Promise<PeerLinkClientPairingResult | null>;
77
+ /** Whether an address answers this device as the linked environment. */
78
+ readonly reaches: (host: string) => Promise<boolean>;
79
+ /** Pairs at `host` with the one-time credential and saves the environment. */
80
+ readonly pair: (input: {
81
+ readonly host: string;
82
+ readonly pairingCode: string;
83
+ }) => Promise<boolean>;
84
+}): Promise<LinkedEnvironmentConnection> {
85
+ const pairing = await options.requestPairing();
86
+ if (pairing === null) return { type: "manual", label: options.label, host: null };
87
+ const { label, urls } = pairing;
88
+ // Asked together, taken in the linking environment's order of preference.
89
+ const answers = await Promise.all(urls.map((url) => options.reaches(url)));
90
+ const host = urls.find((_, index) => answers[index]) ?? null;
91
+ if (pairing.type === "unsupported") {
92
+ return { type: "manual", label, host: host ?? urls[0] ?? null };
93
+ }
94
+ if (host === null) return { type: "unreachable", label };
95
+ return (await options.pair({ host, pairingCode: pairing.credential }))
96
+ ? { type: "connected" }
97
+ : { type: "manual", label, host };
98
+}
99
+
100
const hasStringField = <K extends string>(value: unknown, key: K): value is Record<K, string> =>
101
typeof value === "object" &&
102
value !== null &&
packages/client-runtime/src/state/peerLinks.ts
+9
@@ -115,6 +115,15 @@ export function createPeerLinkEnvironmentAtoms<R, E>(
115
tag: WS_METHODS.peerLinksThreadItem,
116
idleTtlMs: 0,
117
}),
118
+ /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */
119
+ pairClient: createEnvironmentRpcCommand(runtime, {
120
+ label: "environment-data:peer-links:pair-client",
121
+ tag: WS_METHODS.peerLinksPairClient,
122
+ concurrency: {
123
+ mode: "singleFlight",
124
+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]),
125
+ },
126
+ }),
127
// An agent's link card. One answer per card at a time.
128
answerRequest: createEnvironmentRpcCommand(runtime, {
129
label: "environment-data:peer-links:answer-request",
packages/contracts/src/clientRpcPermissions.ts
+1
@@ -86,6 +86,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
86
[WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
87
// A link lets every agent here reach the other environment: Settings' bar.
88
[WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope,
89
+ [WS_METHODS.peerLinksPairClient]: AuthAccessWriteScope,
90
} as const;
91
export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;
92
packages/contracts/src/environment.ts
+3
@@ -191,6 +191,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
191
/** Serves a thread's stream, history pages and item detail to a link's session
192
(`PEER_LINK_THREAD_STREAM_ROUTE`), so a client of the linking environment can read it. */
193
linkThreadStream: Schema.optionalKey(Schema.Boolean),
194
+ /** A full-access link can ask this server for a one-time pairing credential for a client
195
+ of the linking environment. Absent on servers from before it. */
196
+ linkClientPairing: Schema.optionalKey(Schema.Boolean),
197
/** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */
198
mcpApprovalCodes: Schema.optionalKey(Schema.Boolean),
199
peerLinkPairingCodes: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/environmentHttp.ts
+20
-1
@@ -70,6 +70,7 @@ import {
70
EnvironmentSpeechStatus,
71
EnvironmentSpeechTranscriptionResult,
72
} from "./speech.ts";
73
+import { PeerLinkClientPairingCredential, PeerLinkClientPairingRequest } from "./peerLink.ts";
74
import { SecretReference } from "./secretReference.ts";
75
import {
76
OrchestrationV2ShellHttpSnapshot,
@@ -1052,6 +1053,23 @@ class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
1053
}),
1054
) {}
1055
1056
+/**
1057
+ * What a linking environment asks of this one over its link, outside `/mcp`. The handler accepts
1058
+ * only a peer link's own session, so no agent's tool list ever carries it.
1059
+ */
1060
+class EnvironmentPeerLinkHttpApi extends HttpApiGroup.make("peerLink").add(
1061
+ HttpApiEndpoint.post("clientPairing", "/api/peer-link/client-pairing", {
1062
+ headers: OptionalBearerHeaders,
1063
+ payload: PeerLinkClientPairingRequest,
1064
+ success: PeerLinkClientPairingCredential,
1065
+ error: [
1066
+ EnvironmentHttpUnauthorizedError,
1067
+ EnvironmentHttpForbiddenError,
1068
+ EnvironmentHttpInternalServerError,
1069
+ ],
1070
+ }),
1071
+) {}
1072
+
1073
// Path tokens and optional body signatures authenticate webhooks; read raw bytes to verify signatures.
1074
const WebhookParams = Schema.Struct({
1075
hookId: TrimmedNonEmptyString,
@@ -1081,4 +1099,5 @@ export class EnvironmentHttpApi extends HttpApi.make("environment")
1099
.add(EnvironmentProjectsHttpApi)
1100
.add(EnvironmentVoiceHttpApi)
1101
.add(EnvironmentConnectHttpApi)
1084
- .add(EnvironmentWebhooksHttpApi) {}
1102
+ .add(EnvironmentWebhooksHttpApi)
1103
+ .add(EnvironmentPeerLinkHttpApi) {}
packages/contracts/src/peerLink.ts
+55
-1
@@ -1,6 +1,6 @@
1
import * as Schema from "effect/Schema";
2
3
-import { AuthMcpClientAccess } from "./auth.ts";
3
+import { AuthEnvironmentScope, AuthMcpClientAccess } from "./auth.ts";
4
import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
5
6
/**
@@ -156,6 +156,60 @@ export class PeerLinkThreadReadError extends Schema.TaggedError<PeerLinkThreadRe
156
},
157
) {}
158
159
+/** A client of this environment asks to pair with one it links to, without typing a code. */
160
+export const PeerLinkClientPairingInput = Schema.Struct({ environmentId: EnvironmentId });
161
+export type PeerLinkClientPairingInput = typeof PeerLinkClientPairingInput.Type;
162
+
163
+const peerLinkClientPairingTarget = {
164
+ environmentId: EnvironmentId,
165
+ label: Schema.String,
166
+ /** The addresses this environment reaches the linked one at; the client tries them itself. */
167
+ urls: Schema.Array(TrimmedNonEmptyString),
168
+};
169
+
170
+/**
171
+ * A one-time pairing credential from the linked environment, or why this link cannot get one, in
172
+ * which case the user pairs there with a code of their own.
173
+ */
174
+export const PeerLinkClientPairingResult = Schema.Union([
175
+ Schema.Struct({
176
+ type: Schema.Literal("credential"),
177
+ ...peerLinkClientPairingTarget,
178
+ credential: TrimmedNonEmptyString,
179
+ expiresAt: Schema.DateTimeUtc,
180
+ }),
181
+ Schema.Struct({
182
+ type: Schema.Literal("unsupported"),
183
+ ...peerLinkClientPairingTarget,
184
+ reason: Schema.Literals([
185
+ /** The link is below full access, so it may not hand out a client's access. */
186
+ "link_access",
187
+ /** The linked environment runs a version from before this. */
188
+ "version",
189
+ /** The linked environment refused: the beta is off there, or its policy forbids pairing. */
190
+ "refused",
191
+ /** This environment could not reach the linked one; the client still might. */
192
+ "unreachable",
193
+ ]),
194
+ }),
195
+]);
196
+export type PeerLinkClientPairingResult = typeof PeerLinkClientPairingResult.Type;
197
+
198
+/** What a linking environment asks of the linked one, over the link, for one of its clients. */
199
+export const PeerLinkClientPairingRequest = Schema.Struct({
200
+ /** The client's scopes on the linking environment. The credential never carries more. */
201
+ scopes: Schema.Array(AuthEnvironmentScope),
202
+ /** The client's name there, shown in Connections here. */
203
+ clientLabel: TrimmedNonEmptyString,
204
+});
205
+export type PeerLinkClientPairingRequest = typeof PeerLinkClientPairingRequest.Type;
206
+
207
+export const PeerLinkClientPairingCredential = Schema.Struct({
208
+ credential: TrimmedNonEmptyString,
209
+ expiresAt: Schema.DateTimeUtc,
210
+});
211
+export type PeerLinkClientPairingCredential = typeof PeerLinkClientPairingCredential.Type;
212
+
213
/**
214
* The user's answer to an agent asking to link an environment. The pairing
215
* code is used once to link and is never recorded; the thread learns only the
packages/contracts/src/rpc.ts
+10
@@ -18,6 +18,8 @@ import {
18
} from "./mcpApps.ts";
19
import {
20
PeerLink,
21
+ PeerLinkClientPairingInput,
22
+ PeerLinkClientPairingResult,
23
PeerLinkCreateInput,
24
PeerLinkError,
25
PeerLinkName,
@@ -559,6 +561,7 @@ export const WS_METHODS = {
561
peerLinksSubscribeThread: "peerLinks.subscribeThread",
562
peerLinksThreadHistoryPage: "peerLinks.threadHistoryPage",
563
peerLinksThreadItem: "peerLinks.threadItem",
564
+ peerLinksPairClient: "peerLinks.pairClient",
565
serverGetSettings: "server.getSettings",
566
serverUpdateSettings: "server.updateSettings",
567
serverDiscoverSourceControl: "server.discoverSourceControl",
@@ -939,6 +942,12 @@ const WsPeerLinksThreadItemRpc = Rpc.make(WS_METHODS.peerLinksThreadItem, {
942
error: Schema.Union([PeerLinkThreadReadError, EnvironmentAuthorizationError]),
943
});
944
945
+const WsPeerLinksPairClientRpc = Rpc.make(WS_METHODS.peerLinksPairClient, {
946
+ payload: PeerLinkClientPairingInput,
947
+ success: PeerLinkClientPairingResult,
948
+ error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]),
949
+});
950
+
951
const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, {
952
payload: PeerLinkRequestAnswerInput,
953
error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]),
@@ -2346,6 +2355,7 @@ export const WsRpcGroup = RpcGroup.make(
2355
WsPeerLinksSubscribeThreadRpc,
2356
WsPeerLinksThreadHistoryPageRpc,
2357
WsPeerLinksThreadItemRpc,
2358
+ WsPeerLinksPairClientRpc,
2359
WsServerDiscoverSourceControlRpc,
2360
WsServerCheckSecretSourceRpc,
2361
WsServerSearchAcpRegistryRpc,