TypeScript
feat(web,mobile): linked environments in Connections (#16698)
Julius Marmingea6676f9a13a6
diff --git a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsxindex 6192b53301c..1c89305b8fd 100644--- a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx+++ b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx@@ -11,6 +11,7 @@ import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";import { useRemoteConnections } from "../../state/use-remote-environment-registry";import { LocalEnvironmentList } from "./LocalEnvironmentList";import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";+import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection";export function ConnectionsRouteScreen() {const {@@ -69,6 +70,15 @@ export function ConnectionsRouteScreen() {onSetEnabled={onSetEnvironmentEnabled}onUpdate={onUpdateEnvironment}/>+ {connectedEnvironments+ .filter((environment) => environment.connectionState === "connected")+ .map((environment) => (+ <LinkedEnvironmentsSection+ key={environment.environmentId}+ environmentId={environment.environmentId}+ environmentLabel={environment.environmentLabel}+ />+ ))}<PullRequestRoutingSettings /></ScrollView></View>diff --git a/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsxnew file mode 100644index 00000000000..66dd7dfd8f4--- /dev/null+++ b/apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx@@ -0,0 +1,78 @@+import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";+import { useFocusEffect } from "@react-navigation/native";+import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import { useCallback, useState } from "react";+import { AppState, View } from "react-native";++import { AppText as Text } from "../../components/ui/AppText";+import { useEnvironmentServerConfig } from "../../state/entities";+import { peerLinkEnvironment } from "../../state/peerLinks";+import { useEnvironmentQuery } from "../../state/query";+import { useEnvironmentScope } from "../../state/session";+import { SettingsSection } from "../settings/components/SettingsSection";++export function LinkedEnvironmentsSection(props: {+ readonly environmentId: EnvironmentId;+ readonly environmentLabel: string;+}) {+ const config = useEnvironmentServerConfig(props.environmentId);+ const canRead = useEnvironmentScope(props.environmentId, AuthAccessReadScope);+ const supported = canRead && config?.environment.capabilities.peerLinks === true;+ const links = useEnvironmentQuery(+ supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null,+ );+ const [nowMs, setNowMs] = useState(Date.now);+ const hasLinks = supported && (links.data?.links.length ?? 0) > 0;+ useFocusEffect(+ useCallback(() => {+ if (!hasLinks) return;+ const updateNow = () => setNowMs(Date.now());+ updateNow();+ const timer = setInterval(updateNow, 60_000);+ const subscription = AppState.addEventListener("change", (state) => {+ if (state === "active") updateNow();+ });+ return () => {+ clearInterval(timer);+ subscription.remove();+ };+ }, [hasLinks]),+ );+ if (!supported || links.error || !links.data || links.data.links.length === 0) return null;+ const now = DateTime.makeUnsafe(nowMs);+ return (+ <View className="mt-5 gap-3">+ <SettingsSection title={`Linked from ${props.environmentLabel}`}>+ {links.data.links.map((link) => {+ const health = peerLinkHealth(link, now);+ const status =+ health.kind === "expired"+ ? "Expired. Link it again with a new pairing code."+ : health.kind === "unreachable"+ ? (health.detail ?? "Not answering right now.")+ : health.kind === "failing"+ ? health.detail+ : health.expiresInDays !== null+ ? `Expires in ${health.expiresInDays} ${health.expiresInDays === 1 ? "day" : "days"}`+ : "Reachable";+ return (+ <View key={link.environmentId} className="gap-0.5 p-4">+ <Text className="text-base font-t3-bold text-foreground">{link.label}</Text>+ <Text+ className={+ health.kind === "reachable" && health.expiresInDays === null+ ? "text-xs text-foreground-muted"+ : "text-xs text-danger-foreground"+ }+ numberOfLines={2}+ >+ {status}+ </Text>+ </View>+ );+ })}+ </SettingsSection>+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex ed1a9819d26..2233a30441a 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -489,6 +489,7 @@ function ThreadRouteContent(const headerSubtitle = [selectedThreadProject?.title ?? null,selectedEnvironmentConnection?.environmentLabel ?? null,+ selectedThread?.linkOrigin ? `From ${selectedThread.linkOrigin.label}` : null,].filter(Boolean).join(" · ");diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.tsnew file mode 100644index 00000000000..66a29130053--- /dev/null+++ b/apps/mobile/src/state/peerLinks.ts@@ -0,0 +1,5 @@+import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";++import { connectionAtomRuntime } from "../connection/runtime";++export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex a8cdbccf68f..35e2bd4776f 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -5,7 +5,6 @@ import {authScopeRequiredResponse,AssetCreateUrlInput,AuthAccessReadScope,- AuthAccessWriteScope,ServerSettingsPatch,ProviderInstanceMutation,requiredScopesForServerSettingsPatch,@@ -88,8 +87,6 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,[WS_METHODS.peerLinksList]: AuthAccessReadScope,- [WS_METHODS.peerLinksLink]: AuthAccessWriteScope,- [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,[WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 19726720b14..7bb833cb905 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -3159,6 +3159,7 @@ export default function ChatView(props: ChatViewProps) {activeThreadId={activeThread.id}isServerThread={isServerThread}activeThreadTitle={activeThread.title}+ activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}activeProject={activeProject ?? null}parentThreadLink={parentThreadLink}onOpenThread={onOpenRelatedThreadStable}diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsxindex f70b4454873..3ca5160e277 100644--- a/apps/web/src/components/auth/ConnectAgentSurface.tsx+++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx@@ -24,7 +24,7 @@ import { RadioGroup } from "../ui/radio-group";import { Spinner } from "../ui/spinner";import { AuthSurfaceShell } from "./AuthSurfaceShell";-const accessConfig: Record<+export const accessConfig: Record<AuthMcpClientAccess,{ readonly label: string; readonly description: string; readonly icon: LucideIcon }> = {@@ -279,7 +279,7 @@ function ConnectAgentHeading({);}-function AccessOption({+export function AccessOption({access,selected,}: {diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsxindex 6add111820f..116eed2c066 100644--- a/apps/web/src/components/chat/ChatHeader.tsx+++ b/apps/web/src/components/chat/ChatHeader.tsx@@ -19,6 +19,7 @@ import {type MouseEvent as ReactMouseEvent,} from "react";import { isTrailingDoubleClick } from "../Sidebar.logic";+import { Badge } from "../ui/badge";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { toastManager } from "../ui/toast";import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";@@ -45,6 +46,7 @@ interface ChatHeaderProps {activeThreadEnvironmentId: EnvironmentId;activeThreadId: ThreadId;activeThreadTitle: string;+ activeThreadLinkOrigin?: string | null | undefined;isServerThread: boolean;activeProject: EnvironmentProject | null;parentThreadLink: { threadId: ThreadId; title: string } | null;@@ -70,6 +72,7 @@ export const ChatHeader = memo(function ChatHeader({activeThreadEnvironmentId,activeThreadId,activeThreadTitle,+ activeThreadLinkOrigin,isServerThread,activeProject,parentThreadLink,@@ -406,6 +409,16 @@ export const ChatHeader = memo(function ChatHeader({<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup></Tooltip>)}+ {renamingTitle === null && activeThreadLinkOrigin ? (+ <Tooltip>+ <TooltipTrigger render={<Badge variant="info" size="sm" />}>+ From {activeThreadLinkOrigin}+ </TooltipTrigger>+ <TooltipPopup side="top">+ Started by an agent on {activeThreadLinkOrigin} through a linked environment.+ </TooltipPopup>+ </Tooltip>+ ) : null}</WorkspaceBreadcrumbItem></WorkspaceBreadcrumb>{isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex daa240cbf68..06fba368d28 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -36,6 +36,8 @@ import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";import { searchableSetting } from "./settingsSearch";import { EnvironmentIconMenu } from "./EnvironmentIconPicker";import { FoldedSettingsSection } from "./FoldedSettingsSection";+import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";+import { usePeerLinkHosts } from "~/state/peerLinks";import { LoadBalancingSettings } from "./LoadBalancingSettings";import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";import { Input } from "../ui/input";@@ -156,6 +158,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |const desktopBridge = window.desktopBridge;const { environments } = useEnvironments();const primaryEnvironment = usePrimaryEnvironment();+ const peerLinkHosts = usePeerLinkHosts();const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {reportFailure: false,@@ -1533,6 +1536,14 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |}}/>) : null}+ {peerLinkHosts.map((environment, index) => (+ <LinkedEnvironmentsSettings+ key={environment.environmentId}+ environmentId={environment.environmentId}+ environmentLabel={peerLinkHosts.length > 1 ? environment.label : null}+ isSearchTarget={index === 0}+ />+ ))}<LoadBalancingSettings environments={loadBalancingEnvironments} /><PullRequestRoutingSettings environments={loadBalancingEnvironments} /></SettingsPageContainer>diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsxnew file mode 100644index 00000000000..c4804281f54--- /dev/null+++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx@@ -0,0 +1,283 @@+import { useAtomValue } from "@effect/atom-react";+import { AuthMcpClientAccess, type EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";+import * as DateTime from "effect/DateTime";+import { PlusIcon } from "lucide-react";+import { useId, useState } from "react";++import { requestConfirmDialog } from "~/confirmDialog";+import { peerLinkEnvironment } from "~/state/peerLinks";+import { useEnvironmentQuery } from "~/state/query";+import { useAtomCommand } from "~/state/use-atom-command";+import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";+import { ConnectionStatusDot } from "../ConnectionStatusDot";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogClose,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+ DialogTrigger,+} from "../ui/dialog";+import { Input } from "../ui/input";+import { RadioGroup } from "../ui/radio-group";+import { stackedThreadToast, toastManager } from "../ui/toast";+import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";+import { SettingsRow, SettingsSection } from "./settingsLayout";+import { useNowMinute } from "../../hooks/useNowMinute";+import { searchableSetting } from "./settingsSearch";++const failureToast = (title: string, description: string) =>+ toastManager.add(stackedThreadToast({ type: "error", title, description }));++export function LinkedEnvironmentsSettings({+ environmentId,+ environmentLabel,+ isSearchTarget,+}: {+ readonly environmentId: EnvironmentId;+ readonly environmentLabel: string | null;+ readonly isSearchTarget: boolean;+}) {+ const links = useEnvironmentQuery(peerLinkEnvironment.list({ environmentId, input: {} }));+ const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(environmentId));+ const search = searchableSetting("linked-environments");+ return (+ <SettingsSection+ {...(isSearchTarget ? { id: search.id } : {})}+ title={environmentLabel === null ? search.title : `${search.title} · ${environmentLabel}`}+ headerAction={canLink ? <LinkEnvironmentAction environmentId={environmentId} /> : null}+ >+ {links.error ? (+ <SettingsRow title="Could not load linked environments" description={links.error} />+ ) : !links.data ? (+ <SettingsRow title="Loading linked environments…" role="status" />+ ) : links.data.links.length === 0 ? (+ <SettingsRow+ title="No linked environments"+ description="Link another machine running T3 Code, such as a VPS, so agents here can launch and drive threads there."+ />+ ) : (+ links.data.links.map((link) => (+ <LinkedEnvironmentRow+ key={link.environmentId}+ environmentId={environmentId}+ link={link}+ />+ ))+ )}+ </SettingsSection>+ );+}++function LinkedEnvironmentRow({+ environmentId,+ link,+}: {+ readonly environmentId: EnvironmentId;+ readonly link: PeerLinkSummary;+}) {+ const nowMinute = useNowMinute();+ const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute));+ const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: "unlink environment" });+ const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId));+ const [busy, setBusy] = useState(false);+ const forget = async () => {+ const confirmed = await (requestConfirmDialog(+ `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Connections to end the session there too.`,+ { variant: "destructive" },+ ) ?? Promise.resolve(false));+ if (!confirmed) return;+ setBusy(true);+ const result = await unlink({ environmentId, input: { environmentId: link.environmentId } });+ setBusy(false);+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ failureToast("Could not forget the link", String(squashAtomCommandFailure(result)));+ }+ };+ const status =+ health.kind === "expired"+ ? "Expired. Link it again with a new pairing code."+ : health.kind === "unreachable"+ ? (health.detail ?? "Not answering right now.")+ : health.kind === "failing"+ ? health.detail+ : health.expiresInDays !== null+ ? `Expires in ${health.expiresInDays} ${health.expiresInDays === 1 ? "day" : "days"}. Link it again to renew.`+ : "Reachable";+ return (+ <div className={ITEM_ROW_CLASSNAME}>+ <div className={ITEM_ROW_INNER_CLASSNAME}>+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex min-h-5 items-center gap-1.5">+ <ConnectionStatusDot+ tooltipText={status}+ dotClassName={+ health.kind === "reachable"+ ? health.expiresInDays === null+ ? "bg-success"+ : "bg-warning"+ : health.kind === "expired" || health.kind === "failing"+ ? "bg-destructive"+ : "bg-muted-foreground/30"+ }+ pingClassName={null}+ />+ <h3 className="text-sm font-medium text-foreground">{link.label}</h3>+ </div>+ <p className="text-xs text-muted-foreground">+ {accessConfig[link.access].label} · {status}+ </p>+ <p className="truncate text-xs text-muted-foreground/80">{link.urls.join(", ")}</p>+ </div>+ {canUnlink ? (+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">+ <Button+ size="xs"+ variant="destructive-outline"+ disabled={busy}+ onClick={() => void forget()}+ >+ {busy ? "Forgetting…" : "Forget"}+ </Button>+ </div>+ ) : null}+ </div>+ </div>+ );+}++function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {+ const [open, setOpen] = useState(false);+ const [url, setUrl] = useState("");+ const [pairingCode, setPairingCode] = useState("");+ const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");+ const [busy, setBusy] = useState(false);+ const formId = useId();+ const accessLabelId = `${formId}-access`;+ const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" });+ const handleOpenChange = (next: boolean) => {+ setOpen(next);+ if (!next) {+ setUrl("");+ setPairingCode("");+ setAccess("approval-required");+ }+ };+ const submit = async () => {+ setBusy(true);+ const result = await link({+ environmentId,+ input: { url: url.trim(), pairingCode: pairingCode.trim(), access },+ });+ setBusy(false);+ if (result._tag === "Success") {+ toastManager.add({ type: "success", title: `Linked ${result.value.label}` });+ handleOpenChange(false);+ } else if (!isAtomCommandInterrupted(result)) {+ failureToast("Could not link the environment", String(squashAtomCommandFailure(result)));+ }+ };+ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!next && busy) return;+ handleOpenChange(next);+ }}+ >+ <DialogTrigger+ render={+ <Button size="xs" variant="default">+ <PlusIcon className="size-3" />+ Link+ </Button>+ }+ />+ <DialogPopup className="max-w-md">+ <DialogHeader>+ <DialogTitle>Link an environment</DialogTitle>+ <DialogDescription>+ Agents here can then launch, message and wait on threads there. It appears in that+ environment's Connections, where it can be revoked.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel>+ <form+ id={formId}+ className="space-y-4"+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ >+ <label className="block space-y-1.5">+ <span className="block text-xs font-medium text-foreground">Address</span>+ <Input+ value={url}+ onChange={(event) => setUrl(event.target.value)}+ placeholder="https://box.example.ts.net"+ disabled={busy}+ autoFocus+ nativeInput+ spellCheck={false}+ />+ </label>+ <label className="block space-y-1.5">+ <span className="block text-xs font-medium text-foreground">Pairing code</span>+ <Input+ value={pairingCode}+ onChange={(event) => setPairingCode(event.target.value)}+ placeholder="From that environment's Connections, or t3 pair there"+ disabled={busy}+ autoComplete="one-time-code"+ nativeInput+ spellCheck={false}+ />+ </label>+ <div className="space-y-2">+ <span id={accessLabelId} className="block text-xs font-medium">+ What agents here may do there+ </span>+ <RadioGroup+ aria-labelledby={accessLabelId}+ disabled={busy}+ value={access}+ onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}+ >+ {AuthMcpClientAccess.literals.map((option) => (+ <AccessOption key={option} access={option} selected={option === access} />+ ))}+ </RadioGroup>+ <p className="text-xs text-muted-foreground">+ An agent never gets more access there than its own mode here. Below full access, it+ can change only threads this link started, not that environment's own threads,+ projects or settings.+ </p>+ </div>+ </form>+ </DialogPanel>+ <DialogFooter variant="bare">+ <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>+ Cancel+ </DialogClose>+ <Button+ form={formId}+ type="submit"+ disabled={busy || url.trim().length === 0 || pairingCode.trim().length === 0}+ >+ {busy ? "Linking…" : "Link"}+ </Button>+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.tsindex f10dfbd738c..9f5fc6ac4ad 100644--- a/apps/web/src/components/settings/settingsSearch.test.ts+++ b/apps/web/src/components/settings/settingsSearch.test.ts@@ -122,10 +122,37 @@ describe("searchSettings", () => {"auto-settle-inactive-threads","auto-settle-merged-threads","days-before-auto-settle",+ "linked-environments",]);expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]);});+ it("finds linked environments on a remote host without local maintenance access", () => {+ const availability = {+ hasCloudPublicConfig: false,+ hasEnvironment: true,+ hasProviderSettingsEnvironment: true,+ hasMacProviderSettingsEnvironment: false,+ canManageLocalBackend: false,+ localEnvironmentDisabled: true,+ isWslSettingsRowVisible: false,+ hasThreadAutoSettlement: false,+ };+ const results = (hasPeerLinkHost: boolean) =>+ searchSettings(+ "linked environments",+ filterAvailableSettingsSearchItems({ ...availability, hasPeerLinkHost }),+ );+ expect(results(false).map((item) => item.id)).not.toContain("linked-environments");+ expect(results(true)).toContainEqual(+ expect.objectContaining({+ id: "linked-environments",+ to: "/settings/connections",+ targetId: "linked-environments",+ }),+ );+ });+it("finds keybinding commands by label, command id, and default key", () => {expect(searchSettings("toggle sidebar")[0]?.id).toBe("keybinding-sidebar.toggle");expect(searchSettings("sidebar.toggle")[0]?.id).toBe("keybinding-sidebar.toggle");diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex 5840566dc1c..67318a1ee7c 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -65,6 +65,7 @@ export interface SettingsSearchItem {readonly localEnvironmentOnly?: boolean;readonly wslAvailableOnly?: boolean;readonly managedTunnelOnly?: boolean;+ readonly peerLinksOnly?: boolean;readonly secondary?: boolean;readonly requiresThreadAutoSettlement?: boolean;}@@ -79,6 +80,7 @@ export interface SettingsSearchAvailability {readonly isWslSettingsRowVisible: boolean;readonly hasThreadAutoSettlement: boolean;readonly managedTunnelActive?: boolean;+ readonly hasPeerLinkHost?: boolean;}export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {@@ -1072,6 +1074,14 @@ export const SETTINGS_SEARCH_ITEMS = ["connections server backend local remote access administrative permissions scope pairing links qr code authorized clients sessions revoke endpoint",],},+ {+ id: "linked-environments",+ peerLinksOnly: true,+ title: "Linked environments",+ to: "/settings/connections",+ targetId: "linked-environments",+ searchTerms: ["link peer another machine vps agents work there handoff pairing code"],+ },{id: "remote-environments",title: "Environments",@@ -1260,7 +1270,8 @@ export function filterAvailableSettingsSearchItems((!item.localEnvironmentOnly || !availability.localEnvironmentDisabled) &&(!item.wslAvailableOnly || availability.isWslSettingsRowVisible) &&(!item.requiresThreadAutoSettlement || availability.hasThreadAutoSettlement) &&- (!item.managedTunnelOnly || availability.managedTunnelActive === true),+ (!item.managedTunnelOnly || availability.managedTunnelActive === true) &&+ (!item.peerLinksOnly || availability.hasPeerLinkHost === true),);}diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.tsindex 20c5703d342..712c4d87d70 100644--- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts+++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts@@ -6,6 +6,7 @@ import { isElectron } from "~/env";import { isLocalEnvironmentDisabled } from "~/localEnvironment";import { desktopWslStateAtom } from "~/state/desktopWslState";import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";+import { usePeerLinkHosts } from "~/state/peerLinks";import { useEnvironmentQuery } from "~/state/query";import { useEnvironmentScope } from "~/state/session";import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";@@ -42,6 +43,7 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearchgetThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0;const primaryEnvironmentId = usePrimaryEnvironmentId();const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope);+ const hasPeerLinkHost = usePeerLinkHosts().length > 0;const cloudLinkState = usePrimaryCloudLinkState().data;// Same fallback as the Connections row: older servers imply a tunnel from `linked`.const managedTunnelActive =@@ -66,5 +68,6 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearchisWslSettingsRowVisible: wslSettingsRowVisible,hasThreadAutoSettlement,managedTunnelActive,+ hasPeerLinkHost,});}diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.tsnew file mode 100644index 00000000000..c3b6a16d124--- /dev/null+++ b/apps/web/src/state/peerLinks.ts@@ -0,0 +1,19 @@+import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";+import { AuthAccessReadScope } from "@t3tools/contracts";++import { connectionAtomRuntime } from "../connection/runtime";+import { useEnvironments } from "./environments";+import { useEnvironmentsWithScope } from "./session";++export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);++export function usePeerLinkHosts() {+ const { environments } = useEnvironments();+ const supported = environments.filter(+ (environment) =>+ environment.connection.phase === "connected" &&+ environment.serverConfig?.environment.capabilities.peerLinks === true,+ );+ const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);+ return supported.filter((environment) => readable.has(environment.environmentId));+}diff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 4b9acbeecaf..6d6bc234290 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -247,6 +247,28 @@ Claude Code, Codex, ChatGPT and other agents T3 Code did not start can drivethreads on an environment through its MCP server. See[outside agents](./outside-agents.md) for setup.+## Link another environment++Link two machines, such as your laptop and a VPS, and agents on one can work on+the other: launch, message, wait on and stop its threads, answer their+questions, and manage its queues, projects and scheduled tasks. On the machine+you will work from, open **Settings → Connections → Linked environments**,+choose **Link**, and enter the other machine's address and a pairing code from+it. From a terminal, use+`t3 environment link <address> --pairing-code <code> --access <mode>`.++- The access you pick is the most agents from this machine may do there. An+ agent also never gets more there than its own mode here.+- Threads a link starts are marked **From** and this machine's name there.+- A full-access link works there like that machine's own agents. Below full+ access, the link's agents can change only threads it started, not that+ machine's own threads, projects or settings, and they skip its project setup+ scripts.+- The link shows up in that machine's **Settings → Connections** like any+ outside agent. Revoke it there to end it. **Forget** on this machine only+ removes it here.+- Links last 30 days. Link again with a new pairing code to renew one.+## Manage or revoke accessOn the host, **Settings → Sharing & access** lets authorized administrators creatediff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 9719f593607..949ef95e0fb 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -207,6 +207,10 @@"types": "./src/state/deviceHubAccess.ts","default": "./src/state/deviceHubAccess.ts"},+ "./state/peerLinks": {+ "types": "./src/state/peerLinks.ts",+ "default": "./src/state/peerLinks.ts"+ },"./state/preview": {"types": "./src/state/preview.ts","default": "./src/state/preview.ts"diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.tsindex 09927e38398..86fa9563653 100644--- a/packages/client-runtime/src/state/commandPermissions.test.ts+++ b/packages/client-runtime/src/state/commandPermissions.test.ts@@ -7,6 +7,8 @@ import type { RpcSession } from "../rpc/session.ts";import { describe, expect, it } from "@effect/vitest";import { vi } from "vite-plus/test";import {+ AuthAccessReadScope,+ AuthAccessWriteScope,AuthOrchestrationOperateScope,AuthOrchestrationReadScope,AuthPreviewOperateScope,@@ -17,8 +19,10 @@ import {ScheduledTaskId,WS_METHODS,type AuthSessionState,+ type PeerLinkSummary,} from "@t3tools/contracts";import * as Cause from "effect/Cause";+import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";@@ -26,6 +30,8 @@ import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";import { EnvironmentRegistry } from "../connection/registry.ts";import { createCommandPermissions } from "./commandPermissions.ts";import { createEnvironmentRpcCommand } from "./runtime.ts";+import { AVAILABLE_CONNECTION_STATE } from "../connection/model.ts";+import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts";vi.mock("./session.ts", () => ({createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),@@ -291,6 +297,132 @@ it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"]),);+it.effect(+ "refreshes linked environments after permitted writes and blocks a read-only session",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const registry = yield* setup;+ const peer: PeerLinkSummary = {+ environmentId: EnvironmentId.make("peer"),+ label: "Box",+ urls: ["https://box.example.test"],+ access: "auto",+ linkedAt: DateTime.makeUnsafe("2026-10-01T12:00:00Z"),+ expiresAt: DateTime.makeUnsafe("2026-10-31T12:00:00Z"),+ lastReachedAt: null,+ lastError: null,+ status: "reachable",+ };+ let links: ReadonlyArray<PeerLinkSummary> = [];+ const client = {+ [WS_METHODS.peerLinksList]: () => Effect.sync(() => ({ links })),+ [WS_METHODS.peerLinksLink]: vi.fn(() =>+ Effect.sync(() => {+ links = [peer];+ return peer;+ }),+ ),+ [WS_METHODS.peerLinksUnlink]: vi.fn(() =>+ Effect.sync(() => {+ links = [];+ return { removed: true };+ }),+ ),+ };+ const supervisor = {+ target: { environmentId: env },+ session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)),+ state: yield* SubscriptionRef.make({+ ...AVAILABLE_CONNECTION_STATE,+ phase: "connected" as const,+ }),+ } as EnvironmentSupervisor["Service"];+ const peerRuntime = Atom.runtime(+ Layer.succeed(EnvironmentRegistry, {+ run: (id, effect) => {+ expect(id).toBe(env);+ return Effect.provideService(effect, EnvironmentSupervisor, supervisor);+ },+ followStream: (id, stream) => {+ expect(id).toBe(env);+ return Stream.provideService(stream, EnvironmentSupervisor, supervisor);+ },+ } as EnvironmentRegistry["Service"]),+ );+ const peerLinks = createPeerLinkEnvironmentAtoms(peerRuntime);+ const list = peerLinks.list({ environmentId: env, input: {} });+ registry.mount(list);+ const readLinks = AtomRegistry.getResult(registry, list, { suspendOnWaiting: true });+ const setAccess = (writable: boolean) =>+ registry.set(+ sessions(env),+ AsyncResult.success({+ ...grant(false),+ scopes: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],+ permissions: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],+ }),+ );+ registry.mount(sessions(other));+ registry.set(+ sessions(other),+ AsyncResult.success({+ ...grant(false),+ scopes: [AuthAccessWriteScope],+ permissions: [AuthAccessWriteScope],+ }),+ );+ setAccess(false);+ expect(yield* readLinks).toEqual({ links: [] });+ const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access };+ const link = Effect.promise(() =>+ peerLinks.link.run(registry, { environmentId: env, input: linkInput }),+ );+ const unlink = Effect.promise(() =>+ peerLinks.unlink.run(registry, {+ environmentId: env,+ input: { environmentId: peer.environmentId },+ }),+ );+ expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(false);+ const deniedLink = yield* link;+ expect(deniedLink._tag).toBe("Failure");+ if (deniedLink._tag === "Failure") {+ expect(Cause.squash(deniedLink.cause)).toMatchObject({+ _tag: "EnvironmentAuthorizationError",+ requiredPermission: AuthAccessWriteScope,+ });+ }+ expect(client[WS_METHODS.peerLinksLink]).not.toHaveBeenCalled();+ setAccess(true);+ expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(true);+ expect((yield* link)._tag).toBe("Success");+ expect(client[WS_METHODS.peerLinksLink]).toHaveBeenCalledExactlyOnceWith(linkInput);+ expect(yield* readLinks).toEqual({ links: [peer] });++ setAccess(false);+ expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(false);+ const deniedUnlink = yield* unlink;+ expect(deniedUnlink._tag).toBe("Failure");+ if (deniedUnlink._tag === "Failure") {+ expect(Cause.squash(deniedUnlink.cause)).toMatchObject({+ _tag: "EnvironmentAuthorizationError",+ requiredPermission: AuthAccessWriteScope,+ });+ }+ expect(client[WS_METHODS.peerLinksUnlink]).not.toHaveBeenCalled();+ expect(yield* readLinks).toEqual({ links: [peer] });+ setAccess(true);+ expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(true);+ expect((yield* unlink)._tag).toBe("Success");+ expect(client[WS_METHODS.peerLinksUnlink]).toHaveBeenCalledExactlyOnceWith({+ environmentId: peer.environmentId,+ });+ expect(yield* readLinks).toEqual({ links: [] });+ }),+ ),+);+it.effect("honors exact empty permissions and preserves legacy parent grants", () =>Effect.scoped(Effect.gen(function* () {diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex d772989f23e..9dc72dc4930 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -147,6 +147,7 @@ export interface EnvironmentThreadShell {readonly worktreePath: string | null;readonly lineage: OrchestrationV2ThreadShell["lineage"];readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];+ readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];readonly latestRun: ThreadRunSummary | null;readonly runtime: ThreadRuntimeSummary | null;@@ -298,6 +299,7 @@ export function presentThreadShell(branchPullRequest: thread.branchPullRequest ?? null,lineage: thread.lineage,forkedFrom: thread.forkedFrom,+ linkOrigin: thread.linkOrigin ?? null,activeProviderThreadId: thread.activeProviderThreadId,latestRun,runtime,diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.tsnew file mode 100644index 00000000000..6e65f62eeb7--- /dev/null+++ b/packages/client-runtime/src/state/peerLinks.ts@@ -0,0 +1,57 @@+import { type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import { Atom } from "effect/reactivity";++import type { EnvironmentRegistry } from "../connection/registry.ts";+import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";++export function createPeerLinkEnvironmentAtoms<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,+) {+ const list = createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:peer-links:list",+ tag: WS_METHODS.peerLinksList,+ // Listing probes every linked environment, so a list stays fresh briefly.+ staleTimeMs: 10_000,+ });+ return {+ list,+ link: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:peer-links:link",+ tag: WS_METHODS.peerLinksLink,+ onSuccess: ({ environmentId }, registry) =>+ Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))),+ }),+ unlink: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:peer-links:unlink",+ tag: WS_METHODS.peerLinksUnlink,+ onSuccess: ({ environmentId }, registry) =>+ Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))),+ }),+ };+}++const EXPIRY_WARNING_DAYS = 5;++export type PeerLinkHealth =+ | { readonly kind: "reachable"; readonly expiresInDays: number | null }+ | { readonly kind: "unreachable"; readonly detail: string | null }+ | { readonly kind: "failing"; readonly detail: string }+ | { readonly kind: "expired" };++/**+ * Listing only checks that the peer answers, so a link whose last call failed+ * (the peer revoked it, say) is `failing` with the recorded reason; the next+ * successful call clears it.+ */+export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth {+ if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) {+ return { kind: "expired" };+ }+ if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError };+ if (link.lastError !== null) return { kind: "failing", detail: link.lastError };+ const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt)));+ return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null };+}diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.tsindex 3fda40a04a0..5ff35ad1334 100644--- a/packages/contracts/src/clientRpcPermissions.ts+++ b/packages/contracts/src/clientRpcPermissions.ts@@ -52,6 +52,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,// A guest link hands thread access to someone outside, like a pairing link.[WS_METHODS.guestShareCreate]: AuthAccessWriteScope,+ [WS_METHODS.peerLinksLink]: AuthAccessWriteScope,+ [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,} as const;export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;