diff --git a/apps/mobile/src/connection/onboarding.ts b/apps/mobile/src/connection/onboarding.ts
index 54963759ed189..bf10122432349 100644
--- a/apps/mobile/src/connection/onboarding.ts
+++ b/apps/mobile/src/connection/onboarding.ts
@@ -44,3 +44,11 @@ export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime
Effect.flatMap((onboarding) => onboarding.updateBearer(input)),
),
});
+
+export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, {
+ label: "mobile:connection:reaches-environment",
+ execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) =>
+ ConnectionOnboarding.ConnectionOnboarding.pipe(
+ Effect.flatMap((onboarding) => onboarding.reaches(input)),
+ ),
+});
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
index 533c71b54ef35..73e035fe75ece 100644
--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
@@ -30,6 +30,7 @@ import { SymbolView } from "../../components/ui/AppSymbol";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
+import { linkedEnvironmentPrefillAtom } from "./linkedEnvironmentPrefill";
import { splitEnvironmentSections } from "./environmentSections";
import { leaveSettingsPage } from "../settings/settings-navigation";
import { workspaceHasColumns } from "../layout/workspace/workspace-selection-store";
@@ -40,6 +41,8 @@ type ConnectionsNewRouteParams = {
readonly pairingUrl?: string;
readonly autoConnect?: string;
readonly routeFor?: EnvironmentId;
+ /** A linked machine this app chose to pair with; its details come from app state, never the link. */
+ readonly linked?: string;
};
export function ConnectionsNewRouteScreen({
@@ -48,12 +51,15 @@ export function ConnectionsNewRouteScreen({
const params = route.params ?? {};
// Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
+ const known = useAtomValue(linkedEnvironmentPrefillAtom);
+ const linked = known !== null && known.environmentId === params.linked ? known : null;
// A new prefill link replaces whatever the form held.
return (
);
}
@@ -61,9 +67,11 @@ export function ConnectionsNewRouteScreen({
function PairingForm({
routePairingUrl,
routeFor,
+ linked,
}: {
readonly routePairingUrl: string;
readonly routeFor: EnvironmentId | undefined;
+ readonly linked: { readonly label: string; readonly host: string | null } | null;
}) {
const gt = useGT();
const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } =
@@ -71,7 +79,7 @@ function PairingForm({
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl));
- const [hostInput, setHostInput] = useState(initialPairing.host);
+ const [hostInput, setHostInput] = useState(linked?.host ?? initialPairing.host);
const [codeInput, setCodeInput] = useState(initialPairing.code);
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState(null);
@@ -188,7 +196,11 @@ function PairingForm({
return (
{pairingConnectionError ??
- gt(
- "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
- )}
+ (linked
+ ? gt(
+ "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
+ { environment: linked.label },
+ )
+ : gt(
+ "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
+ ))}
diff --git a/apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts b/apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts
new file mode 100644
index 0000000000000..991137c50c2cf
--- /dev/null
+++ b/apps/mobile/src/features/connection/linkedEnvironmentPrefill.ts
@@ -0,0 +1,12 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+
+/**
+ * A linked machine the add-environment screen opens for, with what the environment that links to
+ * it said about it. Set only by this app; a route names the machine and never supplies an address.
+ */
+export const linkedEnvironmentPrefillAtom = Atom.make<{
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly host: string | null;
+} | null>(null).pipe(Atom.withLabel("linked-environment-prefill"));
diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx
index 9cbc930548464..7c9ee3c17e9a7 100644
--- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx
+++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx
@@ -1,4 +1,9 @@
-import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
+import {
+ StackActions,
+ useIsFocused,
+ useNavigation,
+ type StaticScreenProps,
+} from "@react-navigation/native";
import {
isLinkedThreadWorking,
linkedThreadFailure,
@@ -31,11 +36,12 @@ import {
type ThreadFeedActivity,
type ThreadFeedEntry,
} from "../../lib/threadActivity";
-import { useLinkedThreadView } from "../../state/linkedThread";
+import { useConnectLinkedEnvironment, useLinkedThreadView } from "../../state/linkedThread";
import { peerLinkEnvironment } from "../../state/peerLinks";
import { useEnvironmentQuery } from "../../state/query";
import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar";
+import { useOpenLinkedThread } from "./useOpenLinkedThread";
type LinkedThreadRouteParams = {
readonly viaEnvironmentId: string;
@@ -290,6 +296,21 @@ function LinkedThreadView(props: { readonly target: LinkedThreadTarget }) {
// Follows new items only while the reader is already at the end.
const atEnd = useRef(true);
const working = projection !== null && isLinkedThreadWorking(projection);
+ const connection = useConnectLinkedEnvironment(target);
+ const connectState = connection.state;
+ const openThread = useOpenLinkedThread();
+ const connect = async () => {
+ const outcome = await connection.connect();
+ if (outcome.type === "unreachable") return;
+ // This sheet closes either way: the thread opens where the app is now connected, or the
+ // add-environment screen takes its place.
+ if (outcome.type === "connected") {
+ navigation.goBack();
+ openThread({ environmentId: target.environmentId, threadId: target.threadId });
+ return;
+ }
+ navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId }));
+ };
return (
-
+ void connect()}
+ />
+ }
+ notice={
+ connectState.phase === "connecting" ? (
+
+ {gt("Connecting to {environment}...", { environment: label })}
+
+ ) : connectState.phase === "unreachable" ? (
+
+
+ {gt("{label} is not reachable from this device", {
+ label: connectState.label,
+ })}
+
+
+
+ Join a network it is on, such as its Tailscale network, and try again. You can
+ keep reading here.
+
+
+
+ ) : null
+ }
+ />
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 1ca61edb42844..4d04ac029bf64 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "T3 Code auf {host} war zu beschäftigt, um zu antworten.",
"5c5941732d5dfac6": "Die Kopplungsdaten sind ungültig.",
"b8ca23ad7dda376e": "Diese Adresse führt zu {host}, einem anderen Rechner. Füge sie stattdessen als eigene Umgebung hinzu.",
+ "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
"693cb5c4fb40f109": "Nur gespeicherte Bearer-Umgebungen können bearbeitet werden.",
"5f5844b910cb1544": "Die gespeicherten Bearer-Zugangsdaten sind nicht verfügbar.",
"51b0133f1ed3cf5c": "Die Bezeichnung der Umgebung darf nicht leer sein.",
- "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
"3aa15bfbe1920376": "Aktualisiere T3 Code auf {host} manuell; es kann sich nicht selbst aktualisieren.",
"71907f57b7ec64d5": "{host} ist nicht mit einer kompatiblen T3-Code-Version zurückgekommen.",
"e77ac580a4ddcd3b": "Verfügbar",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "Einstellungen öffnen",
"41e3df8a7b6d5d9d": "Ungültiger QR-Code",
"c28525066e29c024": "Der gescannte QR-Code wurde nicht erkannt.",
+ "8a333daf9b7fd03f": "Mit {environment} verbinden",
"53c162d8868a1d0e": "Umgebung hinzufügen",
"403dd9b445331000": "Wird verbunden",
"44bbcfd33b751bd6": "Adresse",
"42fd195574793f9e": "Code",
"51b31345c7bed6f0": "Kopplungscode",
+ "e1cb1c8599e84e26": "Erstelle auf {environment} einen Kopplungscode, in dessen Einstellungen → Freigabe & Zugriff oder mit `t3 auth pairing create`, und gib ihn hier ein.",
"7d6f419f8ab7f779": "Für Rechner in deinem lokalen Netzwerk oder Tailnet. Der Rechner behält seine eigenen Anbieter-Anmeldedaten.",
"36f32bd159bdc0d1": "QR-Code scannen",
"11fd02455d938901": "Scanne den Code von {command} oder aus den Verbindungseinstellungen am Desktop",
@@ -4158,8 +4160,11 @@
"009e2ca841fdc1ef": "diese Umgebung",
"596842e9e887232b": "Wird von {label} gelesen …",
"ff889c17671b40af": "Frühere laden",
+ "d49e5c66faa5d153": "Verbinden, um zu interagieren",
+ "93e690821c726e13": "{label} ist von diesem Gerät aus nicht erreichbar",
"0014ce0aaf1bd68a": "Schreibgeschützt",
"048b8a737af895ac": "Noch nichts in diesem Thread.",
+ "d148218513d9950a": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.",
"1410155e503a917f": "{denial} Wechsle den Modus dieses Threads, um fortzufahren.",
"81ceeceeb521bba6": "Zu {mode} wechseln",
"6ebd73c7bfb58bb7": "App",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index 0c37b2d400c94..ac22e97d21be3 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "T3 Code on {host} was too busy to answer.",
"5c5941732d5dfac6": "The pairing details are invalid.",
"b8ca23ad7dda376e": "That address reaches {host}, a different machine. Add it as its own environment instead.",
+ "0c0150a90b582a7a": "The environment URL is invalid.",
"693cb5c4fb40f109": "Only saved bearer environments can be edited.",
"5f5844b910cb1544": "The saved bearer credential is unavailable.",
"51b0133f1ed3cf5c": "Environment label cannot be empty.",
- "0c0150a90b582a7a": "The environment URL is invalid.",
"3aa15bfbe1920376": "Update T3 Code on {host} manually; it cannot update itself.",
"71907f57b7ec64d5": "{host} did not come back on a compatible T3 Code version.",
"e77ac580a4ddcd3b": "Available",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "Open Settings",
"41e3df8a7b6d5d9d": "Invalid QR code",
"c28525066e29c024": "Scanned QR code was not recognized.",
+ "8a333daf9b7fd03f": "Connect to {environment}",
"53c162d8868a1d0e": "Add environment",
"403dd9b445331000": "Connecting",
"44bbcfd33b751bd6": "Address",
"42fd195574793f9e": "Code",
"51b31345c7bed6f0": "Pairing code",
+ "e1cb1c8599e84e26": "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
"7d6f419f8ab7f779": "For machines on your local network or tailnet. The machine keeps its own provider credentials.",
"36f32bd159bdc0d1": "Scan QR code",
"11fd02455d938901": "Scan the code from {command} or desktop Connections settings",
@@ -4159,8 +4161,11 @@
"009e2ca841fdc1ef": "this environment",
"596842e9e887232b": "Reading from {label}…",
"ff889c17671b40af": "Load earlier",
+ "d49e5c66faa5d153": "Connect to interact",
+ "93e690821c726e13": "{label} is not reachable from this device",
"0014ce0aaf1bd68a": "Read-only",
"048b8a737af895ac": "Nothing in this thread yet.",
+ "d148218513d9950a": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.",
"1410155e503a917f": "{denial} Switch this thread's mode to continue.",
"81ceeceeb521bba6": "Switch to {mode}",
"6ebd73c7bfb58bb7": "App",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index 09e9b73026ad9..046959950b3b0 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "T3 Code en {host} estaba demasiado ocupado para responder.",
"5c5941732d5dfac6": "Los datos de emparejamiento no son válidos.",
"b8ca23ad7dda376e": "Esa dirección lleva a {host}, otra máquina. Añádela como un entorno propio.",
+ "0c0150a90b582a7a": "La URL del entorno no es válida.",
"693cb5c4fb40f109": "Solo se pueden editar los entornos bearer guardados.",
"5f5844b910cb1544": "La credencial bearer guardada no está disponible.",
"51b0133f1ed3cf5c": "La etiqueta del entorno no puede estar vacía.",
- "0c0150a90b582a7a": "La URL del entorno no es válida.",
"3aa15bfbe1920376": "Actualiza T3 Code en {host} manualmente; no puede actualizarse solo.",
"71907f57b7ec64d5": "{host} no volvió con una versión compatible de T3 Code.",
"e77ac580a4ddcd3b": "Disponible",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "Abrir Ajustes",
"41e3df8a7b6d5d9d": "Código QR no válido",
"c28525066e29c024": "No se reconoció el código QR escaneado.",
+ "8a333daf9b7fd03f": "Conectar con {environment}",
"53c162d8868a1d0e": "Añadir entorno",
"403dd9b445331000": "Conectando",
"44bbcfd33b751bd6": "Dirección",
"42fd195574793f9e": "Código",
"51b31345c7bed6f0": "Código de emparejamiento",
+ "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í.",
"7d6f419f8ab7f779": "Para máquinas de tu red local o tailnet. La máquina conserva sus propias credenciales de proveedores.",
"36f32bd159bdc0d1": "Escanear código QR",
"11fd02455d938901": "Escanea el código de {command} o de los ajustes de Conexiones del escritorio",
@@ -4153,8 +4155,11 @@
"009e2ca841fdc1ef": "este entorno",
"596842e9e887232b": "Leyendo desde {label}…",
"ff889c17671b40af": "Cargar anteriores",
+ "d49e5c66faa5d153": "Conectar para interactuar",
+ "93e690821c726e13": "No se puede acceder a {label} desde este dispositivo",
"0014ce0aaf1bd68a": "Solo lectura",
"048b8a737af895ac": "Aún no hay nada en este hilo.",
+ "d148218513d9950a": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.",
"1410155e503a917f": "{denial} Cambia el modo de este hilo para continuar.",
"81ceeceeb521bba6": "Cambiar a {mode}",
"6ebd73c7bfb58bb7": "App",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index 69183070867dd..c156610bd5c09 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "T3 Code sur {host} était trop occupé pour répondre.",
"5c5941732d5dfac6": "Les informations d’appairage ne sont pas valides.",
"b8ca23ad7dda376e": "Cette adresse mène à {host}, une autre machine. Ajoutez-la plutôt comme environnement distinct.",
+ "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
"693cb5c4fb40f109": "Seuls les environnements bearer enregistrés peuvent être modifiés.",
"5f5844b910cb1544": "Les identifiants bearer enregistrés ne sont pas disponibles.",
"51b0133f1ed3cf5c": "Le libellé de l’environnement ne peut pas être vide.",
- "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
"3aa15bfbe1920376": "Mettez à jour T3 Code sur {host} manuellement ; il ne peut pas se mettre à jour seul.",
"71907f57b7ec64d5": "{host} n’est pas revenu sur une version compatible de T3 Code.",
"e77ac580a4ddcd3b": "Disponible",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "Ouvrir les Réglages",
"41e3df8a7b6d5d9d": "Code QR non valide",
"c28525066e29c024": "Le code QR scanné n’a pas été reconnu.",
+ "8a333daf9b7fd03f": "Se connecter à {environment}",
"53c162d8868a1d0e": "Ajouter un environnement",
"403dd9b445331000": "Connexion",
"44bbcfd33b751bd6": "Adresse",
"42fd195574793f9e": "Code",
"51b31345c7bed6f0": "Code d’appairage",
+ "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.",
"7d6f419f8ab7f779": "Pour les machines de votre réseau local ou de votre tailnet. La machine garde ses propres identifiants de fournisseur.",
"36f32bd159bdc0d1": "Scanner un code QR",
"11fd02455d938901": "Scannez le code de {command} ou des paramètres Connexions du bureau",
@@ -4153,8 +4155,11 @@
"009e2ca841fdc1ef": "cet environnement",
"596842e9e887232b": "Lecture depuis {label}…",
"ff889c17671b40af": "Charger les précédents",
+ "d49e5c66faa5d153": "Se connecter pour interagir",
+ "93e690821c726e13": "{label} n’est pas accessible depuis cet appareil",
"0014ce0aaf1bd68a": "Lecture seule",
"048b8a737af895ac": "Rien dans ce fil pour l’instant.",
+ "d148218513d9950a": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.",
"1410155e503a917f": "{denial} Changez le mode de ce fil pour continuer.",
"81ceeceeb521bba6": "Passer en {mode}",
"6ebd73c7bfb58bb7": "App",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index fd55b3e454fa2..019032f1eee88 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "{host} の T3 Code はビジー状態で応答できませんでした。",
"5c5941732d5dfac6": "ペアリングの詳細が無効です。",
"b8ca23ad7dda376e": "そのアドレスは別のマシンである {host} につながります。代わりに独立した環境として追加してください。",
+ "0c0150a90b582a7a": "環境の URL が無効です。",
"693cb5c4fb40f109": "編集できるのは保存済みのベアラー環境のみです。",
"5f5844b910cb1544": "保存済みのベアラー資格情報は利用できません。",
"51b0133f1ed3cf5c": "環境のラベルは空にできません。",
- "0c0150a90b582a7a": "環境の URL が無効です。",
"3aa15bfbe1920376": "{host} の T3 Code は自動で更新できないため、手動で更新してください。",
"71907f57b7ec64d5": "{host} は互換性のある T3 Code のバージョンで復帰しませんでした。",
"e77ac580a4ddcd3b": "利用可能",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "設定を開く",
"41e3df8a7b6d5d9d": "無効な QR コード",
"c28525066e29c024": "スキャンした QR コードを認識できませんでした。",
+ "8a333daf9b7fd03f": "{environment} に接続",
"53c162d8868a1d0e": "環境を追加",
"403dd9b445331000": "接続中",
"44bbcfd33b751bd6": "アドレス",
"42fd195574793f9e": "コード",
"51b31345c7bed6f0": "ペアリングコード",
+ "e1cb1c8599e84e26": "{environment} の設定 → 共有とアクセス、または `t3 auth pairing create` でペアリングコードを作成し、ここに入力してください。",
"7d6f419f8ab7f779": "ローカルネットワークや tailnet 上のマシン向けです。マシンはプロバイダーの認証情報を自身で保持します。",
"36f32bd159bdc0d1": "QR コードをスキャン",
"11fd02455d938901": "{command} またはデスクトップの接続設定に表示されるコードをスキャンしてください",
@@ -4149,8 +4151,11 @@
"009e2ca841fdc1ef": "この環境",
"596842e9e887232b": "{label} から読み取り中…",
"ff889c17671b40af": "以前のものを読み込む",
+ "d49e5c66faa5d153": "接続して操作する",
+ "93e690821c726e13": "このデバイスから {label} に接続できません",
"0014ce0aaf1bd68a": "読み取り専用",
"048b8a737af895ac": "このスレッドにはまだ何もありません。",
+ "d148218513d9950a": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。",
"1410155e503a917f": "{denial} 続行するには、このスレッドのモードを切り替えてください。",
"81ceeceeb521bba6": "{mode} に切り替え",
"6ebd73c7bfb58bb7": "アプリ",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index 0489c6184e35e..de7e21280597f 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "{host}의 T3 Code가 너무 바빠서 응답하지 못했습니다.",
"5c5941732d5dfac6": "페어링 정보가 올바르지 않습니다.",
"b8ca23ad7dda376e": "이 주소는 다른 머신인 {host}에 연결됩니다. 대신 별도의 환경으로 추가하세요.",
+ "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
"693cb5c4fb40f109": "저장된 bearer 환경만 편집할 수 있습니다.",
"5f5844b910cb1544": "저장된 bearer 자격 증명을 사용할 수 없습니다.",
"51b0133f1ed3cf5c": "환경 레이블은 비워 둘 수 없습니다.",
- "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
"3aa15bfbe1920376": "{host}의 T3 Code는 스스로 업데이트할 수 없으니 직접 업데이트하세요.",
"71907f57b7ec64d5": "{host}이(가) 호환되는 T3 Code 버전으로 돌아오지 않았습니다.",
"e77ac580a4ddcd3b": "사용 가능",
@@ -1970,11 +1970,13 @@
"28ae2c5e144a8c02": "설정 열기",
"41e3df8a7b6d5d9d": "잘못된 QR 코드",
"c28525066e29c024": "스캔한 QR 코드를 인식할 수 없습니다.",
+ "8a333daf9b7fd03f": "{environment}에 연결",
"53c162d8868a1d0e": "환경 추가",
"403dd9b445331000": "연결 중",
"44bbcfd33b751bd6": "주소",
"42fd195574793f9e": "코드",
"51b31345c7bed6f0": "페어링 코드",
+ "e1cb1c8599e84e26": "{environment}의 설정 → 공유 및 액세스에서 또는 `t3 auth pairing create`로 페어링 코드를 만든 다음 여기에 입력하세요.",
"7d6f419f8ab7f779": "로컬 네트워크나 tailnet에 있는 머신용입니다. 머신은 자체 제공자 자격 증명을 유지합니다.",
"36f32bd159bdc0d1": "QR 코드 스캔",
"11fd02455d938901": "{command} 또는 데스크톱 연결 설정의 코드를 스캔하세요",
@@ -4153,8 +4155,11 @@
"009e2ca841fdc1ef": "이 환경",
"596842e9e887232b": "{label}에서 읽는 중…",
"ff889c17671b40af": "이전 항목 불러오기",
+ "d49e5c66faa5d153": "연결하여 상호작용",
+ "93e690821c726e13": "이 기기에서 {label}에 연결할 수 없습니다",
"0014ce0aaf1bd68a": "읽기 전용",
"048b8a737af895ac": "이 스레드에는 아직 아무것도 없습니다.",
+ "d148218513d9950a": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.",
"1410155e503a917f": "{denial} 계속하려면 이 스레드의 모드를 전환하세요.",
"81ceeceeb521bba6": "{mode}(으)로 전환",
"6ebd73c7bfb58bb7": "앱",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 03d50749e39cd..46a70448abf80 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "O T3 Code em {host} estava ocupado demais para responder.",
"5c5941732d5dfac6": "Os detalhes de pareamento são inválidos.",
"b8ca23ad7dda376e": "Esse endereço leva a {host}, outra máquina. Adicione-a como um ambiente próprio.",
+ "0c0150a90b582a7a": "A URL do ambiente é inválida.",
"693cb5c4fb40f109": "Só é possível editar ambientes bearer salvos.",
"5f5844b910cb1544": "A credencial bearer salva não está disponível.",
"51b0133f1ed3cf5c": "O rótulo do ambiente não pode ficar vazio.",
- "0c0150a90b582a7a": "A URL do ambiente é inválida.",
"3aa15bfbe1920376": "Atualize o T3 Code em {host} manualmente; ele não consegue se atualizar sozinho.",
"71907f57b7ec64d5": "{host} não voltou em uma versão compatível do T3 Code.",
"e77ac580a4ddcd3b": "Disponível",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "Abrir Ajustes",
"41e3df8a7b6d5d9d": "QR code inválido",
"c28525066e29c024": "O QR code escaneado não foi reconhecido.",
+ "8a333daf9b7fd03f": "Conectar a {environment}",
"53c162d8868a1d0e": "Adicionar ambiente",
"403dd9b445331000": "Conectando",
"44bbcfd33b751bd6": "Endereço",
"42fd195574793f9e": "Código",
"51b31345c7bed6f0": "Código de pareamento",
+ "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.",
"7d6f419f8ab7f779": "Para máquinas na sua rede local ou tailnet. A máquina mantém as próprias credenciais dos provedores.",
"36f32bd159bdc0d1": "Escanear QR code",
"11fd02455d938901": "Escaneie o código de {command} ou das configurações de Conexões do desktop",
@@ -4153,8 +4155,11 @@
"009e2ca841fdc1ef": "este ambiente",
"596842e9e887232b": "Lendo de {label}…",
"ff889c17671b40af": "Carregar anteriores",
+ "d49e5c66faa5d153": "Conectar para interagir",
+ "93e690821c726e13": "{label} não está acessível a partir deste dispositivo",
"0014ce0aaf1bd68a": "Somente leitura",
"048b8a737af895ac": "Ainda não há nada nesta thread.",
+ "d148218513d9950a": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.",
"1410155e503a917f": "{denial} Mude o modo desta thread para continuar.",
"81ceeceeb521bba6": "Mudar para {mode}",
"6ebd73c7bfb58bb7": "App",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index b5700f2a091af..0632e3bf3d673 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "T3 Code на {host} был слишком занят, чтобы ответить.",
"5c5941732d5dfac6": "Данные сопряжения недействительны.",
"b8ca23ad7dda376e": "Этот адрес ведёт к {host}, другому компьютеру. Добавьте его как отдельное окружение.",
+ "0c0150a90b582a7a": "URL окружения недействителен.",
"693cb5c4fb40f109": "Изменять можно только сохранённые окружения с bearer-токеном.",
"5f5844b910cb1544": "Сохранённые bearer-учётные данные недоступны.",
"51b0133f1ed3cf5c": "Название окружения не может быть пустым.",
- "0c0150a90b582a7a": "URL окружения недействителен.",
"3aa15bfbe1920376": "Обновите T3 Code на {host} вручную: он не может обновиться сам.",
"71907f57b7ec64d5": "{host} не вернулся с совместимой версией T3 Code.",
"e77ac580a4ddcd3b": "Доступно",
@@ -1993,11 +1993,13 @@
"28ae2c5e144a8c02": "Открыть настройки",
"41e3df8a7b6d5d9d": "Недействительный QR-код",
"c28525066e29c024": "Отсканированный QR-код не распознан.",
+ "8a333daf9b7fd03f": "Подключиться к {environment}",
"53c162d8868a1d0e": "Добавить окружение",
"403dd9b445331000": "Подключение",
"44bbcfd33b751bd6": "Адрес",
"42fd195574793f9e": "Код",
"51b31345c7bed6f0": "Код сопряжения",
+ "e1cb1c8599e84e26": "Создайте код сопряжения на {environment} в разделе «Настройки → Общий доступ» или командой `t3 auth pairing create` и введите его здесь.",
"7d6f419f8ab7f779": "Для машин в вашей локальной сети или tailnet. Машина хранит собственные учётные данные провайдеров.",
"36f32bd159bdc0d1": "Сканировать QR-код",
"11fd02455d938901": "Отсканируйте код из {command} или из настроек подключений в десктопном приложении",
@@ -4207,8 +4209,11 @@
"009e2ca841fdc1ef": "это окружение",
"596842e9e887232b": "Чтение с {label}…",
"ff889c17671b40af": "Загрузить более ранние",
+ "d49e5c66faa5d153": "Подключиться для взаимодействия",
+ "93e690821c726e13": "{label} недоступно с этого устройства",
"0014ce0aaf1bd68a": "Только чтение",
"048b8a737af895ac": "В этом треде пока ничего нет.",
+ "d148218513d9950a": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.",
"1410155e503a917f": "{denial} Чтобы продолжить, переключите режим этого треда.",
"81ceeceeb521bba6": "Переключиться на {mode}",
"6ebd73c7bfb58bb7": "Приложение",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index 387410edf127e..7d613fb7b3c9b 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "T3 Code på {host} var för upptagen för att svara.",
"5c5941732d5dfac6": "Uppgifterna för parkopplingen är ogiltiga.",
"b8ca23ad7dda376e": "Den adressen leder till {host}, en annan dator. Lägg till den som en egen miljö i stället.",
+ "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
"693cb5c4fb40f109": "Bara sparade bearer-miljöer kan redigeras.",
"5f5844b910cb1544": "Den sparade bearer-uppgiften är inte tillgänglig.",
"51b0133f1ed3cf5c": "Miljöns etikett får inte vara tom.",
- "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
"3aa15bfbe1920376": "Uppdatera T3 Code på {host} manuellt; det kan inte uppdatera sig självt.",
"71907f57b7ec64d5": "{host} kom inte tillbaka med en kompatibel version av T3 Code.",
"e77ac580a4ddcd3b": "Tillgänglig",
@@ -1969,11 +1969,13 @@
"28ae2c5e144a8c02": "Öppna Inställningar",
"41e3df8a7b6d5d9d": "Ogiltig QR-kod",
"c28525066e29c024": "Den skannade QR-koden kändes inte igen.",
+ "8a333daf9b7fd03f": "Anslut till {environment}",
"53c162d8868a1d0e": "Lägg till miljö",
"403dd9b445331000": "Ansluter",
"44bbcfd33b751bd6": "Adress",
"42fd195574793f9e": "Kod",
"51b31345c7bed6f0": "Parkopplingskod",
+ "e1cb1c8599e84e26": "Skapa en parkopplingskod på {environment}, i dess Inställningar → Delning och åtkomst eller med `t3 auth pairing create`, och ange den här.",
"7d6f419f8ab7f779": "För datorer i ditt lokala nätverk eller tailnet. Datorn behåller sina egna leverantörsuppgifter.",
"36f32bd159bdc0d1": "Skanna QR-kod",
"11fd02455d938901": "Skanna koden från {command} eller inställningen Anslutningar på skrivbordet",
@@ -4159,8 +4161,11 @@
"009e2ca841fdc1ef": "den här miljön",
"596842e9e887232b": "Läser från {label}…",
"ff889c17671b40af": "Läs in tidigare",
+ "d49e5c66faa5d153": "Anslut för att interagera",
+ "93e690821c726e13": "{label} kan inte nås från den här enheten",
"0014ce0aaf1bd68a": "Skrivskyddad",
"048b8a737af895ac": "Inget i den här tråden ännu.",
+ "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.",
"1410155e503a917f": "{denial} Byt trådens läge för att fortsätta.",
"81ceeceeb521bba6": "Byt till {mode}",
"6ebd73c7bfb58bb7": "App",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index c526a2f9eb1e3..b560f0af3fbf0 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -457,10 +457,10 @@
"93e37fedae7eaa5b": "{host} 上的 T3 Code 太忙,未能响应。",
"5c5941732d5dfac6": "配对信息无效。",
"b8ca23ad7dda376e": "该地址指向另一台机器 {host}。请将其添加为独立环境。",
+ "0c0150a90b582a7a": "环境 URL 无效。",
"693cb5c4fb40f109": "只能编辑已保存的 bearer 环境。",
"5f5844b910cb1544": "已保存的 bearer 凭据不可用。",
"51b0133f1ed3cf5c": "环境名称不能为空。",
- "0c0150a90b582a7a": "环境 URL 无效。",
"3aa15bfbe1920376": "请手动更新 {host} 上的 T3 Code;它无法自行更新。",
"71907f57b7ec64d5": "{host} 重启后未运行兼容的 T3 Code 版本。",
"e77ac580a4ddcd3b": "可用",
@@ -1971,11 +1971,13 @@
"28ae2c5e144a8c02": "打开设置",
"41e3df8a7b6d5d9d": "二维码无效",
"c28525066e29c024": "无法识别扫描的二维码。",
+ "8a333daf9b7fd03f": "连接到 {environment}",
"53c162d8868a1d0e": "添加环境",
"403dd9b445331000": "正在连接",
"44bbcfd33b751bd6": "地址",
"42fd195574793f9e": "配对码",
"51b31345c7bed6f0": "配对码",
+ "e1cb1c8599e84e26": "在 {environment} 的设置 → 共享与访问中或使用 `t3 auth pairing create` 创建配对码,然后在此输入。",
"7d6f419f8ab7f779": "适用于本地网络或 tailnet 中的机器。该机器保留自己的提供方凭据。",
"36f32bd159bdc0d1": "扫描二维码",
"11fd02455d938901": "扫描 {command} 或桌面端“连接”设置中的二维码",
@@ -4156,8 +4158,11 @@
"009e2ca841fdc1ef": "此环境",
"596842e9e887232b": "正在从 {label} 读取…",
"ff889c17671b40af": "加载更早的内容",
+ "d49e5c66faa5d153": "连接以进行交互",
+ "93e690821c726e13": "无法从此设备访问 {label}",
"0014ce0aaf1bd68a": "只读",
"048b8a737af895ac": "此会话中还没有内容。",
+ "d148218513d9950a": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。",
"1410155e503a917f": "{denial} 切换此会话的模式以继续。",
"81ceeceeb521bba6": "切换到 {mode}",
"6ebd73c7bfb58bb7": "应用",
diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts
index fd685650c903c..ff4c75b9ac1ac 100644
--- a/apps/mobile/src/state/linkedThread.ts
+++ b/apps/mobile/src/state/linkedThread.ts
@@ -1,10 +1,18 @@
-import { useAtomValue } from "@effect/atom-react";
-import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread";
+import { useAtomSet, useAtomValue } from "@effect/atom-react";
+import {
+ connectLinkedEnvironment,
+ type LinkedThreadTarget,
+} from "@t3tools/client-runtime/linked-thread";
import type { EnvironmentId, OrchestrationV2Subagent } from "@t3tools/contracts";
+import { useState } from "react";
+import { connectPairingUrl, reachesEnvironment } from "../connection/onboarding";
+import { linkedEnvironmentPrefillAtom } from "../features/connection/linkedEnvironmentPrefill";
+import { buildPairingUrl } from "../features/connection/pairing";
import { useEnvironments } from "./environments";
import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
import { useEnvironmentQuery } from "./query";
+import { useAtomCommand } from "./use-atom-command";
/**
* What places a delegated task's thread: this app's own connections, and the links `environmentId`
@@ -32,6 +40,63 @@ export function useLinkedThreadReach(
return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) };
}
+export type LinkedEnvironmentConnectState =
+ | { readonly phase: "idle" | "connecting" }
+ | { readonly phase: "unreachable"; readonly label: string };
+
+/**
+ * Connects this app to the environment `target` lives in. One step when the linking environment
+ * can get a pairing for this app; otherwise the caller opens the add-environment screen, which
+ * reads what was learned about the machine.
+ */
+export function useConnectLinkedEnvironment(target: LinkedThreadTarget) {
+ const setPrefill = useAtomSet(linkedEnvironmentPrefillAtom);
+ const mayPair = useAtomValue(
+ peerLinkEnvironment.pairClient.permissionAtom(target.viaEnvironmentId),
+ );
+ const quiet = { reportFailure: false, reportDefect: false } as const;
+ const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
+ const reaches = useAtomCommand(reachesEnvironment, quiet);
+ const pair = useAtomCommand(connectPairingUrl, quiet);
+ const [state, setState] = useState({ phase: "idle" });
+ const connect = async () => {
+ setState({ phase: "connecting" });
+ const outcome = await connectLinkedEnvironment({
+ label: target.label,
+ requestPairing: async () => {
+ // Without it the linking environment refuses; the user can still pair by hand.
+ if (!mayPair) return null;
+ const result = await requestPairing({
+ environmentId: target.viaEnvironmentId,
+ input: { environmentId: target.environmentId },
+ });
+ return result._tag === "Success" ? result.value : null;
+ },
+ reaches: async (host) => {
+ const result = await reaches({ host, environmentId: target.environmentId });
+ return result._tag === "Success" && result.value;
+ },
+ pair: async ({ host, pairingCode }) => {
+ const result = await pair({
+ pairingUrl: buildPairingUrl(host, pairingCode),
+ expectedEnvironmentId: target.environmentId,
+ });
+ return result._tag === "Success";
+ },
+ });
+ setState(
+ outcome.type === "unreachable"
+ ? { phase: "unreachable", label: outcome.label }
+ : { phase: "idle" },
+ );
+ if (outcome.type === "manual") {
+ setPrefill({ environmentId: target.environmentId, label: outcome.label, host: outcome.host });
+ }
+ return outcome;
+ };
+ return { state, connect };
+}
+
/**
* The thread of `target`, streamed through the environment that links to it. The stream runs only
* while `active`; what it last showed stays, so coming back to the screen shows it at once.
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts
index aee5dd3fae815..200a049e0118b 100644
--- a/apps/server/src/auth/RpcAuthorization.test.ts
+++ b/apps/server/src/auth/RpcAuthorization.test.ts
@@ -288,6 +288,59 @@ it.effect("reads a linked environment's thread only for a client that may read t
}).pipe(Effect.scoped),
);
+it.effect("pairs a client with a linked environment only for one that may hand out access", () =>
+ Effect.gen(function* () {
+ const group = WsRpcGroup.omit(
+ ...[...WsRpcGroup.requests.keys()].filter(
+ (
+ tag,
+ ): tag is Exclude<
+ keyof typeof RPC_REQUIRED_SCOPES,
+ typeof WS_METHODS.peerLinksPairClient
+ > => tag !== WS_METHODS.peerLinksPairClient,
+ ),
+ );
+ let asked = 0;
+ const environmentId = EnvironmentId.make("environment-box");
+ const handlers = group.toLayerHandler(WS_METHODS.peerLinksPairClient, () =>
+ Effect.sync(() => {
+ asked++;
+ return {
+ type: "unsupported" as const,
+ reason: "link_access" as const,
+ environmentId,
+ label: "Box",
+ urls: [],
+ };
+ }),
+ );
+ // Running agents and reading the access list do not include handing access out.
+ const operator = yield* RpcTest.makeClient(group).pipe(
+ Effect.provide(
+ Layer.merge(
+ handlers,
+ RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
+ ),
+ ),
+ );
+ expect(
+ yield* operator[WS_METHODS.peerLinksPairClient]({ environmentId }).pipe(Effect.flip),
+ ).toMatchObject({
+ _tag: "EnvironmentAuthorizationError",
+ requiredPermission: AuthAccessWriteScope,
+ });
+ expect(asked).toBe(0);
+
+ const manager = yield* RpcTest.makeClient(group).pipe(
+ Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthAccessWriteScope]))),
+ );
+ expect((yield* manager[WS_METHODS.peerLinksPairClient]({ environmentId })).type).toBe(
+ "unsupported",
+ );
+ expect(asked).toBe(1);
+ }).pipe(Effect.scoped),
+);
+
it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
"enforces read permission on stream %s",
(method) =>
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 5c1e54b8ab75a..2208e70b983e3 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -298,6 +298,7 @@ export const make = Effect.gen(function* () {
mcpModeLimitHeader: true,
linkFence: true,
linkThreadStream: true,
+ linkClientPairing: true,
mcpApprovalCodes: true,
peerLinkPairingCodes: true,
mcpHostedApproval: true,
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 651ca4070a8e9..96351b39b6315 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -73,6 +73,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.peerLinksSubscribeThread]: "peerLinks",
[WS_METHODS.peerLinksThreadHistoryPage]: "peerLinks",
[WS_METHODS.peerLinksThreadItem]: "peerLinks",
+ [WS_METHODS.peerLinksPairClient]: "peerLinks",
[WS_METHODS.serverGetSettings]: "server",
[WS_METHODS.serverUpdateSettings]: "server",
[WS_METHODS.serverSearchAcpRegistry]: "server",
diff --git a/apps/server/src/peer/PeerClientPairing.test.ts b/apps/server/src/peer/PeerClientPairing.test.ts
new file mode 100644
index 0000000000000..a9bd0f63454d7
--- /dev/null
+++ b/apps/server/src/peer/PeerClientPairing.test.ts
@@ -0,0 +1,275 @@
+import { NodeHttpServer } from "@effect/platform-node";
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import {
+ AuthAccessWriteScope,
+ type AuthEnvironmentScope,
+ type AuthMcpClientAccess,
+ AuthOrchestrationOperateScope,
+ AuthOrchestrationReadScope,
+ AuthRelayConfigureScope,
+ AuthStandardClientScopes,
+ AuthTerminalOperateScope,
+ type ExecutionEnvironmentDescriptor,
+ ProviderInstanceId,
+ ThreadId,
+} from "@t3tools/contracts";
+import { expect, it } from "@effect/vitest";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Ref from "effect/Ref";
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
+import * as HttpBody from "effect/http/HttpBody";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as TestClock from "effect/testing/TestClock";
+import { Toolkit } from "effect/ai";
+
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
+import * as McpHttpServer from "../mcp/McpHttpServer.ts";
+import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
+import * as McpToolAccess from "../mcp/McpToolAccess.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as PeerClientPairing from "./PeerClientPairing.ts";
+import * as PeerLinks from "./PeerLinks.ts";
+import {
+ descriptorOf,
+ layerEnvironmentAuth,
+ layerLinkingEnvironment,
+ linkTo,
+ type ServedPeer,
+ servePeer,
+} from "./PeerLinks.testkit.ts";
+
+const laptop = descriptorOf("environment-laptop", "Laptop");
+const box = descriptorOf("environment-box", "Box", { linkClientPairing: true });
+const NoTools = Toolkit.make();
+
+const serveBox = (descriptor: ExecutionEnvironmentDescriptor = box) =>
+ servePeer(
+ descriptor,
+ McpHttpServer.toolkitRegistration(NoTools, McpToolAccess.toLayer(NoTools, {})),
+ );
+
+/** The laptop: its links, its own clients, and what answers a client asking to pair with a link. */
+const makeLaptop = Effect.gen(function* () {
+ const linking = yield* Layer.build(layerLinkingEnvironment(laptop));
+ const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-here-auth-"));
+ const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
+ const pairing = yield* PeerClientPairing.layer.pipe(
+ Layer.provide(Layer.succeedContext(linking)),
+ Layer.provide(Layer.succeed(EnvironmentAuth.EnvironmentAuth, auth)),
+ Layer.provide(FetchHttpClient.layer),
+ Layer.build,
+ );
+ return {
+ links: Context.get(linking, PeerLinks.PeerLinks),
+ settings: Context.get(linking, ServerSettings.ServerSettingsService),
+ pairing: Context.get(pairing, PeerClientPairing.PeerClientPairing),
+ /** A client paired with the laptop, such as a phone. */
+ client: (scopes: ReadonlyArray) =>
+ auth.issueSession({ scopes, label: "Phone" }),
+ };
+});
+
+const metadata = { deviceType: "mobile" as const };
+
+/** Asks the box's route directly, as anything holding `bearer` could, and answers its status. */
+const askBox = (b: ServedPeer, bearer: string | undefined, headers: Record = {}) =>
+ HttpClient.execute(
+ HttpClientRequest.post(`${b.url}/api/peer-link/client-pairing`).pipe(
+ HttpClientRequest.setHeaders({
+ ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }),
+ ...headers,
+ }),
+ HttpClientRequest.setBody(
+ HttpBody.text(
+ JSON.stringify({ scopes: AuthStandardClientScopes, clientLabel: "Phone" }),
+ "application/json",
+ ),
+ ),
+ ),
+ ).pipe(
+ Effect.map((response) => response.status),
+ Effect.provide(FetchHttpClient.layer),
+ );
+
+const linkTokenOf = (a: Effect.Success) =>
+ a.links.resolve(box.environmentId).pipe(Effect.map((resolved) => resolved.token));
+
+it.effect(
+ "a full-access link gets a client one pairing, with no more than the client holds here",
+ () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveBox();
+ const a = yield* makeLaptop;
+ yield* linkTo(a.links, b, "full-access");
+ // Holds less than a pairing code grants, and one scope no pairing code grants.
+ const held = [
+ AuthOrchestrationReadScope,
+ AuthOrchestrationOperateScope,
+ AuthAccessWriteScope,
+ AuthRelayConfigureScope,
+ ];
+ const phone = yield* a.client(held);
+
+ const result = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
+ if (result.type !== "credential") return yield* Effect.die(result);
+ expect(result).toMatchObject({
+ environmentId: box.environmentId,
+ label: "Box",
+ urls: [b.url],
+ });
+ // The box's Connections says where the pairing came from, and can revoke it.
+ expect(yield* b.auth.listPairingLinks()).toMatchObject([{ label: "Phone · via Laptop" }]);
+
+ const session = yield* b.auth.exchangeBootstrapCredentialForAccessToken(
+ result.credential,
+ undefined,
+ metadata,
+ );
+ expect(new Set(session.scope.split(" "))).toEqual(
+ new Set([
+ AuthOrchestrationReadScope,
+ AuthOrchestrationOperateScope,
+ AuthAccessWriteScope,
+ ]),
+ );
+ expect(session.scope).not.toContain(AuthTerminalOperateScope);
+ const again = yield* b.auth
+ .exchangeBootstrapCredentialForAccessToken(result.credential, undefined, metadata)
+ .pipe(Effect.flip);
+ expect(again._tag).toBe("ServerAuthInvalidCredentialError");
+
+ // One the client never redeems is gone within minutes.
+ const unused = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
+ if (unused.type !== "credential") return yield* Effect.die(unused);
+ yield* TestClock.adjust("3 minutes");
+ const late = yield* b.auth
+ .exchangeBootstrapCredentialForAccessToken(unused.credential, undefined, metadata)
+ .pipe(Effect.flip);
+ expect(late._tag).toBe("ServerAuthInvalidCredentialError");
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
+
+it.effect.each(["read-only", "approval-required", "auto"] as const)(
+ "a %s link cannot pair a client, even when the linking environment is bypassed",
+ (access: AuthMcpClientAccess) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveBox();
+ const a = yield* makeLaptop;
+ yield* linkTo(a.links, b, access);
+ const phone = yield* a.client(AuthStandardClientScopes);
+
+ expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
+ type: "unsupported",
+ reason: "link_access",
+ environmentId: box.environmentId,
+ label: "Box",
+ urls: [b.url],
+ });
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
+
+ expect(yield* askBox(b, yield* linkTokenOf(a))).toBe(403);
+ expect(yield* b.auth.listPairingLinks()).toEqual([]);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
+
+it.effect("only a full-access link's own session reaches the box's pairing route", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveBox();
+ const a = yield* makeLaptop;
+ yield* linkTo(a.links, b, "full-access");
+ const linkToken = yield* linkTokenOf(a);
+
+ // An outside agent approved at full access is not a link.
+ const agent = yield* b.auth.issueMcpClientSession({
+ label: "Outside agent",
+ access: "full-access",
+ peerLink: false,
+ client: { deviceType: "bot" },
+ });
+ expect(yield* askBox(b, agent.token)).toBe(403);
+
+ // An agent's thread credential, which a link-started agent holds too, is not a session.
+ const registry = yield* McpSessionRegistry.layer.pipe(
+ Layer.provide(
+ Layer.succeed(ServerEnvironment.ServerEnvironment, {
+ getEnvironmentId: Effect.succeed(box.environmentId),
+ getDescriptor: Effect.succeed(box),
+ }),
+ ),
+ Layer.provide(NodeCrypto.layer),
+ Layer.build,
+ );
+ const thread = yield* Context.get(registry, McpSessionRegistry.McpSessionRegistry).issue({
+ threadId: ThreadId.make("thread:box-link-started"),
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ });
+ expect(yield* askBox(b, thread.config.authorizationHeader.slice("Bearer ".length))).toBe(401);
+
+ // The box's own administrator client pairs devices from Connections, not from here.
+ const owner = yield* b.auth.issueSession({ scopes: AuthStandardClientScopes });
+ expect(yield* askBox(b, owner.token)).toBe(401);
+ expect(yield* askBox(b, undefined)).toBe(401);
+ // A page in a browser never holds a link's token.
+ expect(yield* askBox(b, linkToken, { origin: "https://example.com" })).toBe(403);
+ expect(yield* b.auth.listPairingLinks()).toEqual([]);
+
+ expect(yield* askBox(b, linkToken)).toBe(200);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
+
+it.effect("pairs no client while Linked environments is off on either side", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveBox();
+ const a = yield* makeLaptop;
+ yield* linkTo(a.links, b, "full-access");
+ const phone = yield* a.client(AuthStandardClientScopes);
+ const linkToken = yield* linkTokenOf(a);
+
+ yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
+ expect(yield* askBox(b, linkToken)).toBe(403);
+ expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toMatchObject({
+ type: "unsupported",
+ reason: "refused",
+ });
+ yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
+
+ yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
+ const off = yield* a.pairing
+ .request({ environmentId: box.environmentId }, phone)
+ .pipe(Effect.flip);
+ expect(off.reason).toBe("disabled");
+ expect(yield* b.auth.listPairingLinks()).toEqual([]);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
+
+it.effect("a linked environment from before client pairing is never asked", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveBox(descriptorOf("environment-box", "Box"));
+ const a = yield* makeLaptop;
+ yield* linkTo(a.links, b, "full-access");
+ const phone = yield* a.client(AuthStandardClientScopes);
+
+ expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
+ type: "unsupported",
+ reason: "version",
+ environmentId: box.environmentId,
+ label: "Box",
+ urls: [b.url],
+ });
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
diff --git a/apps/server/src/peer/PeerClientPairing.ts b/apps/server/src/peer/PeerClientPairing.ts
new file mode 100644
index 0000000000000..045b369cfe2f4
--- /dev/null
+++ b/apps/server/src/peer/PeerClientPairing.ts
@@ -0,0 +1,231 @@
+import {
+ type AuthEnvironmentScope,
+ type AuthSessionId,
+ AuthStandardClientScopes,
+ EnvironmentHttpApi,
+ type PeerLinkClientPairingCredential,
+ type PeerLinkClientPairingInput,
+ type PeerLinkClientPairingRequest,
+ type PeerLinkClientPairingResult,
+ PeerLinkError,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as DateTime from "effect/DateTime";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpApi from "effect/http-api/HttpApi";
+import * as HttpApiClient from "effect/http-api/HttpApiClient";
+
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as PeerLinks from "./PeerLinks.ts";
+
+/** Long enough for the client to reach the linked environment and redeem it, and no longer. */
+const CLIENT_PAIRING_TTL = Duration.minutes(3);
+const CLIENT_LABEL_MAX_LENGTH = 80;
+
+const ClientPairingApi = HttpApi.make(EnvironmentHttpApi.identifier)
+ .add(EnvironmentHttpApi.groups.peerLink)
+ .annotateMerge(EnvironmentHttpApi.annotations);
+
+/** Why the linked environment will not mint a client pairing for this caller. */
+export class PeerClientPairingRefused extends Schema.TaggedError()(
+ "PeerClientPairingRefused",
+ {
+ reason: Schema.Literals(["disabled", "not_a_full_access_link", "no_scopes", "policy"]),
+ message: Schema.String,
+ },
+) {}
+
+/**
+ * The linked side: mints a one-time pairing credential for a client of the environment that
+ * links here, when that environment asks over its link.
+ */
+export class PeerClientPairingIssuer extends Context.Service<
+ PeerClientPairingIssuer,
+ {
+ readonly issue: (
+ caller: EnvironmentAuth.McpClientSession,
+ request: PeerLinkClientPairingRequest,
+ ) => Effect.Effect<
+ PeerLinkClientPairingCredential,
+ PeerClientPairingRefused | EnvironmentAuth.ServerAuthInternalError
+ >;
+ }
+>()("t3/peer/PeerClientPairing/PeerClientPairingIssuer") {}
+
+/**
+ * The linking side: gets a client of this environment a pairing credential for an environment
+ * this one links to, so the client can connect there itself.
+ */
+export class PeerClientPairing extends Context.Service<
+ PeerClientPairing,
+ {
+ readonly request: (
+ input: PeerLinkClientPairingInput,
+ client: {
+ readonly sessionId: AuthSessionId;
+ readonly scopes: ReadonlyArray;
+ },
+ ) => Effect.Effect;
+ }
+>()("t3/peer/PeerClientPairing") {}
+
+const makeIssuer = Effect.gen(function* () {
+ const auth = yield* EnvironmentAuth.EnvironmentAuth;
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
+ const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
+ const enabled = serverSettings.getSettings.pipe(
+ Effect.map((settings) => settings.linkedEnvironmentsEnabled),
+ Effect.orElseSucceed(() => false),
+ );
+
+ const issue: PeerClientPairingIssuer["Service"]["issue"] = Effect.fn(
+ "PeerClientPairingIssuer.issue",
+ )(function* (caller, request) {
+ if (!(yield* enabled)) {
+ return yield* new PeerClientPairingRefused({
+ reason: "disabled",
+ message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
+ });
+ }
+ // A full-access link's agents already run as this machine's user and could run
+ // `t3 auth pairing create` themselves, so minting here adds no power. Any lower link would
+ // gain more than it holds, and so would one an administrator's ceiling holds below full access.
+ if (
+ !caller.peerLink ||
+ caller.access !== "full-access" ||
+ (maxRuntimeMode !== undefined && maxRuntimeMode !== "full-access")
+ ) {
+ return yield* new PeerClientPairingRefused({
+ reason: "not_a_full_access_link",
+ message: "Only a full-access link may pair a client here.",
+ });
+ }
+ // Never more than the client holds where it asked, nor more than a pairing code grants.
+ const scopes = AuthStandardClientScopes.filter((scope) => request.scopes.includes(scope));
+ if (scopes.length === 0) {
+ return yield* new PeerClientPairingRefused({
+ reason: "no_scopes",
+ message: "The client holds no access a pairing could carry.",
+ });
+ }
+ const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX)
+ ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length)
+ : caller.label;
+ const clientLabel = Array.from(request.clientLabel).slice(0, CLIENT_LABEL_MAX_LENGTH).join("");
+ const issued = yield* auth
+ .createPairingLink({
+ scopes,
+ ttl: CLIENT_PAIRING_TTL,
+ label: `${clientLabel} · via ${via}`,
+ })
+ .pipe(
+ Effect.catchTags({
+ ManagedPolicyRefusedError: (error) =>
+ Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message })),
+ }),
+ );
+ return { credential: issued.credential, expiresAt: issued.expiresAt };
+ });
+
+ return PeerClientPairingIssuer.of({ issue });
+});
+
+export const layerIssuer = Layer.effect(PeerClientPairingIssuer, makeIssuer);
+
+const make = Effect.gen(function* () {
+ const links = yield* PeerLinks.PeerLinks;
+ const auth = yield* EnvironmentAuth.EnvironmentAuth;
+ const httpClient = yield* HttpClient.HttpClient;
+
+ /** What this environment's Connections calls the client that asked. */
+ const clientLabelOf = (sessionId: AuthSessionId) =>
+ auth.listClientSessions(sessionId).pipe(
+ Effect.map((sessions) => {
+ const client = sessions.find((session) => session.sessionId === sessionId)?.client;
+ return (
+ client?.label ??
+ ([client?.browser, client?.os].filter((part) => part !== undefined).join(" on ") ||
+ "T3 Code client")
+ );
+ }),
+ Effect.orElseSucceed(() => "T3 Code client"),
+ );
+
+ const request: PeerClientPairing["Service"]["request"] = Effect.fn("PeerClientPairing.request")(
+ function* (input, client) {
+ if (!(yield* links.enabled)) {
+ return yield* new PeerLinkError({
+ reason: "disabled",
+ message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
+ });
+ }
+ const stored = yield* links.get(input.environmentId);
+ if (Option.isNone(stored)) {
+ return yield* new PeerLinkError({
+ reason: "unknown_link",
+ message: "This environment is no longer linked to that one.",
+ });
+ }
+ const { environmentId, label, urls, access, expiresAt } = stored.value;
+ if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) {
+ return yield* new PeerLinkError({
+ reason: "expired",
+ message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`,
+ });
+ }
+ const unsupported = (
+ reason: Extract["reason"],
+ name = label,
+ ): PeerLinkClientPairingResult => ({
+ type: "unsupported",
+ environmentId,
+ label: name,
+ urls,
+ reason,
+ });
+ // The linked environment refuses this too; asking would only spend a round trip.
+ if (access !== "full-access") return unsupported("link_access");
+ const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option);
+ if (Option.isNone(resolved)) return unsupported("unreachable");
+ const peer = resolved.value;
+ if (peer.capabilities.linkClientPairing !== true) {
+ return unsupported("version", peer.link.label);
+ }
+ const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe(
+ Effect.provideService(HttpClient.HttpClient, httpClient),
+ );
+ return yield* api.peerLink
+ .clientPairing({
+ headers: { authorization: `Bearer ${peer.token}` },
+ payload: { scopes: client.scopes, clientLabel: yield* clientLabelOf(client.sessionId) },
+ })
+ .pipe(
+ Effect.timeout(PeerLinks.probeTimeout(peer.url)),
+ Effect.map((issued): PeerLinkClientPairingResult => ({
+ type: "credential",
+ environmentId,
+ label: peer.link.label,
+ urls,
+ credential: issued.credential,
+ expiresAt: issued.expiresAt,
+ })),
+ // No cause is logged or returned: a response this version cannot read may hold the credential.
+ Effect.catchTags({
+ HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
+ TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
+ }),
+ Effect.orElseSucceed(() => unsupported("refused", peer.link.label)),
+ );
+ },
+ );
+
+ return PeerClientPairing.of({ request });
+});
+
+export const layer = Layer.effect(PeerClientPairing, make);
diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts
index e95a6a7a427f1..ff09db6cbdf7f 100644
--- a/apps/server/src/peer/PeerLinks.testkit.ts
+++ b/apps/server/src/peer/PeerLinks.testkit.ts
@@ -32,6 +32,8 @@ import * as ServerHttp from "../http.ts";
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as Sqlite from "../persistence/Sqlite.ts";
+import * as PeerHttp from "./http.ts";
+import * as PeerClientPairing from "./PeerClientPairing.ts";
import * as PeerLinks from "./PeerLinks.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as PeerMcpClient from "./PeerMcpClient.ts";
@@ -39,7 +41,8 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
class PeerTestApi extends HttpApi.make("environment")
.add(EnvironmentHttpApi.groups.metadata)
- .add(EnvironmentHttpApi.groups.mcpOAuth) {}
+ .add(EnvironmentHttpApi.groups.mcpOAuth)
+ .add(EnvironmentHttpApi.groups.peerLink) {}
export const descriptorOf = (
environmentId: string,
@@ -58,6 +61,19 @@ export const descriptorOf = (
},
});
+/** An environment's own sessions and pairing links, on a database and secret store of its own. */
+export const layerEnvironmentAuth = (prefix: string) =>
+ EnvironmentAuth.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
+ Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
+ Layer.provide(Sqlite.layerMemory),
+ Layer.provideMerge(ServerSecretStore.layer),
+ Layer.provideMerge(ServerEnvironment.layerIdentity),
+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix })),
+ Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
+ Layer.fresh,
+ );
+
/**
* The environment a link points at, as it runs: its descriptor, MCP OAuth,
* and `/mcp` with `tools` behind the real client authenticator, on a real
@@ -81,17 +97,7 @@ export const servePeer = (
getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
getDescriptor: Ref.get(descriptor),
});
- const authContext = yield* EnvironmentAuth.layer.pipe(
- Layer.provide(ManagedPolicy.layerTest()),
- Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
- Layer.provide(Sqlite.layerMemory),
- Layer.provideMerge(ServerSecretStore.layer),
- Layer.provideMerge(ServerEnvironment.layerIdentity),
- Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
- Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
- Layer.fresh,
- Layer.build,
- );
+ const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-peer-"));
const layerRecordBearers = HttpRouter.middleware(
(httpEffect) =>
Effect.gen(function* () {
@@ -131,6 +137,7 @@ export const servePeer = (
),
),
),
+ Layer.provide(PeerHttp.layer.pipe(Layer.provide(PeerClientPairing.layerIssuer))),
Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
Layer.provide(AuthHttp.layerAuthenticatedAuth),
),
diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts
index 4bf0653974e53..5325e5745c5d7 100644
--- a/apps/server/src/peer/PeerLinks.ts
+++ b/apps/server/src/peer/PeerLinks.ts
@@ -84,6 +84,9 @@ export interface ResolvedPeerLink {
readonly capabilities: ExecutionEnvironmentCapabilities;
}
+/** What a link's session is called in the peer's Connections, before this environment's label. */
+export const LINK_CLIENT_NAME_PREFIX = "T3 Code · ";
+
export const LINKED_ENVIRONMENTS_OFF =
"Linked environments is off on this machine. Turn it on in Settings → Labs.";
@@ -552,7 +555,7 @@ const make = Effect.gen(function* () {
message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
});
}
- const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);
+ const issued = yield* signIn(primary, input, `${LINK_CLIENT_NAME_PREFIX}${self.label}`);
const now = yield* DateTime.now;
const linked: PeerLink = {
environmentId: peer.environmentId,
diff --git a/apps/server/src/peer/http.ts b/apps/server/src/peer/http.ts
new file mode 100644
index 0000000000000..4baf9bebb9746
--- /dev/null
+++ b/apps/server/src/peer/http.ts
@@ -0,0 +1,76 @@
+import {
+ EnvironmentHttpApi,
+ EnvironmentHttpForbiddenError,
+ EnvironmentHttpInternalServerError,
+ EnvironmentHttpUnauthorizedError,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import { HttpServerRequest, HttpServerResponse } from "effect/http";
+import * as HttpEffect from "effect/http/HttpEffect";
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
+
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as PeerClientPairing from "./PeerClientPairing.ts";
+
+// The response is a credential.
+const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
+ Effect.succeed(
+ HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),
+ ),
+);
+
+/**
+ * A link session is accepted on `/mcp` and here, nowhere else. This is a route and not an MCP
+ * tool so that no agent's tool list can hold it: thread credentials never authenticate here.
+ */
+export const layer = HttpApiBuilder.group(
+ EnvironmentHttpApi,
+ "peerLink",
+ Effect.fnUntraced(function* (handlers) {
+ const auth = yield* EnvironmentAuth.EnvironmentAuth;
+ const issuer = yield* PeerClientPairing.PeerClientPairingIssuer;
+ return handlers.handle(
+ "clientPairing",
+ Effect.fn("environment.peerLink.clientPairing")(function* (args) {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ yield* noStore;
+ // A browser never holds a link's token; refuse one before reading credentials, as `/mcp` does.
+ if (request.headers.origin !== undefined) {
+ return yield* new EnvironmentHttpForbiddenError({
+ message: "This route does not accept browser requests.",
+ });
+ }
+ const caller = yield* auth.authenticateMcpClient(request).pipe(
+ Effect.mapError((error) =>
+ EnvironmentAuth.isServerAuthCredentialError(error)
+ ? new EnvironmentHttpUnauthorizedError({
+ message: "Only a linked environment's session is accepted here.",
+ })
+ : new EnvironmentHttpInternalServerError({
+ message: "The session could not be checked.",
+ }),
+ ),
+ );
+ return yield* issuer.issue(caller, args.payload).pipe(
+ Effect.catchTags({
+ PeerClientPairingRefused: (error) =>
+ Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
+ }),
+ Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
+ Effect.logError("Could not mint a client pairing for a linked environment.", {
+ cause,
+ }).pipe(
+ Effect.andThen(
+ Effect.fail(
+ new EnvironmentHttpInternalServerError({
+ message: "The pairing could not be created.",
+ }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }),
+ );
+ }),
+);
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index d23f4ff7aa756..c838cfc2b7872 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -92,6 +92,8 @@ import * as TerminalManager from "./terminal/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as PeerForwarding from "./peer/PeerForwarding.ts";
import * as RemoteDelegation from "./peer/RemoteDelegation.ts";
+import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
+import * as PeerClientPairingHttp from "./peer/http.ts";
import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
import * as PeerLinks from "./peer/PeerLinks.ts";
import * as PeerMcpClient from "./peer/PeerMcpClient.ts";
@@ -850,6 +852,7 @@ const layerMakeRoutes = Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(AuthHttp.layer),
Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
+ Layer.provide(PeerClientPairingHttp.layer.pipe(Layer.provide(PeerClientPairing.layerIssuer))),
Layer.provide(CloudHttp.layer),
Layer.provide(OrchestrationHttp.layer),
Layer.provide(PullRequestHttp.layer),
@@ -901,7 +904,7 @@ const layerMakeRoutes = Layer.mergeAll(
Layer.provide(PreviewBrowser.layer),
// Links to other environments, shared by clients (WebSocket) and agents (/mcp).
Layer.provide(
- Layer.merge(PeerForwarding.layer, PeerThreadRelay.layer).pipe(
+ Layer.mergeAll(PeerForwarding.layer, PeerThreadRelay.layer, PeerClientPairing.layer).pipe(
Layer.provideMerge(PeerMcpClient.layer),
Layer.provideMerge(PeerLinks.layer),
),
diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts
index 6da9e9ab69c66..12d6a1b601b3a 100644
--- a/apps/server/src/ws.test.ts
+++ b/apps/server/src/ws.test.ts
@@ -102,6 +102,7 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as RpcAuthorization from "./auth/RpcAuthorization.ts";
import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts";
+import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
import * as PeerLinks from "./peer/PeerLinks.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -850,6 +851,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
Layer.mock(PeerLinks.PeerLinks)({}),
Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
Layer.mock(PeerThreadRelay.PeerThreadRelay)({}),
+ Layer.mock(PeerClientPairing.PeerClientPairing)({}),
Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }),
Layer.mock(PreviewManager.PreviewManager)({}),
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 1035be8096a9c..3747e013a0193 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -6,6 +6,7 @@ import * as Context from "effect/Context";
import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
+import * as PeerClientPairing from "./peer/PeerClientPairing.ts";
import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
import * as PeerLinks from "./peer/PeerLinks.ts";
import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts";
@@ -1562,6 +1563,7 @@ export const layerWsRpc = (
const peerLinks = yield* PeerLinks.PeerLinks;
const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay;
+ const peerClientPairing = yield* PeerClientPairing.PeerClientPairing;
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -2720,6 +2722,8 @@ export const layerWsRpc = (
Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
Effect.andThen(peerThreadRelay.item(input)),
),
+ [WS_METHODS.peerLinksPairClient]: (input) =>
+ peerClientPairing.request(input, currentSession),
[WS_METHODS.peerLinksAnswerRequest]: (input) =>
Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
Effect.andThen(peerLinkRequests.answer(input)),
@@ -3632,6 +3636,7 @@ export const layer = Layer.unwrap(
const peerLinks = yield* PeerLinks.PeerLinks;
const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay;
+ const peerClientPairing = yield* PeerClientPairing.PeerClientPairing;
const sql = yield* SqlClient.SqlClient;
return HttpRouter.add(
"GET",
@@ -3733,6 +3738,7 @@ export const layer = Layer.unwrap(
Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)),
Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)),
Layer.provide(Layer.succeed(PeerThreadRelay.PeerThreadRelay, peerThreadRelay)),
+ Layer.provide(Layer.succeed(PeerClientPairing.PeerClientPairing, peerClientPairing)),
Layer.provide(
SourceControlDiscovery.layer.pipe(
Layer.provide(
diff --git a/apps/web/src/components/chat/LinkedThreadPane.tsx b/apps/web/src/components/chat/LinkedThreadPane.tsx
index 041c46a6bc52f..514e75b3c1e34 100644
--- a/apps/web/src/components/chat/LinkedThreadPane.tsx
+++ b/apps/web/src/components/chat/LinkedThreadPane.tsx
@@ -1,13 +1,17 @@
import { isLinkedThreadWorking, linkedThreadFailure } from "@t3tools/client-runtime/linked-thread";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { T, useGT, useMessages, Var } from "gt-react";
-import { EyeIcon } from "lucide-react";
+import { EyeIcon, PlugIcon } from "lucide-react";
import { useState, type ReactNode } from "react";
import { useStableCallback } from "../../hooks/useStableCallback";
import { type LinkedThreadSurface, linkedThreadTitle } from "../../linkedThreadSurface";
import { useEnvironment } from "../../state/environments";
-import { linkedThreadItemSource, useLinkedThreadView } from "../../state/linkedThreadView";
+import {
+ linkedThreadItemSource,
+ useConnectLinkedEnvironment,
+ useLinkedThreadView,
+} from "../../state/linkedThreadView";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
import { Button } from "../ui/button";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
@@ -18,6 +22,7 @@ import {
ReadOnlyComposerStatus,
} from "./ReadOnlyComposerBar";
import { Spinner } from "../ui/spinner";
+import { toastManager } from "../ui/toast";
import type { MessagesTimelineHistoryControls } from "./MessagesTimeline";
import { ReadOnlyThreadTimeline } from "./ReadOnlyThreadTimeline";
@@ -86,6 +91,63 @@ export function LinkedThreadPane(props: {
const [turnItemSource] = useState(() => linkedThreadItemSource(surface));
const label = surface.label;
const projection = view?.thread.projection ?? null;
+ const connection = useConnectLinkedEnvironment(panelRef, surface);
+ const connectState = connection.state;
+ const connecting = connectState.phase === "connecting";
+ const connect = async () => {
+ const outcome = await connection.connect();
+ if (outcome.type === "connected") {
+ toastManager.add({
+ type: "success",
+ title: gt("Connected to {label}", { label }),
+ description: gt("This device is paired with it and can use its threads."),
+ });
+ }
+ };
+ const connectNotice: ComposerBannerStackItem | null =
+ connectState.phase === "connecting"
+ ? {
+ id: "connecting",
+ variant: "info",
+ icon: ,
+ title: gt("Connecting to {label}…", { label }),
+ }
+ : connectState.phase === "unreachable"
+ ? {
+ id: "unreachable",
+ variant: "warning",
+ icon: ,
+ title: gt("{label} is not reachable from this device", { label: connectState.label }),
+ description: gt(
+ "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.",
+ ),
+ }
+ : connectState.phase === "manual"
+ ? {
+ id: "manual",
+ variant: "info",
+ icon: ,
+ title: gt("{label} needs a pairing code", { label: connectState.prefill.label }),
+ description: gt("Create one on it, then add it to this device as an environment."),
+ actions: (
+
+ ),
+ }
+ : null;
+ const connectAction = (
+
+ );
const failure = error === null ? null : linkedThreadFailure(error, { via, label }, m);
const retryAction = failure?.retryable ? (
@@ -136,7 +198,13 @@ export function LinkedThreadPane(props: {
)}
-
+
>
) : (
)}
-
+
>
)}
diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx
index 1ff226b1bc03d..bdf0dae7cbf96 100644
--- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx
+++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx
@@ -53,6 +53,7 @@ import {
import { useEnvironmentQuery } from "~/state/query";
import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts";
import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
+import type { AddEnvironmentPrefill } from "~/state/linkedThreadView";
import { useAtomCommand } from "../../state/use-atom-command";
import { primaryServerKeybindingsAtom } from "~/state/server";
import {
@@ -77,6 +78,7 @@ const sshHostSuggestionValue = (target: DesktopDiscoveredSshHost) =>
export function AddEnvironmentDialog({
open,
+ prefill = null,
routeTarget,
error,
savedEnvironments,
@@ -84,6 +86,8 @@ export function AddEnvironmentDialog({
onErrorChange,
}: {
readonly open: boolean;
+ /** A machine the user chose elsewhere to pair with; they supply only the pairing code. */
+ readonly prefill?: AddEnvironmentPrefill | null;
readonly routeTarget: EnvironmentPresentation | null;
readonly error: string | null;
readonly savedEnvironments: ReadonlyArray;
@@ -119,7 +123,7 @@ export function AddEnvironmentDialog({
return keys;
})();
const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote");
- const [savedBackendHost, setSavedBackendHost] = useState("");
+ const [savedBackendHost, setSavedBackendHost] = useState(prefill?.host ?? "");
const [savedBackendPairingCode, setSavedBackendPairingCode] = useState("");
const [savedBackendSshHost, setSavedBackendSshHost] = useState("");
const [savedBackendSshUsername, setSavedBackendSshUsername] = useState("");
@@ -243,9 +247,10 @@ export function AddEnvironmentDialog({
return;
}
+ const expected = routeTarget ?? prefill;
const result = await connectPairing({
...remotePairingInput,
- ...(routeTarget ? { expectedEnvironmentId: routeTarget.environmentId } : {}),
+ ...(expected ? { expectedEnvironmentId: expected.environmentId } : {}),
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
@@ -683,14 +688,21 @@ export function AddEnvironmentDialog({
{routeTarget
? gt("Add a route to {environment}", { environment: routeTarget.label })
- : gt("Add Environment")}
+ : prefill
+ ? gt("Connect to {environment}", { environment: prefill.label })
+ : gt("Add Environment")}
{routeTarget
? gt(
"Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine.",
)
- : gt("Pair another environment to this client.")}
+ : prefill
+ ? gt(
+ "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
+ { environment: prefill.label },
+ )
+ : gt("Pair another environment to this client.")}
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index 8f4d8778bcf80..1201b18e2a9a8 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -4,7 +4,7 @@ import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels
import { SessionPermissions } from "./SessionPermissions";
import { useSearch } from "@tanstack/react-router";
import { ChevronRightIcon, EllipsisIcon } from "lucide-react";
-import { useAtomValue } from "@effect/atom-react";
+import { useAtom, useAtomValue } from "@effect/atom-react";
import { type ReactNode, useState } from "react";
import { T, useGT, useMessages, Var } from "gt-react";
import {
@@ -50,6 +50,7 @@ import { ConnectDeviceApprovalSettings } from "./ConnectDeviceApprovalSettings";
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
import { FoldedSettingsSection } from "./FoldedSettingsSection";
import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";
+import { addEnvironmentPrefillAtom } from "~/state/linkedThreadView";
import { usePeerLinkHosts } from "~/state/peerLinks";
import { LoadBalancingSettings } from "./LoadBalancingSettings";
import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";
@@ -356,12 +357,15 @@ function ConnectionsSettingsContent({
const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
const [routeTarget, setRouteTarget] = useState(null);
const [savedBackendError, setSavedBackendError] = useState(null);
+ // Set by a read-only linked thread whose machine this client is about to pair with.
+ const [addPrefill, setAddPrefill] = useAtom(addEnvironmentPrefillAtom);
const handleAddBackendDialogOpenChange = (open: boolean) => {
setAddBackendDialogOpen(open);
if (open) {
setRouteTarget(null);
} else {
setSavedBackendError(null);
+ setAddPrefill(null);
}
};
const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] =
@@ -1814,7 +1818,9 @@ function ConnectionsSettingsContent({
) : null}
onboarding.registerSsh(input)),
),
});
+
+export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, {
+ label: "web:connection:reaches-environment",
+ execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) =>
+ ConnectionOnboarding.ConnectionOnboarding.pipe(
+ Effect.flatMap((onboarding) => onboarding.reaches(input)),
+ ),
+});
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index acdfd90c95938..6bf4e782aad8d 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "T3 Code auf {host} war zu beschäftigt, um zu antworten.",
"5c5941732d5dfac6": "Die Kopplungsdaten sind ungültig.",
"b8ca23ad7dda376e": "Diese Adresse führt zu {host}, einem anderen Rechner. Füge sie stattdessen als eigene Umgebung hinzu.",
+ "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
"693cb5c4fb40f109": "Nur gespeicherte Bearer-Umgebungen können bearbeitet werden.",
"5f5844b910cb1544": "Die gespeicherten Bearer-Zugangsdaten sind nicht verfügbar.",
"51b0133f1ed3cf5c": "Die Bezeichnung der Umgebung darf nicht leer sein.",
- "0c0150a90b582a7a": "Die URL der Umgebung ist ungültig.",
"3aa15bfbe1920376": "Aktualisiere T3 Code auf {host} manuell; es kann sich nicht selbst aktualisieren.",
"71907f57b7ec64d5": "{host} ist nicht mit einer kompatiblen T3-Code-Version zurückgekommen.",
"e77ac580a4ddcd3b": "Verfügbar",
@@ -3623,7 +3623,15 @@
"009e2ca841fdc1ef": "diese Umgebung",
"8cb2e5692c4f05ab": "Öffne diesen Thread auf {label}, um diese Darstellung zu sehen.",
"745a0b899008618c": "Frühere Runden konnten nicht geladen werden. Versuche es erneut.",
+ "4ab24e2807a0d82f": "Mit {label} verbunden",
+ "b797c7beccf2dc46": "Dieses Gerät ist damit gekoppelt und kann seine Threads verwenden.",
+ "d8c4a71a728fcf68": "Verbindung mit {label} wird hergestellt…",
+ "93e690821c726e13": "{label} ist von diesem Gerät aus nicht erreichbar",
+ "a5424a5a76e10aa3": "Tritt einem Netzwerk bei, in dem es sich befindet, etwa seinem Tailscale-Netzwerk, und versuche es erneut. Du kannst hier weiterlesen.",
+ "1942567fd95da447": "{label} benötigt einen Kopplungscode",
+ "0f62d432499e13f9": "Erstelle dort einen und füge es diesem Gerät als Umgebung hinzu.",
"0014ce0aaf1bd68a": "Schreibgeschützt",
+ "10ca916def8211d4": "Code eingeben",
"d0bda35aeec66684": [
"Wird von ",
{
@@ -3634,6 +3642,7 @@
" gelesen …"
],
"c3e8cd9bf44e2f43": "Angezeigt wird, was zuvor gelesen wurde.",
+ "a446e3bda256c2b3": "Verbinden, um zu interagieren",
"eb6e0584cf4a2a1d": "Sprache: {language}",
"d76c606a3c519b78": "Zeilenumbruch deaktivieren",
"2b683498cee8c8a7": "Zeilen umbrechen",
@@ -7303,8 +7312,10 @@
"53c162d8868a1d0e": "Umgebung hinzufügen",
"53339e47accf021a": "Hosts durchsuchen oder devbox eingeben",
"d808738388ab80b0": "Route zu {environment} hinzufügen",
+ "8a333daf9b7fd03f": "Mit {environment} verbinden",
"7662025844bf543f": "Umgebung hinzufügen",
"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.",
+ "e1cb1c8599e84e26": "Erstelle auf {environment} einen Kopplungscode, in dessen Einstellungen → Freigabe & Zugriff oder mit `t3 auth pairing create`, und gib ihn hier ein.",
"1bea4864d46d70d0": "Eine weitere Umgebung mit diesem Client koppeln.",
"9b24ef052b321e57": "Gib einen Backend-Host und einen Kopplungscode ein.",
"3e20f17f71edf0ad": "Lokale SSH-Konfiguration, Agent und Tunnel für das Backend verwenden.",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index bf9125e821f5d..3ed9b5b0b09ca 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "T3 Code on {host} was too busy to answer.",
"5c5941732d5dfac6": "The pairing details are invalid.",
"b8ca23ad7dda376e": "That address reaches {host}, a different machine. Add it as its own environment instead.",
+ "0c0150a90b582a7a": "The environment URL is invalid.",
"693cb5c4fb40f109": "Only saved bearer environments can be edited.",
"5f5844b910cb1544": "The saved bearer credential is unavailable.",
"51b0133f1ed3cf5c": "Environment label cannot be empty.",
- "0c0150a90b582a7a": "The environment URL is invalid.",
"3aa15bfbe1920376": "Update T3 Code on {host} manually; it cannot update itself.",
"71907f57b7ec64d5": "{host} did not come back on a compatible T3 Code version.",
"e77ac580a4ddcd3b": "Available",
@@ -3622,7 +3622,15 @@
"009e2ca841fdc1ef": "this environment",
"8cb2e5692c4f05ab": "Open this thread on {label} to see this visual.",
"745a0b899008618c": "Could not load earlier turns. Try again.",
+ "4ab24e2807a0d82f": "Connected to {label}",
+ "b797c7beccf2dc46": "This device is paired with it and can use its threads.",
+ "d8c4a71a728fcf68": "Connecting to {label}…",
+ "93e690821c726e13": "{label} is not reachable from this device",
+ "a5424a5a76e10aa3": "Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.",
+ "1942567fd95da447": "{label} needs a pairing code",
+ "0f62d432499e13f9": "Create one on it, then add it to this device as an environment.",
"0014ce0aaf1bd68a": "Read-only",
+ "10ca916def8211d4": "Enter code",
"d0bda35aeec66684": [
"Reading from ",
{
@@ -3633,6 +3641,7 @@
"…"
],
"c3e8cd9bf44e2f43": "Showing what was read before.",
+ "a446e3bda256c2b3": "Connect to interact",
"eb6e0584cf4a2a1d": "Language: {language}",
"d76c606a3c519b78": "Disable line wrap",
"2b683498cee8c8a7": "Wrap lines",
@@ -7311,8 +7320,10 @@
"53c162d8868a1d0e": "Add environment",
"53339e47accf021a": "Search hosts or type devbox",
"d808738388ab80b0": "Add a route to {environment}",
+ "8a333daf9b7fd03f": "Connect to {environment}",
"7662025844bf543f": "Add Environment",
"65b1d784a5e84254": "Pair this machine again over another address, such as its Tailscale name. It joins the existing routes instead of adding a second machine.",
+ "e1cb1c8599e84e26": "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.",
"1bea4864d46d70d0": "Pair another environment to this client.",
"9b24ef052b321e57": "Enter a backend host and pairing code.",
"3e20f17f71edf0ad": "Use local SSH config, agent, and tunnels for the backend.",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index e0f52492df584..dd9280abac65f 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "T3 Code en {host} estaba demasiado ocupado para responder.",
"5c5941732d5dfac6": "Los datos de emparejamiento no son válidos.",
"b8ca23ad7dda376e": "Esa dirección lleva a {host}, otra máquina. Añádela como un entorno propio.",
+ "0c0150a90b582a7a": "La URL del entorno no es válida.",
"693cb5c4fb40f109": "Solo se pueden editar los entornos bearer guardados.",
"5f5844b910cb1544": "La credencial bearer guardada no está disponible.",
"51b0133f1ed3cf5c": "La etiqueta del entorno no puede estar vacía.",
- "0c0150a90b582a7a": "La URL del entorno no es válida.",
"3aa15bfbe1920376": "Actualiza T3 Code en {host} manualmente; no puede actualizarse solo.",
"71907f57b7ec64d5": "{host} no volvió con una versión compatible de T3 Code.",
"e77ac580a4ddcd3b": "Disponible",
@@ -3622,7 +3622,15 @@
"009e2ca841fdc1ef": "este entorno",
"8cb2e5692c4f05ab": "Abre este hilo en {label} para ver este elemento visual.",
"745a0b899008618c": "No se pudieron cargar los turnos anteriores. Vuelve a intentarlo.",
+ "4ab24e2807a0d82f": "Conectado a {label}",
+ "b797c7beccf2dc46": "Este dispositivo está emparejado con él y puede usar sus hilos.",
+ "d8c4a71a728fcf68": "Conectando con {label}…",
+ "93e690821c726e13": "No se puede acceder a {label} desde este dispositivo",
+ "a5424a5a76e10aa3": "Únete a una red en la que esté, como su red de Tailscale, y vuelve a intentarlo. Puedes seguir leyendo aquí.",
+ "1942567fd95da447": "{label} necesita un código de emparejamiento",
+ "0f62d432499e13f9": "Crea uno allí y añádelo a este dispositivo como entorno.",
"0014ce0aaf1bd68a": "Solo lectura",
+ "10ca916def8211d4": "Introducir código",
"d0bda35aeec66684": [
"Leyendo desde ",
{
@@ -3633,6 +3641,7 @@
"…"
],
"c3e8cd9bf44e2f43": "Se muestra lo que se leyó antes.",
+ "a446e3bda256c2b3": "Conectar para interactuar",
"eb6e0584cf4a2a1d": "Lenguaje: {language}",
"d76c606a3c519b78": "Desactivar ajuste de línea",
"2b683498cee8c8a7": "Ajustar líneas",
@@ -7304,8 +7313,10 @@
"53c162d8868a1d0e": "Añadir entorno",
"53339e47accf021a": "Busca hosts o escribe devbox",
"d808738388ab80b0": "Añadir una ruta a {environment}",
+ "8a333daf9b7fd03f": "Conectar con {environment}",
"7662025844bf543f": "Añadir entorno",
"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.",
+ "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í.",
"1bea4864d46d70d0": "Empareja otro entorno con este cliente.",
"9b24ef052b321e57": "Introduce un host de backend y un código de emparejamiento.",
"3e20f17f71edf0ad": "Usa la configuración SSH local, el agente y los túneles para el backend.",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 97cd5bc681a6f..f4c23672f0cef 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "T3 Code sur {host} était trop occupé pour répondre.",
"5c5941732d5dfac6": "Les informations d’appairage ne sont pas valides.",
"b8ca23ad7dda376e": "Cette adresse mène à {host}, une autre machine. Ajoutez-la plutôt comme environnement distinct.",
+ "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
"693cb5c4fb40f109": "Seuls les environnements bearer enregistrés peuvent être modifiés.",
"5f5844b910cb1544": "Les identifiants bearer enregistrés ne sont pas disponibles.",
"51b0133f1ed3cf5c": "Le libellé de l’environnement ne peut pas être vide.",
- "0c0150a90b582a7a": "L’URL de l’environnement n’est pas valide.",
"3aa15bfbe1920376": "Mettez à jour T3 Code sur {host} manuellement ; il ne peut pas se mettre à jour seul.",
"71907f57b7ec64d5": "{host} n’est pas revenu sur une version compatible de T3 Code.",
"e77ac580a4ddcd3b": "Disponible",
@@ -3622,7 +3622,15 @@
"009e2ca841fdc1ef": "cet environnement",
"8cb2e5692c4f05ab": "Ouvrez ce fil sur {label} pour voir ce visuel.",
"745a0b899008618c": "Impossible de charger les tours précédents. Réessayez.",
+ "4ab24e2807a0d82f": "Connecté à {label}",
+ "b797c7beccf2dc46": "Cet appareil y est appairé et peut utiliser ses fils.",
+ "d8c4a71a728fcf68": "Connexion à {label}…",
+ "93e690821c726e13": "{label} n’est pas accessible depuis cet appareil",
+ "a5424a5a76e10aa3": "Rejoignez un réseau sur lequel il se trouve, comme son réseau Tailscale, puis réessayez. Vous pouvez continuer à lire ici.",
+ "1942567fd95da447": "{label} nécessite un code d’appairage",
+ "0f62d432499e13f9": "Créez-en un dessus, puis ajoutez-le à cet appareil comme environnement.",
"0014ce0aaf1bd68a": "Lecture seule",
+ "10ca916def8211d4": "Saisir le code",
"d0bda35aeec66684": [
"Lecture depuis ",
{
@@ -3633,6 +3641,7 @@
"…"
],
"c3e8cd9bf44e2f43": "Affichage de ce qui a été lu auparavant.",
+ "a446e3bda256c2b3": "Se connecter pour interagir",
"eb6e0584cf4a2a1d": "Langage : {language}",
"d76c606a3c519b78": "Désactiver le retour à la ligne",
"2b683498cee8c8a7": "Retour à la ligne",
@@ -7305,8 +7314,10 @@
"53c162d8868a1d0e": "Ajouter un environnement",
"53339e47accf021a": "Rechercher des hôtes ou saisir devbox",
"d808738388ab80b0": "Ajouter une route vers {environment}",
+ "8a333daf9b7fd03f": "Se connecter à {environment}",
"7662025844bf543f": "Ajouter un environnement",
"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.",
+ "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.",
"1bea4864d46d70d0": "Appairez un autre environnement à ce client.",
"9b24ef052b321e57": "Saisissez un hôte de backend et un code d’appairage.",
"3e20f17f71edf0ad": "Utiliser la configuration SSH locale, l’agent et les tunnels pour le backend.",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 43ee223b82fe4..7e2d260d010ba 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "{host} の T3 Code はビジー状態で応答できませんでした。",
"5c5941732d5dfac6": "ペアリングの詳細が無効です。",
"b8ca23ad7dda376e": "そのアドレスは別のマシンである {host} につながります。代わりに独立した環境として追加してください。",
+ "0c0150a90b582a7a": "環境の URL が無効です。",
"693cb5c4fb40f109": "編集できるのは保存済みのベアラー環境のみです。",
"5f5844b910cb1544": "保存済みのベアラー資格情報は利用できません。",
"51b0133f1ed3cf5c": "環境のラベルは空にできません。",
- "0c0150a90b582a7a": "環境の URL が無効です。",
"3aa15bfbe1920376": "{host} の T3 Code は自動で更新できないため、手動で更新してください。",
"71907f57b7ec64d5": "{host} は互換性のある T3 Code のバージョンで復帰しませんでした。",
"e77ac580a4ddcd3b": "利用可能",
@@ -3617,7 +3617,15 @@
"009e2ca841fdc1ef": "この環境",
"8cb2e5692c4f05ab": "このビジュアルを見るには、{label} でこのスレッドを開いてください。",
"745a0b899008618c": "以前のターンを読み込めませんでした。もう一度お試しください。",
+ "4ab24e2807a0d82f": "{label} に接続しました",
+ "b797c7beccf2dc46": "このデバイスはペアリング済みで、そのスレッドを利用できます。",
+ "d8c4a71a728fcf68": "{label} に接続しています…",
+ "93e690821c726e13": "このデバイスから {label} に接続できません",
+ "a5424a5a76e10aa3": "Tailscale ネットワークなど、そのマシンが接続しているネットワークに参加してから、もう一度お試しください。ここでは引き続き閲覧できます。",
+ "1942567fd95da447": "{label} にはペアリングコードが必要です",
+ "0f62d432499e13f9": "そのマシンで作成し、このデバイスに環境として追加してください。",
"0014ce0aaf1bd68a": "読み取り専用",
+ "10ca916def8211d4": "コードを入力",
"d0bda35aeec66684": [
"読み取り中: ",
{
@@ -3628,6 +3636,7 @@
"…"
],
"c3e8cd9bf44e2f43": "以前に読み取った内容を表示しています。",
+ "a446e3bda256c2b3": "接続して操作する",
"eb6e0584cf4a2a1d": "言語: {language}",
"d76c606a3c519b78": "行の折り返しを無効にする",
"2b683498cee8c8a7": "行を折り返す",
@@ -7271,8 +7280,10 @@
"53c162d8868a1d0e": "環境を追加",
"53339e47accf021a": "ホストを検索、または devbox と入力",
"d808738388ab80b0": "{environment} へのルートを追加",
+ "8a333daf9b7fd03f": "{environment} に接続",
"7662025844bf543f": "環境を追加",
"65b1d784a5e84254": "このマシンを別のアドレス (Tailscale の名前など) でもう一度ペアリングします。2 台目のマシンとして追加されるのではなく、既存のルートに加わります。",
+ "e1cb1c8599e84e26": "{environment} の設定 → 共有とアクセス、または `t3 auth pairing create` でペアリングコードを作成し、ここに入力してください。",
"1bea4864d46d70d0": "このクライアントに別の環境をペアリングします。",
"9b24ef052b321e57": "バックエンドのホストとペアリングコードを入力してください。",
"3e20f17f71edf0ad": "バックエンドにはローカルの SSH 構成、エージェント、トンネルを使用します。",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index 0536a957dcf87..6e9795c9f0fd6 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "{host}의 T3 Code가 너무 바빠서 응답하지 못했습니다.",
"5c5941732d5dfac6": "페어링 정보가 올바르지 않습니다.",
"b8ca23ad7dda376e": "이 주소는 다른 머신인 {host}에 연결됩니다. 대신 별도의 환경으로 추가하세요.",
+ "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
"693cb5c4fb40f109": "저장된 bearer 환경만 편집할 수 있습니다.",
"5f5844b910cb1544": "저장된 bearer 자격 증명을 사용할 수 없습니다.",
"51b0133f1ed3cf5c": "환경 레이블은 비워 둘 수 없습니다.",
- "0c0150a90b582a7a": "환경 URL이 올바르지 않습니다.",
"3aa15bfbe1920376": "{host}의 T3 Code는 스스로 업데이트할 수 없으니 직접 업데이트하세요.",
"71907f57b7ec64d5": "{host}이(가) 호환되는 T3 Code 버전으로 돌아오지 않았습니다.",
"e77ac580a4ddcd3b": "사용 가능",
@@ -3617,7 +3617,15 @@
"009e2ca841fdc1ef": "이 환경",
"8cb2e5692c4f05ab": "이 시각 자료를 보려면 {label}에서 이 스레드를 여세요.",
"745a0b899008618c": "이전 턴을 불러올 수 없습니다. 다시 시도하세요.",
+ "4ab24e2807a0d82f": "{label}에 연결됨",
+ "b797c7beccf2dc46": "이 기기가 페어링되어 해당 스레드를 사용할 수 있습니다.",
+ "d8c4a71a728fcf68": "{label}에 연결하는 중…",
+ "93e690821c726e13": "이 기기에서 {label}에 연결할 수 없습니다",
+ "a5424a5a76e10aa3": "Tailscale 네트워크처럼 해당 머신이 연결된 네트워크에 참여한 후 다시 시도하세요. 여기에서 계속 읽을 수 있습니다.",
+ "1942567fd95da447": "{label}에 페어링 코드가 필요합니다",
+ "0f62d432499e13f9": "해당 머신에서 코드를 만든 다음 이 기기에 환경으로 추가하세요.",
"0014ce0aaf1bd68a": "읽기 전용",
+ "10ca916def8211d4": "코드 입력",
"d0bda35aeec66684": [
"읽는 중: ",
{
@@ -3628,6 +3636,7 @@
"…"
],
"c3e8cd9bf44e2f43": "이전에 읽은 내용을 표시하고 있습니다.",
+ "a446e3bda256c2b3": "연결하여 상호작용",
"eb6e0584cf4a2a1d": "언어: {language}",
"d76c606a3c519b78": "줄 바꿈 끄기",
"2b683498cee8c8a7": "줄 바꿈",
@@ -7274,8 +7283,10 @@
"53c162d8868a1d0e": "환경 추가",
"53339e47accf021a": "호스트 검색 또는 devbox 입력",
"d808738388ab80b0": "{environment}에 경로 추가",
+ "8a333daf9b7fd03f": "{environment}에 연결",
"7662025844bf543f": "환경 추가",
"65b1d784a5e84254": "Tailscale 이름 같은 다른 주소로 이 머신을 다시 페어링하세요. 두 번째 머신을 추가하는 대신 기존 경로에 합쳐집니다.",
+ "e1cb1c8599e84e26": "{environment}의 설정 → 공유 및 액세스에서 또는 `t3 auth pairing create`로 페어링 코드를 만든 다음 여기에 입력하세요.",
"1bea4864d46d70d0": "이 클라이언트에 다른 환경을 페어링합니다.",
"9b24ef052b321e57": "백엔드 호스트와 페어링 코드를 입력하세요.",
"3e20f17f71edf0ad": "백엔드에 로컬 SSH 구성, 에이전트, 터널을 사용합니다.",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index 5003e05f792b7..dc0dbfcad030c 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "O T3 Code em {host} estava ocupado demais para responder.",
"5c5941732d5dfac6": "Os detalhes de pareamento são inválidos.",
"b8ca23ad7dda376e": "Esse endereço leva a {host}, outra máquina. Adicione-a como um ambiente próprio.",
+ "0c0150a90b582a7a": "A URL do ambiente é inválida.",
"693cb5c4fb40f109": "Só é possível editar ambientes bearer salvos.",
"5f5844b910cb1544": "A credencial bearer salva não está disponível.",
"51b0133f1ed3cf5c": "O rótulo do ambiente não pode ficar vazio.",
- "0c0150a90b582a7a": "A URL do ambiente é inválida.",
"3aa15bfbe1920376": "Atualize o T3 Code em {host} manualmente; ele não consegue se atualizar sozinho.",
"71907f57b7ec64d5": "{host} não voltou em uma versão compatível do T3 Code.",
"e77ac580a4ddcd3b": "Disponível",
@@ -3622,7 +3622,15 @@
"009e2ca841fdc1ef": "este ambiente",
"8cb2e5692c4f05ab": "Abra este thread em {label} para ver este visual.",
"745a0b899008618c": "Não foi possível carregar os turnos anteriores. Tente novamente.",
+ "4ab24e2807a0d82f": "Conectado a {label}",
+ "b797c7beccf2dc46": "Este dispositivo está pareado com ele e pode usar suas threads.",
+ "d8c4a71a728fcf68": "Conectando a {label}…",
+ "93e690821c726e13": "{label} não está acessível a partir deste dispositivo",
+ "a5424a5a76e10aa3": "Entre em uma rede em que ele esteja, como a rede Tailscale dele, e tente novamente. Você pode continuar lendo aqui.",
+ "1942567fd95da447": "{label} precisa de um código de pareamento",
+ "0f62d432499e13f9": "Crie um nele e adicione-o a este dispositivo como ambiente.",
"0014ce0aaf1bd68a": "Somente leitura",
+ "10ca916def8211d4": "Inserir código",
"d0bda35aeec66684": [
"Lendo de ",
{
@@ -3633,6 +3641,7 @@
"…"
],
"c3e8cd9bf44e2f43": "Mostrando o que foi lido antes.",
+ "a446e3bda256c2b3": "Conectar para interagir",
"eb6e0584cf4a2a1d": "Linguagem: {language}",
"d76c606a3c519b78": "Desativar quebra de linha",
"2b683498cee8c8a7": "Quebrar linhas",
@@ -7304,8 +7313,10 @@
"53c162d8868a1d0e": "Adicionar ambiente",
"53339e47accf021a": "Pesquise hosts ou digite devbox",
"d808738388ab80b0": "Adicionar uma rota para {environment}",
+ "8a333daf9b7fd03f": "Conectar a {environment}",
"7662025844bf543f": "Adicionar ambiente",
"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.",
+ "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.",
"1bea4864d46d70d0": "Parear outro ambiente com este cliente.",
"9b24ef052b321e57": "Informe o host do backend e um código de pareamento.",
"3e20f17f71edf0ad": "Usa a configuração SSH local, o agent e túneis para o backend.",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 9d9c58696fd16..31b603d4b2b59 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "T3 Code на {host} был слишком занят, чтобы ответить.",
"5c5941732d5dfac6": "Данные сопряжения недействительны.",
"b8ca23ad7dda376e": "Этот адрес ведёт к {host}, другому компьютеру. Добавьте его как отдельное окружение.",
+ "0c0150a90b582a7a": "URL окружения недействителен.",
"693cb5c4fb40f109": "Изменять можно только сохранённые окружения с bearer-токеном.",
"5f5844b910cb1544": "Сохранённые bearer-учётные данные недоступны.",
"51b0133f1ed3cf5c": "Название окружения не может быть пустым.",
- "0c0150a90b582a7a": "URL окружения недействителен.",
"3aa15bfbe1920376": "Обновите T3 Code на {host} вручную: он не может обновиться сам.",
"71907f57b7ec64d5": "{host} не вернулся с совместимой версией T3 Code.",
"e77ac580a4ddcd3b": "Доступно",
@@ -3622,7 +3622,15 @@
"009e2ca841fdc1ef": "это окружение",
"8cb2e5692c4f05ab": "Откройте этот тред на {label}, чтобы увидеть это визуальное представление.",
"745a0b899008618c": "Не удалось загрузить более ранние ходы. Повторите попытку.",
+ "4ab24e2807a0d82f": "Подключено к {label}",
+ "b797c7beccf2dc46": "Это устройство сопряжено с ним и может работать с его тредами.",
+ "d8c4a71a728fcf68": "Подключение к {label}…",
+ "93e690821c726e13": "{label} недоступно с этого устройства",
+ "a5424a5a76e10aa3": "Подключитесь к сети, в которой оно находится, например к его сети Tailscale, и повторите попытку. Здесь можно продолжать чтение.",
+ "1942567fd95da447": "Для {label} нужен код сопряжения",
+ "0f62d432499e13f9": "Создайте его там и добавьте эту машину на устройство как окружение.",
"0014ce0aaf1bd68a": "Только чтение",
+ "10ca916def8211d4": "Ввести код",
"d0bda35aeec66684": [
"Чтение с ",
{
@@ -3633,6 +3641,7 @@
"…"
],
"c3e8cd9bf44e2f43": "Показано то, что было прочитано раньше.",
+ "a446e3bda256c2b3": "Подключиться для взаимодействия",
"eb6e0584cf4a2a1d": "Язык: {language}",
"d76c606a3c519b78": "Отключить перенос строк",
"2b683498cee8c8a7": "Переносить строки",
@@ -7304,8 +7313,10 @@
"53c162d8868a1d0e": "Добавить окружение",
"53339e47accf021a": "Поиск хостов или введите devbox",
"d808738388ab80b0": "Добавить маршрут к {environment}",
+ "8a333daf9b7fd03f": "Подключиться к {environment}",
"7662025844bf543f": "Добавить окружение",
"65b1d784a5e84254": "Выполните сопряжение с этой машиной заново по другому адресу, например по имени в Tailscale. Он добавится к существующим маршрутам, а не создаст вторую машину.",
+ "e1cb1c8599e84e26": "Создайте код сопряжения на {environment} в разделе «Настройки → Общий доступ» или командой `t3 auth pairing create` и введите его здесь.",
"1bea4864d46d70d0": "Выполните сопряжение этого клиента с другим окружением.",
"9b24ef052b321e57": "Введите хост бэкенда и код сопряжения.",
"3e20f17f71edf0ad": "Использовать локальные конфигурацию SSH, агент и туннели для бэкенда.",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 0a645b45857ae..a0f86175e48e3 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "T3 Code på {host} var för upptagen för att svara.",
"5c5941732d5dfac6": "Uppgifterna för parkopplingen är ogiltiga.",
"b8ca23ad7dda376e": "Den adressen leder till {host}, en annan dator. Lägg till den som en egen miljö i stället.",
+ "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
"693cb5c4fb40f109": "Bara sparade bearer-miljöer kan redigeras.",
"5f5844b910cb1544": "Den sparade bearer-uppgiften är inte tillgänglig.",
"51b0133f1ed3cf5c": "Miljöns etikett får inte vara tom.",
- "0c0150a90b582a7a": "Miljöns URL är ogiltig.",
"3aa15bfbe1920376": "Uppdatera T3 Code på {host} manuellt; det kan inte uppdatera sig självt.",
"71907f57b7ec64d5": "{host} kom inte tillbaka med en kompatibel version av T3 Code.",
"e77ac580a4ddcd3b": "Tillgänglig",
@@ -3622,7 +3622,15 @@
"009e2ca841fdc1ef": "den här miljön",
"8cb2e5692c4f05ab": "Öppna den här tråden på {label} för att se den här visualiseringen.",
"745a0b899008618c": "Kunde inte läsa in tidigare omgångar. Försök igen.",
+ "4ab24e2807a0d82f": "Ansluten till {label}",
+ "b797c7beccf2dc46": "Den här enheten är parkopplad med den och kan använda dess trådar.",
+ "d8c4a71a728fcf68": "Ansluter till {label}…",
+ "93e690821c726e13": "{label} kan inte nås från den här enheten",
+ "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.",
+ "1942567fd95da447": "{label} behöver en parkopplingskod",
+ "0f62d432499e13f9": "Skapa en där och lägg till den på den här enheten som en miljö.",
"0014ce0aaf1bd68a": "Skrivskyddad",
+ "10ca916def8211d4": "Ange kod",
"d0bda35aeec66684": [
"Läser från ",
{
@@ -3633,6 +3641,7 @@
"…"
],
"c3e8cd9bf44e2f43": "Visar det som lästes tidigare.",
+ "a446e3bda256c2b3": "Anslut för att interagera",
"eb6e0584cf4a2a1d": "Språk: {language}",
"d76c606a3c519b78": "Inaktivera radbrytning",
"2b683498cee8c8a7": "Bryt rader",
@@ -7310,8 +7319,10 @@
"53c162d8868a1d0e": "Lägg till miljö",
"53339e47accf021a": "Sök värdar eller skriv devbox",
"d808738388ab80b0": "Lägg till en rutt till {environment}",
+ "8a333daf9b7fd03f": "Anslut till {environment}",
"7662025844bf543f": "Lägg till miljö",
"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.",
+ "e1cb1c8599e84e26": "Skapa en parkopplingskod på {environment}, i dess Inställningar → Delning och åtkomst eller med `t3 auth pairing create`, och ange den här.",
"1bea4864d46d70d0": "Parkoppla en annan miljö med den här klienten.",
"9b24ef052b321e57": "Ange en backend-värd och en parkopplingskod.",
"3e20f17f71edf0ad": "Använd lokal SSH-konfiguration, agent och tunnlar för backenden.",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index b933baac631c6..312065925ba94 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -458,10 +458,10 @@
"93e37fedae7eaa5b": "{host} 上的 T3 Code 太忙,未能响应。",
"5c5941732d5dfac6": "配对信息无效。",
"b8ca23ad7dda376e": "该地址指向另一台机器 {host}。请将其添加为独立环境。",
+ "0c0150a90b582a7a": "环境 URL 无效。",
"693cb5c4fb40f109": "只能编辑已保存的 bearer 环境。",
"5f5844b910cb1544": "已保存的 bearer 凭据不可用。",
"51b0133f1ed3cf5c": "环境名称不能为空。",
- "0c0150a90b582a7a": "环境 URL 无效。",
"3aa15bfbe1920376": "请手动更新 {host} 上的 T3 Code;它无法自行更新。",
"71907f57b7ec64d5": "{host} 重启后未运行兼容的 T3 Code 版本。",
"e77ac580a4ddcd3b": "可用",
@@ -3627,7 +3627,15 @@
"009e2ca841fdc1ef": "此环境",
"8cb2e5692c4f05ab": "在 {label} 上打开此会话即可查看此可视内容。",
"745a0b899008618c": "无法加载更早的对话。请重试。",
+ "4ab24e2807a0d82f": "已连接到 {label}",
+ "b797c7beccf2dc46": "此设备已与其配对,可以使用其中的会话。",
+ "d8c4a71a728fcf68": "正在连接 {label}…",
+ "93e690821c726e13": "无法从此设备访问 {label}",
+ "a5424a5a76e10aa3": "请加入它所在的网络(例如其 Tailscale 网络),然后重试。你仍可在此继续阅读。",
+ "1942567fd95da447": "{label} 需要配对码",
+ "0f62d432499e13f9": "在该机器上创建配对码,然后将其作为环境添加到此设备。",
"0014ce0aaf1bd68a": "只读",
+ "10ca916def8211d4": "输入配对码",
"d0bda35aeec66684": [
"正在从 ",
{
@@ -3638,6 +3646,7 @@
" 读取…"
],
"c3e8cd9bf44e2f43": "正在显示之前读取的内容。",
+ "a446e3bda256c2b3": "连接以进行交互",
"eb6e0584cf4a2a1d": "语言:{language}",
"d76c606a3c519b78": "取消自动换行",
"2b683498cee8c8a7": "自动换行",
@@ -7319,8 +7328,10 @@
"53c162d8868a1d0e": "添加环境",
"53339e47accf021a": "搜索主机或输入 devbox",
"d808738388ab80b0": "为 {environment} 添加线路",
+ "8a333daf9b7fd03f": "连接到 {environment}",
"7662025844bf543f": "添加环境",
"65b1d784a5e84254": "使用其他地址(例如 Tailscale 名称)再次配对此机器。该地址将加入现有线路,不会重复添加机器。",
+ "e1cb1c8599e84e26": "在 {environment} 的设置 → 共享与访问中或使用 `t3 auth pairing create` 创建配对码,然后在此输入。",
"1bea4864d46d70d0": "将其他环境与此客户端配对。",
"9b24ef052b321e57": "输入后端主机和配对码。",
"3e20f17f71edf0ad": "使用本地 SSH 配置、认证代理和隧道连接后端。",
diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts
index 63145c73119d6..7dfc41a9f617f 100644
--- a/apps/web/src/state/linkedThreadView.ts
+++ b/apps/web/src/state/linkedThreadView.ts
@@ -1,6 +1,7 @@
-import { useAtomValue } from "@effect/atom-react";
-import { scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { useAtom, useAtomSet, useAtomValue } from "@effect/atom-react";
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
+ connectLinkedEnvironment,
type LinkedThreadOpen,
resolveLinkedThreadOpen,
} from "@t3tools/client-runtime/linked-thread";
@@ -10,11 +11,13 @@ import { AsyncResult, Atom } from "effect/reactivity";
import type { TurnItemSource } from "../components/chat/timelineRowContext";
import { useRightPanelStore } from "../rightPanelStore";
+import { connectPairing, reachesEnvironment } from "../connection/onboarding";
import type { LinkedThreadSurface } from "../linkedThreadSurface";
import { buildThreadRouteParams } from "../threadRoutes";
import { useEnvironment } from "./environments";
import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
import { useEnvironmentQuery } from "./query";
+import { useAtomCommand } from "./use-atom-command";
/**
* 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(
};
}
+/** A linked environment the add-environment dialog opens for, with what is known about it filled in. */
+export interface AddEnvironmentPrefill {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly host: string | null;
+}
+
+export const addEnvironmentPrefillAtom = Atom.make(null).pipe(
+ Atom.withLabel("add-environment-prefill"),
+);
+
+export type LinkedEnvironmentConnectState =
+ | { readonly phase: "idle" | "connecting" }
+ | { readonly phase: "unreachable"; readonly label: string }
+ /** The user pairs with a code of their own; `prefill` reopens the dialog for it. */
+ | { readonly phase: "manual"; readonly prefill: AddEnvironmentPrefill };
+
+// Kept like the tab's reads, so the tab still says what happened after a visit to Settings.
+const linkedEnvironmentConnectAtom = Atom.family((key: string) =>
+ Atom.make({ phase: "idle" }).pipe(
+ Atom.setIdleTTL(5 * 60_000),
+ Atom.withLabel(`linked-environment-connect:${key}`),
+ ),
+);
+
+/**
+ * Connects this client to the environment `surface`'s thread lives in. One step when the linking
+ * environment can get a pairing for this client: the thread then opens there and the tab closes.
+ * Otherwise the add-environment dialog opens for that machine.
+ */
+export function useConnectLinkedEnvironment(
+ panelRef: ScopedThreadRef,
+ surface: LinkedThreadSurface,
+) {
+ const navigate = useNavigate();
+ const setPrefill = useAtomSet(addEnvironmentPrefillAtom);
+ const mayPair = useAtomValue(
+ peerLinkEnvironment.pairClient.permissionAtom(surface.viaEnvironmentId),
+ );
+ const quiet = { reportFailure: false, reportDefect: false } as const;
+ const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
+ const reaches = useAtomCommand(reachesEnvironment, quiet);
+ const pair = useAtomCommand(connectPairing, quiet);
+ const [state, setState] = useAtom(
+ linkedEnvironmentConnectAtom(`${scopedThreadKey(panelRef)}:${surface.id}`),
+ );
+ const addWithCode = (prefill: AddEnvironmentPrefill) => {
+ setPrefill(prefill);
+ void navigate({ to: "/settings/connections" });
+ };
+ const connect = async () => {
+ setState({ phase: "connecting" });
+ const outcome = await connectLinkedEnvironment({
+ label: surface.label,
+ requestPairing: async () => {
+ // Without it the linking environment refuses; the user can still pair by hand.
+ if (!mayPair) return null;
+ const result = await requestPairing({
+ environmentId: surface.viaEnvironmentId,
+ input: { environmentId: surface.environmentId },
+ });
+ return result._tag === "Success" ? result.value : null;
+ },
+ reaches: async (host) => {
+ const result = await reaches({ host, environmentId: surface.environmentId });
+ return result._tag === "Success" && result.value;
+ },
+ pair: async ({ host, pairingCode }) => {
+ const result = await pair({
+ host,
+ pairingCode,
+ expectedEnvironmentId: surface.environmentId,
+ });
+ return result._tag === "Success";
+ },
+ });
+ if (outcome.type === "unreachable") {
+ setState({ phase: "unreachable", label: outcome.label });
+ return outcome;
+ }
+ if (outcome.type === "connected") {
+ setState({ phase: "idle" });
+ // The thread opens where every thread on a connected environment does, so its tab is done.
+ useRightPanelStore.getState().closeSurface(panelRef, surface.id);
+ void navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(scopeThreadRef(surface.environmentId, surface.threadId)),
+ });
+ return outcome;
+ }
+ const prefill = {
+ environmentId: surface.environmentId,
+ label: outcome.label,
+ host: outcome.host,
+ };
+ setState({ phase: "manual", prefill });
+ addWithCode(prefill);
+ return outcome;
+ };
+ return { state, connect, addWithCode };
+}
+
/** Where a linked thread's expanded rows read an item in full: through the linking environment. */
export const linkedThreadItemSource = (
target: Pick,
diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md
index 9d0ebabb48158..ea64b8523541b 100644
--- a/docs/internals/environment-auth.md
+++ b/docs/internals/environment-auth.md
@@ -79,7 +79,8 @@ declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts)
where every tool must declare who may call it to compile. Any other grant adds
`orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions, and for a
[peer link](remote.md#peer-links)'s session alone the thread routes in
-[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read. Every other HTTP and WebSocket
+[linkThreadHttp](../../apps/server/src/peer/linkThreadHttp.ts), which only read, and the
+client pairing described below. Every other HTTP and WebSocket
path rejects that subject, because the RPC surface would let the agent act
above its ceiling. Inside MCP the credential sets the limits and tool
parameters only pick targets; see
@@ -91,6 +92,17 @@ discovery: the handlers still refuse such a call with
`thread_credential_required`. A secret card belongs to a thread's run, so an
outside agent that needs a secret starts a thread and lets that agent ask.
+A full-access [peer link](../../apps/server/src/peer/PeerClientPairing.ts) may
+mint a one-time pairing for a client of the environment that holds it. Its
+agents already run as this machine's user and could run `t3 auth pairing create`,
+so this adds no authority; a narrower link would gain some, so it is refused
+here, on the linked side, whatever the linking side sent. The pairing carries
+the client's scopes on the linking environment intersected with a normal
+pairing's. A person starts it: the linking environment exposes it as a WebSocket
+RPC behind `access:write`, and the linked side as an HTTP route that accepts only
+a link's session. It is not an MCP tool, because a tool is reachable by whatever
+holds a thread credential, and hiding one from tool listings is only discovery.
+
Issuer and resource URLs come from the request's Host and
`X-Forwarded-Proto`, so one server answers over loopback, Tailscale Serve and a
T3 Connect tunnel. A proxy that rewrites Host or drops the protocol header
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 1f6e221b3ebe5..a3efb1de076d1 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -487,7 +487,16 @@ it opens as a tab in the right panel, beside the thread you are in, and shows
the same timeline as any other thread.
- The view is marked **Read-only** with both machines' names. To reply, approve
- or stop the thread, connect this app to that machine.
+ or stop the thread, choose **Connect to interact**. When the link has full
+ access, this app pairs with that machine in one step and opens the thread
+ there; you need permission to manage access on the machine you are connected
+ to. Otherwise the add-environment form opens for that machine and asks for a
+ pairing code you create on it.
+- This app connects to that machine directly, so it must be able to reach one of
+ the addresses the link uses. If it cannot, the view says so and stays
+ read-only. The new connection appears in that machine's **Settings → Sharing &
+ access**, named after this device and the machine it came through, and is
+ revoked there like any other.
- Files, images and published visuals stay on that machine and do not load
here. A command's output shows as of when you open its row.
- If this app is already connected to that machine, the thread opens there as
diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.ts
index 4f804090853a8..aa74cc1088758 100644
--- a/packages/client-runtime/src/connection/onboarding.ts
+++ b/packages/client-runtime/src/connection/onboarding.ts
@@ -83,6 +83,11 @@ export class ConnectionOnboarding extends Context.Service<
readonly updateBearer: (
input: BearerConnectionUpdateInput,
) => Effect.Effect;
+ /** Whether `host` answers this device as `environmentId`. Nothing is sent but the question. */
+ readonly reaches: (input: {
+ readonly host: string;
+ readonly environmentId: EnvironmentId;
+ }) => Effect.Effect;
}
>()("@t3tools/client-runtime/connection/onboarding/ConnectionOnboarding") {}
@@ -214,6 +219,27 @@ const registerPairingConnection = Effect.fn(
return registration.target.environmentId;
});
+const REACHABILITY_TIMEOUT_MS = 6_000;
+
+const reachesEnvironment = Effect.fn("clientRuntime.connection.onboarding.reachesEnvironment")(
+ function* (input: { readonly host: string; readonly environmentId: EnvironmentId }) {
+ const httpBaseUrl = yield* Effect.try({
+ try: () => normalizeHttpBaseUrl(input.host),
+ catch: () =>
+ new ConnectionBlockedError({
+ reason: "configuration",
+ ...translatableDetail(msg("The environment URL is invalid.")),
+ }),
+ });
+ const descriptor = yield* fetchRemoteEnvironmentDescriptor({
+ httpBaseUrl,
+ timeoutMs: REACHABILITY_TIMEOUT_MS,
+ });
+ return descriptor.environmentId === input.environmentId;
+ },
+ Effect.orElseSucceed(() => false),
+);
+
const isBearerProfile = Schema.is(BearerConnectionProfile);
const updateBearerConnection = Effect.fn(
@@ -378,6 +404,12 @@ export const make = Effect.gen(function* () {
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
),
+ reaches: Effect.fnUntraced(
+ function* (input) {
+ return yield* reachesEnvironment(input);
+ },
+ Effect.provideService(HttpClient.HttpClient, httpClient),
+ ),
});
});
diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts
index 694363d5c135a..8b2d4e105e5b1 100644
--- a/packages/client-runtime/src/linkedThread.test.ts
+++ b/packages/client-runtime/src/linkedThread.test.ts
@@ -1,9 +1,12 @@
import {
+ EnvironmentId,
EventId,
type OrchestrationV2ThreadHistoryPage,
type OrchestrationV2ThreadStreamItem,
+ type PeerLinkClientPairingResult,
} from "@t3tools/contracts";
-import { expect, it } from "@effect/vitest";
+import { describe, expect, it } from "@effect/vitest";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
@@ -11,6 +14,7 @@ import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import {
+ connectLinkedEnvironment,
followLinkedThread,
keepLinkedThreadView,
LINKED_THREAD_RETRY_MS,
@@ -158,3 +162,78 @@ it.effect("loads the turns before a snapshot's window once per request", () =>
expect(asked).toEqual(["cursor-1"]);
}).pipe(Effect.scoped),
);
+
+describe("connectLinkedEnvironment", () => {
+ const lan = "http://192.168.1.20:3773";
+ const tailnet = "https://vm.tail.ts.net";
+ const target = {
+ environmentId: EnvironmentId.make("environment-vm"),
+ label: "VM",
+ urls: [lan, tailnet],
+ };
+ const credential: PeerLinkClientPairingResult = {
+ type: "credential",
+ ...target,
+ credential: "ONE-TIME",
+ expiresAt: DateTime.makeUnsafe(0),
+ };
+ const connect = (
+ pairing: PeerLinkClientPairingResult | null,
+ reachable: ReadonlyArray,
+ paired = true,
+ ) => {
+ const pairs: Array<{ host: string; pairingCode: string }> = [];
+ return connectLinkedEnvironment({
+ label: "vm (saved name)",
+ requestPairing: async () => pairing,
+ reaches: async (host) => reachable.includes(host),
+ pair: async (input) => {
+ pairs.push(input);
+ return paired;
+ },
+ }).then((outcome) => ({ outcome, pairs }));
+ };
+
+ it("redeems the pairing at the first address this device reaches", async () => {
+ expect(await connect(credential, [tailnet])).toEqual({
+ outcome: { type: "connected" },
+ pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }],
+ });
+ expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan);
+ });
+
+ it("says the machine is out of reach, and spends nothing, when no address answers", async () => {
+ expect(await connect(credential, [])).toEqual({
+ outcome: { type: "unreachable", label: "VM" },
+ pairs: [],
+ });
+ });
+
+ it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => {
+ const unsupported: PeerLinkClientPairingResult = {
+ type: "unsupported",
+ reason: "link_access",
+ ...target,
+ };
+ const manual = (host: string | null) => ({
+ outcome: { type: "manual", label: "VM", host },
+ pairs: [],
+ });
+ expect(await connect(unsupported, [tailnet])).toEqual(manual(tailnet));
+ // An address the user can correct beats an empty field.
+ expect(await connect(unsupported, [])).toEqual(manual(lan));
+ expect(await connect({ ...unsupported, urls: [] }, [])).toEqual(manual(null));
+ // The linking environment never answered, so only the client's own name is known.
+ expect((await connect(null, [lan])).outcome).toEqual({
+ type: "manual",
+ label: "vm (saved name)",
+ host: null,
+ });
+ // The one-time pairing was refused where it was redeemed.
+ expect((await connect(credential, [lan], false)).outcome).toEqual({
+ type: "manual",
+ label: "VM",
+ host: lan,
+ });
+ });
+});
diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts
index a5316a99008b7..15364cddf54ea 100644
--- a/packages/client-runtime/src/linkedThread.ts
+++ b/packages/client-runtime/src/linkedThread.ts
@@ -3,6 +3,7 @@ import type {
OrchestrationV2ThreadHistoryPage,
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadStreamItem,
+ PeerLinkClientPairingResult,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -56,6 +57,46 @@ export function resolveLinkedThreadOpen(input: {
return input.own === undefined ? "unavailable" : "direct";
}
+export type LinkedEnvironmentConnection =
+ /** This client paired with the linked environment and saved it. */
+ | { readonly type: "connected" }
+ /** No address the linking environment knows answers from this device. */
+ | { readonly type: "unreachable"; readonly label: string }
+ /** The user pairs with a code of their own, in the add-environment flow, with this filled in. */
+ | { readonly type: "manual"; readonly label: string; readonly host: string | null };
+
+/**
+ * Connects this client to a linked environment. The linking environment asks it for a one-time
+ * pairing over a full-access link, and the client redeems that at an address it can reach itself.
+ * Anything short of that leaves the user to pair by hand.
+ */
+export async function connectLinkedEnvironment(options: {
+ readonly label: string;
+ /** Asks the linking environment for a pairing; null when it could not answer. */
+ readonly requestPairing: () => Promise;
+ /** Whether an address answers this device as the linked environment. */
+ readonly reaches: (host: string) => Promise;
+ /** Pairs at `host` with the one-time credential and saves the environment. */
+ readonly pair: (input: {
+ readonly host: string;
+ readonly pairingCode: string;
+ }) => Promise;
+}): Promise {
+ const pairing = await options.requestPairing();
+ if (pairing === null) return { type: "manual", label: options.label, host: null };
+ const { label, urls } = pairing;
+ // Asked together, taken in the linking environment's order of preference.
+ const answers = await Promise.all(urls.map((url) => options.reaches(url)));
+ const host = urls.find((_, index) => answers[index]) ?? null;
+ if (pairing.type === "unsupported") {
+ return { type: "manual", label, host: host ?? urls[0] ?? null };
+ }
+ if (host === null) return { type: "unreachable", label };
+ return (await options.pair({ host, pairingCode: pairing.credential }))
+ ? { type: "connected" }
+ : { type: "manual", label, host };
+}
+
const hasStringField = (value: unknown, key: K): value is Record =>
typeof value === "object" &&
value !== null &&
diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts
index fe6579d9d0c75..0f76e9cfb3dea 100644
--- a/packages/client-runtime/src/state/peerLinks.ts
+++ b/packages/client-runtime/src/state/peerLinks.ts
@@ -115,6 +115,15 @@ export function createPeerLinkEnvironmentAtoms(
tag: WS_METHODS.peerLinksThreadItem,
idleTtlMs: 0,
}),
+ /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */
+ pairClient: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:peer-links:pair-client",
+ tag: WS_METHODS.peerLinksPairClient,
+ concurrency: {
+ mode: "singleFlight",
+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]),
+ },
+ }),
// An agent's link card. One answer per card at a time.
answerRequest: createEnvironmentRpcCommand(runtime, {
label: "environment-data:peer-links:answer-request",
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 0b6164871a0ad..47f24f576735e 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -86,6 +86,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
// A link lets every agent here reach the other environment: Settings' bar.
[WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope,
+ [WS_METHODS.peerLinksPairClient]: AuthAccessWriteScope,
} as const;
export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index b1a4c9ea18fcd..8ccdc7293a6e1 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -191,6 +191,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Serves a thread's stream, history pages and item detail to a link's session
(`PEER_LINK_THREAD_STREAM_ROUTE`), so a client of the linking environment can read it. */
linkThreadStream: Schema.optionalKey(Schema.Boolean),
+ /** A full-access link can ask this server for a one-time pairing credential for a client
+ of the linking environment. Absent on servers from before it. */
+ linkClientPairing: Schema.optionalKey(Schema.Boolean),
/** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */
mcpApprovalCodes: Schema.optionalKey(Schema.Boolean),
peerLinkPairingCodes: Schema.optionalKey(Schema.Boolean),
diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts
index c9a348efa72e8..fa51a25a1110b 100644
--- a/packages/contracts/src/environmentHttp.ts
+++ b/packages/contracts/src/environmentHttp.ts
@@ -70,6 +70,7 @@ import {
EnvironmentSpeechStatus,
EnvironmentSpeechTranscriptionResult,
} from "./speech.ts";
+import { PeerLinkClientPairingCredential, PeerLinkClientPairingRequest } from "./peerLink.ts";
import { SecretReference } from "./secretReference.ts";
import {
OrchestrationV2ShellHttpSnapshot,
@@ -1052,6 +1053,23 @@ class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
}),
) {}
+/**
+ * What a linking environment asks of this one over its link, outside `/mcp`. The handler accepts
+ * only a peer link's own session, so no agent's tool list ever carries it.
+ */
+class EnvironmentPeerLinkHttpApi extends HttpApiGroup.make("peerLink").add(
+ HttpApiEndpoint.post("clientPairing", "/api/peer-link/client-pairing", {
+ headers: OptionalBearerHeaders,
+ payload: PeerLinkClientPairingRequest,
+ success: PeerLinkClientPairingCredential,
+ error: [
+ EnvironmentHttpUnauthorizedError,
+ EnvironmentHttpForbiddenError,
+ EnvironmentHttpInternalServerError,
+ ],
+ }),
+) {}
+
// Path tokens and optional body signatures authenticate webhooks; read raw bytes to verify signatures.
const WebhookParams = Schema.Struct({
hookId: TrimmedNonEmptyString,
@@ -1081,4 +1099,5 @@ export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentProjectsHttpApi)
.add(EnvironmentVoiceHttpApi)
.add(EnvironmentConnectHttpApi)
- .add(EnvironmentWebhooksHttpApi) {}
+ .add(EnvironmentWebhooksHttpApi)
+ .add(EnvironmentPeerLinkHttpApi) {}
diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts
index bf25a34e07cf7..3b367c04eaecb 100644
--- a/packages/contracts/src/peerLink.ts
+++ b/packages/contracts/src/peerLink.ts
@@ -1,6 +1,6 @@
import * as Schema from "effect/Schema";
-import { AuthMcpClientAccess } from "./auth.ts";
+import { AuthEnvironmentScope, AuthMcpClientAccess } from "./auth.ts";
import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
/**
@@ -156,6 +156,60 @@ export class PeerLinkThreadReadError extends Schema.TaggedError