The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 14:30 UTC
feat(web,mobile): linked environments in Connections (#16698)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 14:04 UTC
a6676f9a13a6363787cfba80edd7f696e6e9ae7e
20 files changed
+684
-6
apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx
+10
@@ -11,6 +11,7 @@ import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
11
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
12
import { LocalEnvironmentList } from "./LocalEnvironmentList";
13
import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";
14
+import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection";
15
16
export function ConnectionsRouteScreen() {
17
const {
@@ -69,6 +70,15 @@ export function ConnectionsRouteScreen() {
70
onSetEnabled={onSetEnvironmentEnabled}
71
onUpdate={onUpdateEnvironment}
72
/>
73
+ {connectedEnvironments
74
+ .filter((environment) => environment.connectionState === "connected")
75
+ .map((environment) => (
76
+ <LinkedEnvironmentsSection
77
+ key={environment.environmentId}
78
+ environmentId={environment.environmentId}
79
+ environmentLabel={environment.environmentLabel}
80
+ />
81
+ ))}
82
<PullRequestRoutingSettings />
83
</ScrollView>
84
</View>
apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
new
+78
@@ -0,0 +1,78 @@
1
+import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
2
+import { useFocusEffect } from "@react-navigation/native";
3
+import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";
4
+import * as DateTime from "effect/DateTime";
5
+import { useCallback, useState } from "react";
6
+import { AppState, View } from "react-native";
7
+
8
+import { AppText as Text } from "../../components/ui/AppText";
9
+import { useEnvironmentServerConfig } from "../../state/entities";
10
+import { peerLinkEnvironment } from "../../state/peerLinks";
11
+import { useEnvironmentQuery } from "../../state/query";
12
+import { useEnvironmentScope } from "../../state/session";
13
+import { SettingsSection } from "../settings/components/SettingsSection";
14
+
15
+export function LinkedEnvironmentsSection(props: {
16
+ readonly environmentId: EnvironmentId;
17
+ readonly environmentLabel: string;
18
+}) {
19
+ const config = useEnvironmentServerConfig(props.environmentId);
20
+ const canRead = useEnvironmentScope(props.environmentId, AuthAccessReadScope);
21
+ const supported = canRead && config?.environment.capabilities.peerLinks === true;
22
+ const links = useEnvironmentQuery(
23
+ supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null,
24
+ );
25
+ const [nowMs, setNowMs] = useState(Date.now);
26
+ const hasLinks = supported && (links.data?.links.length ?? 0) > 0;
27
+ useFocusEffect(
28
+ useCallback(() => {
29
+ if (!hasLinks) return;
30
+ const updateNow = () => setNowMs(Date.now());
31
+ updateNow();
32
+ const timer = setInterval(updateNow, 60_000);
33
+ const subscription = AppState.addEventListener("change", (state) => {
34
+ if (state === "active") updateNow();
35
+ });
36
+ return () => {
37
+ clearInterval(timer);
38
+ subscription.remove();
39
+ };
40
+ }, [hasLinks]),
41
+ );
42
+ if (!supported || links.error || !links.data || links.data.links.length === 0) return null;
43
+ const now = DateTime.makeUnsafe(nowMs);
44
+ return (
45
+ <View className="mt-5 gap-3">
46
+ <SettingsSection title={`Linked from ${props.environmentLabel}`}>
47
+ {links.data.links.map((link) => {
48
+ const health = peerLinkHealth(link, now);
49
+ const status =
50
+ health.kind === "expired"
51
+ ? "Expired. Link it again with a new pairing code."
52
+ : health.kind === "unreachable"
53
+ ? (health.detail ?? "Not answering right now.")
54
+ : health.kind === "failing"
55
+ ? health.detail
56
+ : health.expiresInDays !== null
57
+ ? `Expires in ${health.expiresInDays} ${health.expiresInDays === 1 ? "day" : "days"}`
58
+ : "Reachable";
59
+ return (
60
+ <View key={link.environmentId} className="gap-0.5 p-4">
61
+ <Text className="text-base font-t3-bold text-foreground">{link.label}</Text>
62
+ <Text
63
+ className={
64
+ health.kind === "reachable" && health.expiresInDays === null
65
+ ? "text-xs text-foreground-muted"
66
+ : "text-xs text-danger-foreground"
67
+ }
68
+ numberOfLines={2}
69
+ >
70
+ {status}
71
+ </Text>
72
+ </View>
73
+ );
74
+ })}
75
+ </SettingsSection>
76
+ </View>
77
+ );
78
+}
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+1
@@ -489,6 +489,7 @@ function ThreadRouteContent(
489
const headerSubtitle = [
490
selectedThreadProject?.title ?? null,
491
selectedEnvironmentConnection?.environmentLabel ?? null,
492
+ selectedThread?.linkOrigin ? `From ${selectedThread.linkOrigin.label}` : null,
493
]
494
.filter(Boolean)
495
.join(" · ");
apps/mobile/src/state/peerLinks.ts
new
+5
@@ -0,0 +1,5 @@
1
+import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
2
+
3
+import { connectionAtomRuntime } from "../connection/runtime";
4
+
5
+export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
apps/server/src/auth/RpcAuthorization.ts
-3
@@ -5,7 +5,6 @@ import {
5
authScopeRequiredResponse,
6
AssetCreateUrlInput,
7
AuthAccessReadScope,
8
- AuthAccessWriteScope,
8
ServerSettingsPatch,
9
ProviderInstanceMutation,
10
requiredScopesForServerSettingsPatch,
@@ -88,8 +87,6 @@ export const RPC_REQUIRED_SCOPES = {
87
[WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,
88
[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
89
[WS_METHODS.peerLinksList]: AuthAccessReadScope,
91
- [WS_METHODS.peerLinksLink]: AuthAccessWriteScope,
92
- [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
90
[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
91
[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
92
[WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,
apps/web/src/components/ChatView.tsx
+1
@@ -3159,6 +3159,7 @@ export default function ChatView(props: ChatViewProps) {
3159
activeThreadId={activeThread.id}
3160
isServerThread={isServerThread}
3161
activeThreadTitle={activeThread.title}
3162
+ activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}
3163
activeProject={activeProject ?? null}
3164
parentThreadLink={parentThreadLink}
3165
onOpenThread={onOpenRelatedThreadStable}
apps/web/src/components/auth/ConnectAgentSurface.tsx
+2
-2
@@ -24,7 +24,7 @@ import { RadioGroup } from "../ui/radio-group";
24
import { Spinner } from "../ui/spinner";
25
import { AuthSurfaceShell } from "./AuthSurfaceShell";
26
27
-const accessConfig: Record<
27
+export const accessConfig: Record<
28
AuthMcpClientAccess,
29
{ readonly label: string; readonly description: string; readonly icon: LucideIcon }
30
> = {
@@ -279,7 +279,7 @@ function ConnectAgentHeading({
279
);
280
}
281
282
-function AccessOption({
282
+export function AccessOption({
283
access,
284
selected,
285
}: {
apps/web/src/components/chat/ChatHeader.tsx
+13
@@ -19,6 +19,7 @@ import {
19
type MouseEvent as ReactMouseEvent,
20
} from "react";
21
import { isTrailingDoubleClick } from "../Sidebar.logic";
22
+import { Badge } from "../ui/badge";
23
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
24
import { toastManager } from "../ui/toast";
25
import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
@@ -45,6 +46,7 @@ interface ChatHeaderProps {
46
activeThreadEnvironmentId: EnvironmentId;
47
activeThreadId: ThreadId;
48
activeThreadTitle: string;
49
+ activeThreadLinkOrigin?: string | null | undefined;
50
isServerThread: boolean;
51
activeProject: EnvironmentProject | null;
52
parentThreadLink: { threadId: ThreadId; title: string } | null;
@@ -70,6 +72,7 @@ export const ChatHeader = memo(function ChatHeader({
72
activeThreadEnvironmentId,
73
activeThreadId,
74
activeThreadTitle,
75
+ activeThreadLinkOrigin,
76
isServerThread,
77
activeProject,
78
parentThreadLink,
@@ -406,6 +409,16 @@ export const ChatHeader = memo(function ChatHeader({
409
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
410
</Tooltip>
411
)}
412
+ {renamingTitle === null && activeThreadLinkOrigin ? (
413
+ <Tooltip>
414
+ <TooltipTrigger render={<Badge variant="info" size="sm" />}>
415
+ From {activeThreadLinkOrigin}
416
+ </TooltipTrigger>
417
+ <TooltipPopup side="top">
418
+ Started by an agent on {activeThreadLinkOrigin} through a linked environment.
419
+ </TooltipPopup>
420
+ </Tooltip>
421
+ ) : null}
422
</WorkspaceBreadcrumbItem>
423
</WorkspaceBreadcrumb>
424
{isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
apps/web/src/components/settings/ConnectionsSettings.tsx
+11
@@ -36,6 +36,8 @@ import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
36
import { searchableSetting } from "./settingsSearch";
37
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
38
import { FoldedSettingsSection } from "./FoldedSettingsSection";
39
+import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";
40
+import { usePeerLinkHosts } from "~/state/peerLinks";
41
import { LoadBalancingSettings } from "./LoadBalancingSettings";
42
import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";
43
import { Input } from "../ui/input";
@@ -156,6 +158,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
158
const desktopBridge = window.desktopBridge;
159
const { environments } = useEnvironments();
160
const primaryEnvironment = usePrimaryEnvironment();
161
+ const peerLinkHosts = usePeerLinkHosts();
162
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
163
const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
164
reportFailure: false,
@@ -1533,6 +1536,14 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1536
}}
1537
/>
1538
) : null}
1539
+ {peerLinkHosts.map((environment, index) => (
1540
+ <LinkedEnvironmentsSettings
1541
+ key={environment.environmentId}
1542
+ environmentId={environment.environmentId}
1543
+ environmentLabel={peerLinkHosts.length > 1 ? environment.label : null}
1544
+ isSearchTarget={index === 0}
1545
+ />
1546
+ ))}
1547
<LoadBalancingSettings environments={loadBalancingEnvironments} />
1548
<PullRequestRoutingSettings environments={loadBalancingEnvironments} />
1549
</SettingsPageContainer>
apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
new
+283
@@ -0,0 +1,283 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import { AuthMcpClientAccess, type EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
3
+import {
4
+ isAtomCommandInterrupted,
5
+ squashAtomCommandFailure,
6
+} from "@t3tools/client-runtime/state/runtime";
7
+import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
8
+import * as DateTime from "effect/DateTime";
9
+import { PlusIcon } from "lucide-react";
10
+import { useId, useState } from "react";
11
+
12
+import { requestConfirmDialog } from "~/confirmDialog";
13
+import { peerLinkEnvironment } from "~/state/peerLinks";
14
+import { useEnvironmentQuery } from "~/state/query";
15
+import { useAtomCommand } from "~/state/use-atom-command";
16
+import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";
17
+import { ConnectionStatusDot } from "../ConnectionStatusDot";
18
+import { Button } from "../ui/button";
19
+import {
20
+ Dialog,
21
+ DialogClose,
22
+ DialogDescription,
23
+ DialogFooter,
24
+ DialogHeader,
25
+ DialogPanel,
26
+ DialogPopup,
27
+ DialogTitle,
28
+ DialogTrigger,
29
+} from "../ui/dialog";
30
+import { Input } from "../ui/input";
31
+import { RadioGroup } from "../ui/radio-group";
32
+import { stackedThreadToast, toastManager } from "../ui/toast";
33
+import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
34
+import { SettingsRow, SettingsSection } from "./settingsLayout";
35
+import { useNowMinute } from "../../hooks/useNowMinute";
36
+import { searchableSetting } from "./settingsSearch";
37
+
38
+const failureToast = (title: string, description: string) =>
39
+ toastManager.add(stackedThreadToast({ type: "error", title, description }));
40
+
41
+export function LinkedEnvironmentsSettings({
42
+ environmentId,
43
+ environmentLabel,
44
+ isSearchTarget,
45
+}: {
46
+ readonly environmentId: EnvironmentId;
47
+ readonly environmentLabel: string | null;
48
+ readonly isSearchTarget: boolean;
49
+}) {
50
+ const links = useEnvironmentQuery(peerLinkEnvironment.list({ environmentId, input: {} }));
51
+ const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(environmentId));
52
+ const search = searchableSetting("linked-environments");
53
+ return (
54
+ <SettingsSection
55
+ {...(isSearchTarget ? { id: search.id } : {})}
56
+ title={environmentLabel === null ? search.title : `${search.title} · ${environmentLabel}`}
57
+ headerAction={canLink ? <LinkEnvironmentAction environmentId={environmentId} /> : null}
58
+ >
59
+ {links.error ? (
60
+ <SettingsRow title="Could not load linked environments" description={links.error} />
61
+ ) : !links.data ? (
62
+ <SettingsRow title="Loading linked environments…" role="status" />
63
+ ) : links.data.links.length === 0 ? (
64
+ <SettingsRow
65
+ title="No linked environments"
66
+ description="Link another machine running T3 Code, such as a VPS, so agents here can launch and drive threads there."
67
+ />
68
+ ) : (
69
+ links.data.links.map((link) => (
70
+ <LinkedEnvironmentRow
71
+ key={link.environmentId}
72
+ environmentId={environmentId}
73
+ link={link}
74
+ />
75
+ ))
76
+ )}
77
+ </SettingsSection>
78
+ );
79
+}
80
+
81
+function LinkedEnvironmentRow({
82
+ environmentId,
83
+ link,
84
+}: {
85
+ readonly environmentId: EnvironmentId;
86
+ readonly link: PeerLinkSummary;
87
+}) {
88
+ const nowMinute = useNowMinute();
89
+ const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute));
90
+ const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: "unlink environment" });
91
+ const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId));
92
+ const [busy, setBusy] = useState(false);
93
+ const forget = async () => {
94
+ const confirmed = await (requestConfirmDialog(
95
+ `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Connections to end the session there too.`,
96
+ { variant: "destructive" },
97
+ ) ?? Promise.resolve(false));
98
+ if (!confirmed) return;
99
+ setBusy(true);
100
+ const result = await unlink({ environmentId, input: { environmentId: link.environmentId } });
101
+ setBusy(false);
102
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
103
+ failureToast("Could not forget the link", String(squashAtomCommandFailure(result)));
104
+ }
105
+ };
106
+ const status =
107
+ health.kind === "expired"
108
+ ? "Expired. Link it again with a new pairing code."
109
+ : health.kind === "unreachable"
110
+ ? (health.detail ?? "Not answering right now.")
111
+ : health.kind === "failing"
112
+ ? health.detail
113
+ : health.expiresInDays !== null
114
+ ? `Expires in ${health.expiresInDays} ${health.expiresInDays === 1 ? "day" : "days"}. Link it again to renew.`
115
+ : "Reachable";
116
+ return (
117
+ <div className={ITEM_ROW_CLASSNAME}>
118
+ <div className={ITEM_ROW_INNER_CLASSNAME}>
119
+ <div className="min-w-0 flex-1 space-y-1">
120
+ <div className="flex min-h-5 items-center gap-1.5">
121
+ <ConnectionStatusDot
122
+ tooltipText={status}
123
+ dotClassName={
124
+ health.kind === "reachable"
125
+ ? health.expiresInDays === null
126
+ ? "bg-success"
127
+ : "bg-warning"
128
+ : health.kind === "expired" || health.kind === "failing"
129
+ ? "bg-destructive"
130
+ : "bg-muted-foreground/30"
131
+ }
132
+ pingClassName={null}
133
+ />
134
+ <h3 className="text-sm font-medium text-foreground">{link.label}</h3>
135
+ </div>
136
+ <p className="text-xs text-muted-foreground">
137
+ {accessConfig[link.access].label} · {status}
138
+ </p>
139
+ <p className="truncate text-xs text-muted-foreground/80">{link.urls.join(", ")}</p>
140
+ </div>
141
+ {canUnlink ? (
142
+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
143
+ <Button
144
+ size="xs"
145
+ variant="destructive-outline"
146
+ disabled={busy}
147
+ onClick={() => void forget()}
148
+ >
149
+ {busy ? "Forgetting…" : "Forget"}
150
+ </Button>
151
+ </div>
152
+ ) : null}
153
+ </div>
154
+ </div>
155
+ );
156
+}
157
+
158
+function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {
159
+ const [open, setOpen] = useState(false);
160
+ const [url, setUrl] = useState("");
161
+ const [pairingCode, setPairingCode] = useState("");
162
+ const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
163
+ const [busy, setBusy] = useState(false);
164
+ const formId = useId();
165
+ const accessLabelId = `${formId}-access`;
166
+ const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" });
167
+ const handleOpenChange = (next: boolean) => {
168
+ setOpen(next);
169
+ if (!next) {
170
+ setUrl("");
171
+ setPairingCode("");
172
+ setAccess("approval-required");
173
+ }
174
+ };
175
+ const submit = async () => {
176
+ setBusy(true);
177
+ const result = await link({
178
+ environmentId,
179
+ input: { url: url.trim(), pairingCode: pairingCode.trim(), access },
180
+ });
181
+ setBusy(false);
182
+ if (result._tag === "Success") {
183
+ toastManager.add({ type: "success", title: `Linked ${result.value.label}` });
184
+ handleOpenChange(false);
185
+ } else if (!isAtomCommandInterrupted(result)) {
186
+ failureToast("Could not link the environment", String(squashAtomCommandFailure(result)));
187
+ }
188
+ };
189
+ return (
190
+ <Dialog
191
+ open={open}
192
+ onOpenChange={(next) => {
193
+ if (!next && busy) return;
194
+ handleOpenChange(next);
195
+ }}
196
+ >
197
+ <DialogTrigger
198
+ render={
199
+ <Button size="xs" variant="default">
200
+ <PlusIcon className="size-3" />
201
+ Link
202
+ </Button>
203
+ }
204
+ />
205
+ <DialogPopup className="max-w-md">
206
+ <DialogHeader>
207
+ <DialogTitle>Link an environment</DialogTitle>
208
+ <DialogDescription>
209
+ Agents here can then launch, message and wait on threads there. It appears in that
210
+ environment's Connections, where it can be revoked.
211
+ </DialogDescription>
212
+ </DialogHeader>
213
+ <DialogPanel>
214
+ <form
215
+ id={formId}
216
+ className="space-y-4"
217
+ onSubmit={(event) => {
218
+ event.preventDefault();
219
+ void submit();
220
+ }}
221
+ >
222
+ <label className="block space-y-1.5">
223
+ <span className="block text-xs font-medium text-foreground">Address</span>
224
+ <Input
225
+ value={url}
226
+ onChange={(event) => setUrl(event.target.value)}
227
+ placeholder="https://box.example.ts.net"
228
+ disabled={busy}
229
+ autoFocus
230
+ nativeInput
231
+ spellCheck={false}
232
+ />
233
+ </label>
234
+ <label className="block space-y-1.5">
235
+ <span className="block text-xs font-medium text-foreground">Pairing code</span>
236
+ <Input
237
+ value={pairingCode}
238
+ onChange={(event) => setPairingCode(event.target.value)}
239
+ placeholder="From that environment's Connections, or t3 pair there"
240
+ disabled={busy}
241
+ autoComplete="one-time-code"
242
+ nativeInput
243
+ spellCheck={false}
244
+ />
245
+ </label>
246
+ <div className="space-y-2">
247
+ <span id={accessLabelId} className="block text-xs font-medium">
248
+ What agents here may do there
249
+ </span>
250
+ <RadioGroup
251
+ aria-labelledby={accessLabelId}
252
+ disabled={busy}
253
+ value={access}
254
+ onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
255
+ >
256
+ {AuthMcpClientAccess.literals.map((option) => (
257
+ <AccessOption key={option} access={option} selected={option === access} />
258
+ ))}
259
+ </RadioGroup>
260
+ <p className="text-xs text-muted-foreground">
261
+ An agent never gets more access there than its own mode here. Below full access, it
262
+ can change only threads this link started, not that environment's own threads,
263
+ projects or settings.
264
+ </p>
265
+ </div>
266
+ </form>
267
+ </DialogPanel>
268
+ <DialogFooter variant="bare">
269
+ <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
270
+ Cancel
271
+ </DialogClose>
272
+ <Button
273
+ form={formId}
274
+ type="submit"
275
+ disabled={busy || url.trim().length === 0 || pairingCode.trim().length === 0}
276
+ >
277
+ {busy ? "Linking…" : "Link"}
278
+ </Button>
279
+ </DialogFooter>
280
+ </DialogPopup>
281
+ </Dialog>
282
+ );
283
+}
apps/web/src/components/settings/settingsSearch.test.ts
+27
@@ -122,10 +122,37 @@ describe("searchSettings", () => {
122
"auto-settle-inactive-threads",
123
"auto-settle-merged-threads",
124
"days-before-auto-settle",
125
+ "linked-environments",
126
]);
127
expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]);
128
});
129
130
+ it("finds linked environments on a remote host without local maintenance access", () => {
131
+ const availability = {
132
+ hasCloudPublicConfig: false,
133
+ hasEnvironment: true,
134
+ hasProviderSettingsEnvironment: true,
135
+ hasMacProviderSettingsEnvironment: false,
136
+ canManageLocalBackend: false,
137
+ localEnvironmentDisabled: true,
138
+ isWslSettingsRowVisible: false,
139
+ hasThreadAutoSettlement: false,
140
+ };
141
+ const results = (hasPeerLinkHost: boolean) =>
142
+ searchSettings(
143
+ "linked environments",
144
+ filterAvailableSettingsSearchItems({ ...availability, hasPeerLinkHost }),
145
+ );
146
+ expect(results(false).map((item) => item.id)).not.toContain("linked-environments");
147
+ expect(results(true)).toContainEqual(
148
+ expect.objectContaining({
149
+ id: "linked-environments",
150
+ to: "/settings/connections",
151
+ targetId: "linked-environments",
152
+ }),
153
+ );
154
+ });
155
+
156
it("finds keybinding commands by label, command id, and default key", () => {
157
expect(searchSettings("toggle sidebar")[0]?.id).toBe("keybinding-sidebar.toggle");
158
expect(searchSettings("sidebar.toggle")[0]?.id).toBe("keybinding-sidebar.toggle");
apps/web/src/components/settings/settingsSearch.ts
+12
-1
@@ -65,6 +65,7 @@ export interface SettingsSearchItem {
65
readonly localEnvironmentOnly?: boolean;
66
readonly wslAvailableOnly?: boolean;
67
readonly managedTunnelOnly?: boolean;
68
+ readonly peerLinksOnly?: boolean;
69
readonly secondary?: boolean;
70
readonly requiresThreadAutoSettlement?: boolean;
71
}
@@ -79,6 +80,7 @@ export interface SettingsSearchAvailability {
80
readonly isWslSettingsRowVisible: boolean;
81
readonly hasThreadAutoSettlement: boolean;
82
readonly managedTunnelActive?: boolean;
83
+ readonly hasPeerLinkHost?: boolean;
84
}
85
86
export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
@@ -1072,6 +1074,14 @@ export const SETTINGS_SEARCH_ITEMS = [
1074
"connections server backend local remote access administrative permissions scope pairing links qr code authorized clients sessions revoke endpoint",
1075
],
1076
},
1077
+ {
1078
+ id: "linked-environments",
1079
+ peerLinksOnly: true,
1080
+ title: "Linked environments",
1081
+ to: "/settings/connections",
1082
+ targetId: "linked-environments",
1083
+ searchTerms: ["link peer another machine vps agents work there handoff pairing code"],
1084
+ },
1085
{
1086
id: "remote-environments",
1087
title: "Environments",
@@ -1260,7 +1270,8 @@ export function filterAvailableSettingsSearchItems(
1270
(!item.localEnvironmentOnly || !availability.localEnvironmentDisabled) &&
1271
(!item.wslAvailableOnly || availability.isWslSettingsRowVisible) &&
1272
(!item.requiresThreadAutoSettlement || availability.hasThreadAutoSettlement) &&
1263
- (!item.managedTunnelOnly || availability.managedTunnelActive === true),
1273
+ (!item.managedTunnelOnly || availability.managedTunnelActive === true) &&
1274
+ (!item.peerLinksOnly || availability.hasPeerLinkHost === true),
1275
);
1276
}
1277
apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
+3
@@ -6,6 +6,7 @@ import { isElectron } from "~/env";
6
import { isLocalEnvironmentDisabled } from "~/localEnvironment";
7
import { desktopWslStateAtom } from "~/state/desktopWslState";
8
import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
9
+import { usePeerLinkHosts } from "~/state/peerLinks";
10
import { useEnvironmentQuery } from "~/state/query";
11
import { useEnvironmentScope } from "~/state/session";
12
import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";
@@ -42,6 +43,7 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch
43
getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0;
44
const primaryEnvironmentId = usePrimaryEnvironmentId();
45
const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope);
46
+ const hasPeerLinkHost = usePeerLinkHosts().length > 0;
47
const cloudLinkState = usePrimaryCloudLinkState().data;
48
// Same fallback as the Connections row: older servers imply a tunnel from `linked`.
49
const managedTunnelActive =
@@ -66,5 +68,6 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch
68
isWslSettingsRowVisible: wslSettingsRowVisible,
69
hasThreadAutoSettlement,
70
managedTunnelActive,
71
+ hasPeerLinkHost,
72
});
73
}
apps/web/src/state/peerLinks.ts
new
+19
@@ -0,0 +1,19 @@
1
+import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
2
+import { AuthAccessReadScope } from "@t3tools/contracts";
3
+
4
+import { connectionAtomRuntime } from "../connection/runtime";
5
+import { useEnvironments } from "./environments";
6
+import { useEnvironmentsWithScope } from "./session";
7
+
8
+export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
9
+
10
+export function usePeerLinkHosts() {
11
+ const { environments } = useEnvironments();
12
+ const supported = environments.filter(
13
+ (environment) =>
14
+ environment.connection.phase === "connected" &&
15
+ environment.serverConfig?.environment.capabilities.peerLinks === true,
16
+ );
17
+ const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);
18
+ return supported.filter((environment) => readable.has(environment.environmentId));
19
+}
docs/user/remote-access.md
+22
@@ -247,6 +247,28 @@ Claude Code, Codex, ChatGPT and other agents T3 Code did not start can drive
247
threads on an environment through its MCP server. See
248
[outside agents](./outside-agents.md) for setup.
249
250
+## Link another environment
251
+
252
+Link two machines, such as your laptop and a VPS, and agents on one can work on
253
+the other: launch, message, wait on and stop its threads, answer their
254
+questions, and manage its queues, projects and scheduled tasks. On the machine
255
+you will work from, open **Settings → Connections → Linked environments**,
256
+choose **Link**, and enter the other machine's address and a pairing code from
257
+it. From a terminal, use
258
+`t3 environment link <address> --pairing-code <code> --access <mode>`.
259
+
260
+- The access you pick is the most agents from this machine may do there. An
261
+ agent also never gets more there than its own mode here.
262
+- Threads a link starts are marked **From** and this machine's name there.
263
+- A full-access link works there like that machine's own agents. Below full
264
+ access, the link's agents can change only threads it started, not that
265
+ machine's own threads, projects or settings, and they skip its project setup
266
+ scripts.
267
+- The link shows up in that machine's **Settings → Connections** like any
268
+ outside agent. Revoke it there to end it. **Forget** on this machine only
269
+ removes it here.
270
+- Links last 30 days. Link again with a new pairing code to renew one.
271
+
272
## Manage or revoke access
273
274
On the host, **Settings → Sharing & access** lets authorized administrators create
packages/client-runtime/package.json
+4
@@ -207,6 +207,10 @@
207
"types": "./src/state/deviceHubAccess.ts",
208
"default": "./src/state/deviceHubAccess.ts"
209
},
210
+ "./state/peerLinks": {
211
+ "types": "./src/state/peerLinks.ts",
212
+ "default": "./src/state/peerLinks.ts"
213
+ },
214
"./state/preview": {
215
"types": "./src/state/preview.ts",
216
"default": "./src/state/preview.ts"
packages/client-runtime/src/state/commandPermissions.test.ts
+132
@@ -7,6 +7,8 @@ import type { RpcSession } from "../rpc/session.ts";
7
import { describe, expect, it } from "@effect/vitest";
8
import { vi } from "vite-plus/test";
9
import {
10
+ AuthAccessReadScope,
11
+ AuthAccessWriteScope,
12
AuthOrchestrationOperateScope,
13
AuthOrchestrationReadScope,
14
AuthPreviewOperateScope,
@@ -17,8 +19,10 @@ import {
19
ScheduledTaskId,
20
WS_METHODS,
21
type AuthSessionState,
22
+ type PeerLinkSummary,
23
} from "@t3tools/contracts";
24
import * as Cause from "effect/Cause";
25
+import * as DateTime from "effect/DateTime";
26
import * as Effect from "effect/Effect";
27
import * as Fiber from "effect/Fiber";
28
import * as Layer from "effect/Layer";
@@ -26,6 +30,8 @@ import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
30
import { EnvironmentRegistry } from "../connection/registry.ts";
31
import { createCommandPermissions } from "./commandPermissions.ts";
32
import { createEnvironmentRpcCommand } from "./runtime.ts";
33
+import { AVAILABLE_CONNECTION_STATE } from "../connection/model.ts";
34
+import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts";
35
36
vi.mock("./session.ts", () => ({
37
createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),
@@ -291,6 +297,132 @@ it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"]
297
),
298
);
299
300
+it.effect(
301
+ "refreshes linked environments after permitted writes and blocks a read-only session",
302
+ () =>
303
+ Effect.scoped(
304
+ Effect.gen(function* () {
305
+ const registry = yield* setup;
306
+ const peer: PeerLinkSummary = {
307
+ environmentId: EnvironmentId.make("peer"),
308
+ label: "Box",
309
+ urls: ["https://box.example.test"],
310
+ access: "auto",
311
+ linkedAt: DateTime.makeUnsafe("2026-10-01T12:00:00Z"),
312
+ expiresAt: DateTime.makeUnsafe("2026-10-31T12:00:00Z"),
313
+ lastReachedAt: null,
314
+ lastError: null,
315
+ status: "reachable",
316
+ };
317
+ let links: ReadonlyArray<PeerLinkSummary> = [];
318
+ const client = {
319
+ [WS_METHODS.peerLinksList]: () => Effect.sync(() => ({ links })),
320
+ [WS_METHODS.peerLinksLink]: vi.fn(() =>
321
+ Effect.sync(() => {
322
+ links = [peer];
323
+ return peer;
324
+ }),
325
+ ),
326
+ [WS_METHODS.peerLinksUnlink]: vi.fn(() =>
327
+ Effect.sync(() => {
328
+ links = [];
329
+ return { removed: true };
330
+ }),
331
+ ),
332
+ };
333
+ const supervisor = {
334
+ target: { environmentId: env },
335
+ session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)),
336
+ state: yield* SubscriptionRef.make({
337
+ ...AVAILABLE_CONNECTION_STATE,
338
+ phase: "connected" as const,
339
+ }),
340
+ } as EnvironmentSupervisor["Service"];
341
+ const peerRuntime = Atom.runtime(
342
+ Layer.succeed(EnvironmentRegistry, {
343
+ run: (id, effect) => {
344
+ expect(id).toBe(env);
345
+ return Effect.provideService(effect, EnvironmentSupervisor, supervisor);
346
+ },
347
+ followStream: (id, stream) => {
348
+ expect(id).toBe(env);
349
+ return Stream.provideService(stream, EnvironmentSupervisor, supervisor);
350
+ },
351
+ } as EnvironmentRegistry["Service"]),
352
+ );
353
+ const peerLinks = createPeerLinkEnvironmentAtoms(peerRuntime);
354
+ const list = peerLinks.list({ environmentId: env, input: {} });
355
+ registry.mount(list);
356
+ const readLinks = AtomRegistry.getResult(registry, list, { suspendOnWaiting: true });
357
+ const setAccess = (writable: boolean) =>
358
+ registry.set(
359
+ sessions(env),
360
+ AsyncResult.success({
361
+ ...grant(false),
362
+ scopes: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
363
+ permissions: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
364
+ }),
365
+ );
366
+ registry.mount(sessions(other));
367
+ registry.set(
368
+ sessions(other),
369
+ AsyncResult.success({
370
+ ...grant(false),
371
+ scopes: [AuthAccessWriteScope],
372
+ permissions: [AuthAccessWriteScope],
373
+ }),
374
+ );
375
+ setAccess(false);
376
+ expect(yield* readLinks).toEqual({ links: [] });
377
+ const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access };
378
+ const link = Effect.promise(() =>
379
+ peerLinks.link.run(registry, { environmentId: env, input: linkInput }),
380
+ );
381
+ const unlink = Effect.promise(() =>
382
+ peerLinks.unlink.run(registry, {
383
+ environmentId: env,
384
+ input: { environmentId: peer.environmentId },
385
+ }),
386
+ );
387
+ expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(false);
388
+ const deniedLink = yield* link;
389
+ expect(deniedLink._tag).toBe("Failure");
390
+ if (deniedLink._tag === "Failure") {
391
+ expect(Cause.squash(deniedLink.cause)).toMatchObject({
392
+ _tag: "EnvironmentAuthorizationError",
393
+ requiredPermission: AuthAccessWriteScope,
394
+ });
395
+ }
396
+ expect(client[WS_METHODS.peerLinksLink]).not.toHaveBeenCalled();
397
+ setAccess(true);
398
+ expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(true);
399
+ expect((yield* link)._tag).toBe("Success");
400
+ expect(client[WS_METHODS.peerLinksLink]).toHaveBeenCalledExactlyOnceWith(linkInput);
401
+ expect(yield* readLinks).toEqual({ links: [peer] });
402
+
403
+ setAccess(false);
404
+ expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(false);
405
+ const deniedUnlink = yield* unlink;
406
+ expect(deniedUnlink._tag).toBe("Failure");
407
+ if (deniedUnlink._tag === "Failure") {
408
+ expect(Cause.squash(deniedUnlink.cause)).toMatchObject({
409
+ _tag: "EnvironmentAuthorizationError",
410
+ requiredPermission: AuthAccessWriteScope,
411
+ });
412
+ }
413
+ expect(client[WS_METHODS.peerLinksUnlink]).not.toHaveBeenCalled();
414
+ expect(yield* readLinks).toEqual({ links: [peer] });
415
+ setAccess(true);
416
+ expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(true);
417
+ expect((yield* unlink)._tag).toBe("Success");
418
+ expect(client[WS_METHODS.peerLinksUnlink]).toHaveBeenCalledExactlyOnceWith({
419
+ environmentId: peer.environmentId,
420
+ });
421
+ expect(yield* readLinks).toEqual({ links: [] });
422
+ }),
423
+ ),
424
+);
425
+
426
it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
427
Effect.scoped(
428
Effect.gen(function* () {
packages/client-runtime/src/state/models.ts
+2
@@ -147,6 +147,7 @@ export interface EnvironmentThreadShell {
147
readonly worktreePath: string | null;
148
readonly lineage: OrchestrationV2ThreadShell["lineage"];
149
readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
150
+ readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;
151
readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
152
readonly latestRun: ThreadRunSummary | null;
153
readonly runtime: ThreadRuntimeSummary | null;
@@ -298,6 +299,7 @@ export function presentThreadShell(
299
branchPullRequest: thread.branchPullRequest ?? null,
300
lineage: thread.lineage,
301
forkedFrom: thread.forkedFrom,
302
+ linkOrigin: thread.linkOrigin ?? null,
303
activeProviderThreadId: thread.activeProviderThreadId,
304
latestRun,
305
runtime,
packages/client-runtime/src/state/peerLinks.ts
new
+57
@@ -0,0 +1,57 @@
1
+import { type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts";
2
+import * as DateTime from "effect/DateTime";
3
+import * as Duration from "effect/Duration";
4
+import * as Effect from "effect/Effect";
5
+import { Atom } from "effect/reactivity";
6
+
7
+import type { EnvironmentRegistry } from "../connection/registry.ts";
8
+import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
9
+
10
+export function createPeerLinkEnvironmentAtoms<R, E>(
11
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
12
+) {
13
+ const list = createEnvironmentRpcQueryAtomFamily(runtime, {
14
+ label: "environment-data:peer-links:list",
15
+ tag: WS_METHODS.peerLinksList,
16
+ // Listing probes every linked environment, so a list stays fresh briefly.
17
+ staleTimeMs: 10_000,
18
+ });
19
+ return {
20
+ list,
21
+ link: createEnvironmentRpcCommand(runtime, {
22
+ label: "environment-data:peer-links:link",
23
+ tag: WS_METHODS.peerLinksLink,
24
+ onSuccess: ({ environmentId }, registry) =>
25
+ Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))),
26
+ }),
27
+ unlink: createEnvironmentRpcCommand(runtime, {
28
+ label: "environment-data:peer-links:unlink",
29
+ tag: WS_METHODS.peerLinksUnlink,
30
+ onSuccess: ({ environmentId }, registry) =>
31
+ Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))),
32
+ }),
33
+ };
34
+}
35
+
36
+const EXPIRY_WARNING_DAYS = 5;
37
+
38
+export type PeerLinkHealth =
39
+ | { readonly kind: "reachable"; readonly expiresInDays: number | null }
40
+ | { readonly kind: "unreachable"; readonly detail: string | null }
41
+ | { readonly kind: "failing"; readonly detail: string }
42
+ | { readonly kind: "expired" };
43
+
44
+/**
45
+ * Listing only checks that the peer answers, so a link whose last call failed
46
+ * (the peer revoked it, say) is `failing` with the recorded reason; the next
47
+ * successful call clears it.
48
+ */
49
+export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth {
50
+ if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) {
51
+ return { kind: "expired" };
52
+ }
53
+ if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError };
54
+ if (link.lastError !== null) return { kind: "failing", detail: link.lastError };
55
+ const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt)));
56
+ return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null };
57
+}
packages/contracts/src/clientRpcPermissions.ts
+2
@@ -52,6 +52,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
52
[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,
53
// A guest link hands thread access to someone outside, like a pairing link.
54
[WS_METHODS.guestShareCreate]: AuthAccessWriteScope,
55
+ [WS_METHODS.peerLinksLink]: AuthAccessWriteScope,
56
+ [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
57
} as const;
58
export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;
59