From 9972fbd14b6c76b439c4d944ff3ac4e56bf3ddad Mon Sep 17 00:00:00 2001
From: Orin
Date: Wed, 18 Nov 2026 06:20:15 -0800
Subject: [PATCH 1/5] fix(server): agents can raise the access of an existing
environment link
When an agent asked t3_environment_link for more access than an existing link
had, the server returned the existing link at once and showed no card, so the
agent could only unlink and link again. The server now returns an existing link
at once only when it has at least the requested access; otherwise the card asks
the user, and linking again replaces the old link.
The card offers "use this link" only when the link covers the requested access.
A "use existing" answer for a link removed meanwhile now leaves the card open
with an error instead of failing it, and the client refreshes its links after
every answer, so the next try shows the link step.
Co-Authored-By: Claude Opus 5.5
---
.../src/features/threads/LinkRequestCard.tsx | 25 ++++---
apps/mobile/src/i18n/translations/de.json | 1 +
apps/mobile/src/i18n/translations/en.json | 1 +
apps/mobile/src/i18n/translations/es.json | 1 +
apps/mobile/src/i18n/translations/fr.json | 1 +
apps/mobile/src/i18n/translations/ja.json | 1 +
apps/mobile/src/i18n/translations/ko.json | 1 +
apps/mobile/src/i18n/translations/pt-BR.json | 1 +
apps/mobile/src/i18n/translations/ru.json | 1 +
apps/mobile/src/i18n/translations/sv.json | 1 +
apps/mobile/src/i18n/translations/zh.json | 1 +
apps/server/src/peer/PeerLinkRequests.test.ts | 69 +++++++++++++++----
apps/server/src/peer/PeerLinkRequests.ts | 28 ++++----
.../src/components/chat/LinkRequestCard.tsx | 10 ++-
.../components/settings/LinkMachineSelect.tsx | 2 +-
.../settings/LinkedEnvironmentsSettings.tsx | 2 +-
packages/client-runtime/src/linkBatch.test.ts | 4 +-
packages/client-runtime/src/linkBatch.ts | 4 +-
.../client-runtime/src/linkRequest.test.ts | 55 ++++++++++-----
packages/client-runtime/src/linkRequest.ts | 34 ++++++---
.../client-runtime/src/state/peerLinks.ts | 3 +-
packages/contracts/src/auth.ts | 7 ++
packages/contracts/src/peerLink.ts | 1 +
23 files changed, 183 insertions(+), 71 deletions(-)
diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx
index 1ee34663431b..bc59b741ea66 100644
--- a/apps/mobile/src/features/threads/LinkRequestCard.tsx
+++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx
@@ -9,6 +9,7 @@ import {
linkRequestFailureMessage,
linkRequestInitialMachine,
type LinkRequestItem,
+ linkRequestKeepsLink,
linkRequestTarget,
rankMachinesByHint,
} from "@t3tools/client-runtime/link-request";
@@ -243,7 +244,7 @@ function LinkRequestSheet(props: {
Option.isSome(connected) &&
mayMint &&
!mintFailed.has(targetId);
- const useExisting = target.kind === "machine" && target.linked;
+ const useExisting = linkRequestKeepsLink(item, target);
const ready =
target.kind !== "none" &&
(useExisting ||
@@ -251,7 +252,7 @@ function LinkRequestSheet(props: {
const prepareAnswer = async () => {
if (target.kind === "none") return null;
- if (target.kind === "machine" && target.linked) {
+ if (useExisting && target.kind === "machine") {
return linkRequestAnswerInput(item, {
type: "use-existing",
environmentId: target.environmentId,
@@ -407,6 +408,11 @@ function LinkRequestSheet(props: {
) : target.kind === "none" ? null : (
<>
+ {target.kind === "machine" && target.linkedAccess !== null ? (
+
+ Already linked. Linking again renews it with the access you pick.
+
+ ) : null}
{canMint ? null : (
+it.live("naming a machine linked with enough access returns the link at once, with no card", () =>
withBoth((a, b) =>
Effect.gen(function* () {
yield* seedThread(a);
const pairing = yield* b.auth.issuePairingCredential();
yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
- const asked = yield* a.call({ environmentId: box.environmentId });
- expect(asked.structuredContent).toEqual({
- status: "linked",
- environmentId: box.environmentId,
- label: "Box",
- access: "auto",
- });
+ for (const asks of [
+ {},
+ { requestedAccess: "approval-required" },
+ { requestedAccess: "auto" },
+ ]) {
+ const asked = yield* a.call({ environmentId: box.environmentId, ...asks });
+ expect(asked.structuredContent).toEqual({
+ status: "linked",
+ environmentId: box.environmentId,
+ label: "Box",
+ access: "auto",
+ });
+ }
expect(yield* cardOf(a)).toBeUndefined();
// Not both: the address could name another machine than the id.
@@ -1088,6 +1094,41 @@ it.live("a retry naming a machine linked meanwhile closes the card it left as li
),
);
+it.live("a machine linked with less access than asked goes through the card, which raises it", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* linkTo(a.links, b, "read-only");
+ const asked = yield* a.call({
+ environmentId: box.environmentId,
+ requestedAccess: "full-access",
+ });
+ expect(asked.structuredContent).toMatchObject({ status: "pending" });
+ const card = yield* pendingCard(a);
+ expect(card.requestedAccess).toBe("full-access");
+
+ // Linking again over the old link replaces it; nothing is unlinked first.
+ const pairing = yield* b.auth.issuePairingCredential();
+ yield* a.requests.answer({
+ threadId,
+ turnItemId: card.id,
+ answer: {
+ type: "link",
+ environmentId: box.environmentId,
+ label: "Box",
+ urls: [b.url],
+ access: "full-access",
+ pairingCode: pairing.credential,
+ },
+ });
+ expect(yield* cardOf(a)).toMatchObject({ linkStatus: "linked", linkedAccess: "full-access" });
+ expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))).toMatchObject({
+ access: "full-access",
+ });
+ }),
+ ),
+);
+
it.live("a link that expired goes through the card, so the user can link it again", () =>
withBoth((a, b) =>
Effect.gen(function* () {
@@ -1097,16 +1138,18 @@ it.live("a link that expired goes through the card, so the user can link it agai
expect(asked.structuredContent).toMatchObject({ status: "pending" });
const card = yield* pendingCard(a);
- // Keeping the expired link is no answer: the card fails and says why.
- yield* a.requests
+ // Keeping the expired link is no answer, as when a client's list still shows one
+ // removed meanwhile; the card stays open for the user to link again.
+ const kept = yield* a.requests
.answer({
threadId,
turnItemId: card.id,
answer: { type: "use-existing", environmentId: box.environmentId },
})
- .pipe(afterLinksExpire);
- expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
- expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired");
+ .pipe(afterLinksExpire, Effect.flip);
+ expect(kept.reason).toBe("link_gone");
+ expect(yield* cardOf(a)).toMatchObject({ linkStatus: "pending" });
+ expect((yield* outcomeMessages(a)).messages).toHaveLength(0);
}),
),
);
diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts
index a33bb47d7ec1..6f6f64668aed 100644
--- a/apps/server/src/peer/PeerLinkRequests.ts
+++ b/apps/server/src/peer/PeerLinkRequests.ts
@@ -7,6 +7,7 @@
import {
CommandId,
type EnvironmentId,
+ mcpClientAccessCovers,
MessageId,
type NodeId,
type OrchestrationV2Notification,
@@ -15,7 +16,6 @@ import {
type OrchestratorMcpEnvironmentLinkResult,
OrchestratorMcpFailure,
type PeerLink,
- PeerLinkError,
PeerLinkRequestError,
type PeerLinkRequestAnswerInput,
type RunId,
@@ -209,7 +209,8 @@ const make = Effect.gen(function* () {
"Pass either environmentId or url, not both. Pass neither to let the user pick the machine.",
});
}
- // A machine already linked needs no card: the agent can use it now.
+ // A machine already linked with enough access needs no card: the agent can
+ // use it now. One linked with less gets a card, and linking again raises it.
if (input.environmentId !== undefined) {
const linked = yield* usableLink(input.environmentId).pipe(
Effect.mapError(
@@ -217,7 +218,11 @@ const make = Effect.gen(function* () {
new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
),
);
- if (Option.isSome(linked)) {
+ if (
+ Option.isSome(linked) &&
+ (input.requestedAccess === undefined ||
+ mcpClientAccessCovers(linked.value.access, input.requestedAccess))
+ ) {
if (input.clientRequestId !== undefined) {
yield* closeAsLinked(
threadId,
@@ -300,28 +305,21 @@ const make = Effect.gen(function* () {
/** Links the machine the user picked, or finds the link they chose to keep. */
const answerOutcome = (
answer: PeerLinkRequestAnswerInput["answer"],
- ): Effect.Effect => {
+ ): Effect.Effect => {
switch (answer.type) {
case "decline":
return Effect.succeed({ linkStatus: "declined" });
case "use-existing":
+ // A client's list of links can lag one removed meanwhile, by an agent say.
+ // The card stays open so the user can link the machine again.
return usableLink(answer.environmentId).pipe(
+ Effect.mapError((cause) => new PeerLinkRequestError({ reason: "load_failed", cause })),
Effect.flatMap(
Option.match({
- onNone: () =>
- Effect.fail(
- new PeerLinkError({
- reason: "unknown_link",
- message:
- "That environment is no longer linked here, or its link expired. Link it again.",
- }),
- ),
+ onNone: () => Effect.fail(new PeerLinkRequestError({ reason: "link_gone" })),
onSome: (linked) => Effect.succeed(linkedOutcome(linked)),
}),
),
- Effect.catch((error) =>
- Effect.succeed({ linkStatus: "failed", failure: error.message }),
- ),
);
case "link": {
const [url, ...alternateUrls] = answer.urls;
diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx
index 81c25774a900..86fd16626786 100644
--- a/apps/web/src/components/chat/LinkRequestCard.tsx
+++ b/apps/web/src/components/chat/LinkRequestCard.tsx
@@ -9,6 +9,7 @@ import {
linkRequestFailureMessage,
linkRequestInitialMachine,
type LinkRequestItem,
+ linkRequestKeepsLink,
linkRequestTarget,
linkRequestTargetName,
rankMachinesByHint,
@@ -232,7 +233,7 @@ function LinkRequestDialog(props: {
!mintFailed.has(targetId);
// An address the agent gave is already filled in; only one the user must type is asked for.
const asksAddress = needsAddress && item.url === undefined;
- const useExisting = target.kind === "machine" && target.linked;
+ const useExisting = linkRequestKeepsLink(item, target);
// A named machine with an address it answers at has nothing to choose before access.
const steps: ReadonlyArray =
pickMachine || asksAddress ? ["machine", "access"] : ["access"];
@@ -259,7 +260,7 @@ function LinkRequestDialog(props: {
// Settles to the answer to send, an error to show, or nothing to do.
const prepareAnswer = async () => {
if (target.kind === "none") return null;
- if (target.kind === "machine" && target.linked) {
+ if (useExisting && target.kind === "machine") {
return linkRequestAnswerInput(item, {
type: "use-existing",
environmentId: target.environmentId,
@@ -407,6 +408,11 @@ function LinkRequestDialog(props: {
) : null}
{useExisting ? null : (
<>
+ {target.kind === "machine" && target.linkedAccess !== null ? (
+
+ Already linked. Linking again renews it with the access you pick.
+
\" />);\n+ expect(screen.getByTitle('HTML preview')).toBeTruthy();\n+});\n", "prs": [{"number": 123, "title": "fix(web): HTML preview frame gets an accessible title", "headRefName": "fix/html-preview-title", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Check", "state": "pass"}, {"name": "Test Web", "state": "pass"}], "mergeStateStatus": "CLEAN"}], "files": {"apps/web/src/HtmlPreview.tsx": "export function HtmlPreview({ html }: { html: string }) {\n return ;\n}\n", "apps/web/src/HtmlPreview.test.tsx": "import { expect, it } from 'vitest';\nimport { render, screen } from '@testing-library/react';\nimport { HtmlPreview } from './HtmlPreview';\n\nit('gives the preview frame an accessible name', () => {\n render(hi\" />);\n expect(screen.getByTitle('HTML preview')).toBeTruthy();\n});\n"}}, "shellMocks": [{"match": "gh pr merge", "output": "✓ Squashed and merged pull request acme/app#123 (fix(web): HTML preview frame gets an accessible title)"}]}, "prompt": "Update on pull request #123 (https://github.com/acme/app/pull/123), which T3 Code is watching for you:\n- All 4 checks passed on abc1234.\n\nLook into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.", "expect": {"calls": [{"tool": "Bash", "args": {"command": "~gh pr merge"}}, {"tool": "t3_thread_organize", "args": {"action": "settle"}}], "notCalls": ["watch_pull_request", "t3_thread_update", "Monitor", "ScheduleWakeup"], "shellMustNot": ["\\bsleep \\d", "gh pr checks[^\\n]*--watch", "gh run watch", "\\buntil\\b[^\\n]*\\bgh (pr|run|api)\\b", "pr-wait"]}}
{"id": "thread-send-fresh-context", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send that should start a fresh provider session", "experience": "The user wanted a confused long-running thread to start over in the same thread without its old context; a plain send would keep feeding it the history.", "rule": "`freshContext: true` on t3_thread_send starts a new provider session in the same thread, like /clear.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The thread working on the CSV importer keeps reverting to the old column mapping from early in its history."}, {"role": "assistant", "text": "That thread has a long history with three different mappings in it, so the model keeps picking up the stale one."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "link": "", "messageId": "msg-1", "runId": "run-1", "status": "starting", "delivery": "started"}}}, "prompt": "Send it the final mapping below and have it start over with a clean context in that same thread, so the old history stops leaking in: thread 11111111-1111-4111-8111-111111111111.\n\nFinal mapping: id -> customer_id, amt -> amount_cents, ts -> created_at.", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111", "freshContext": true}}], "notCalls": ["delegate_task", "t3_thread_launch", "create_threads"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-03: fresh provider sessions in one T3 thread"}, "notes": "Pairs with thread-send-to-named-top-level-thread, where an ordinary send must not set freshContext."}
{"id": "child-async-delegate-keeps-working", "area": "orchestration", "kind": "bad", "pattern": "async delegate ends a child's turn with work left", "experience": "A delegated child told to start an advisory async check and then rebase ended its turn right after delegate_task, because the result's next said to end the turn, and sat idle until the check finished.", "rule": "Follow a running delegate's `next`. (intended: keep doing other work; end the turn only when none is left)", "privacy": "commit-safe", "setup": {"role": "delegated-child", "delegateRole": "implementation", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "codex", "inheritedModel": "gpt-6.1-sol", "inheritedOptions": [{"id": "reasoningEffort", "value": "xhigh"}, {"id": "serviceTier", "value": "priority"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default", "task_status": "default"}, "world": {"repo": "acme/app", "branch": "feat/lexer", "status": "", "commits": [{"sha": "5c1e9a2", "subject": "lex strings"}, {"sha": "9b0d7f4", "subject": "lex numbers"}, {"sha": "2f8a6c1", "subject": "add token kinds"}], "main": "main's newest commit 7d3e0b5 'rename readChar to peek' changes lex.ts; rebasing feat/lexer onto main stops at a conflict in lex.ts on 'lex numbers'.", "files": {"lex.ts": "export function readChar(s: string, i: number) {\n return s[i];\n}\n\nexport function lexNumber(s: string, i: number) {\n return readChar(s, i);\n}\n", "kinds.ts": "export type Kind = \"num\" | \"str\";\n", "str.ts": "export function lexString(s: string) {\n return s.slice(1, -1);\n}\n", "/home/user/BRIEF.md": "# Rebase with an advisory background check\n\nRepository: `/home/user/app`. Work only in `/home/user/`.\n\nThe job: rebase `feat/lexer` onto `main` and resolve any conflicts so the code stays consistent with `main` (`main` renamed `readChar` to `peek`). Write `/home/user/report.md` with the new HEAD SHA and the check's output.\n\n## The background check\n\nDo this first, before the rebase: call the T3 tool `delegate_task` once with\n- `target`: `{\"providerInstanceId\": \"claudeAgent\", \"model\": \"claude-haiku-5-5\", \"options\": [{\"id\": \"effort\", \"value\": \"low\"}]}`\n- `mode`: `\"async\"`\n- `task`: `Run the shell command \\`sleep 120 && echo CHECK OK\\` and reply with its output only. Do not edit files or start subagents.`\n\nThe check is advisory: never wait for it. Start the rebase at once. Its result reaches you as a message. Start no other subagents.\n\nBefore each step, append `date -u +%T` and the step name to `/home/user/log.txt`.\n\nYour final message is one line.\n"}}}, "prompt": "Read /home/user/BRIEF.md and follow it.", "expect": {"calls": [{"tool": "delegate_task", "args": {"mode": "async", "target.model": "claude-haiku-5-5"}}], "shellMust": ["git\\s+(-C\\s+\\S+\\s+)?rebase\\b"], "maxCalls": {"task_status": 0, "t3_thread_wait": 0}, "shellMustNot": ["\\bsleep\\b"]}, "source": {"issue": "https://github.com/pingdotgg/t3code/issues/27126"}, "notes": "The reporter's brief and prompt, with Acme paths. The check is advisory, so the rebase must start in the same turn as delegate_task."}
+{"id": "vps-linked-read-only-raises-access", "area": "orchestration", "kind": "bad", "pattern": "linked machine with less access than the work needs", "experience": "With the VPS linked read-only, an agent asked to run a command there was told t3_environment_link is for a machine that is not linked and returns linked for one that is, so it never asked the user to raise the link: it gave up, or told the user to unlink and relink by hand.", "rule": "A machine linked with less access than the work needs: call t3_environment_link with its environmentId and a requestedAccess above the link's, so the user can raise it in a card.", "privacy": "commit-safe", "setup": {"role": "top", "linkedEnvironments": true, "mocks": {"t3_environment_links": {"environmentId": "environment-laptop", "links": [{"environmentId": "environment-vps", "label": "Hetzner VPS", "status": "reachable", "access": "read-only", "expiresAt": "2026-12-01T00:00:00.000Z", "lastError": null}], "notListed": "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words."}, "delegate_task": {"_tag": "OrchestratorMcpFailure", "code": "capability_denied", "message": "This tool changes the environment, and this MCP client was approved for read-only access."}, "t3_thread_launch": {"_tag": "OrchestratorMcpFailure", "code": "capability_denied", "message": "This tool changes the environment, and this MCP client was approved for read-only access."}, "create_threads": {"_tag": "OrchestratorMcpFailure", "code": "capability_denied", "message": "This tool changes the environment, and this MCP client was approved for read-only access."}, "t3_environment_link": {"status": "pending", "turnItemId": "turn-item-link-card-1"}}}, "prompt": "Delegate this to my vps: run `uname -a` there and tell me the result. Do not edit any files here.", "expect": {"calls": [{"tool": "t3_environment_link", "args": {"environmentId": "environment-vps"}}], "callsMustNot": [{"tool": "t3_environment_link", "args": {"requestedAccess": null}}, {"tool": "t3_environment_link", "args": {"requestedAccess": "read-only"}}]}, "source": {"request": "review of pingdotgg/t3code#38633: agents were never told a link's access can be raised"}}
diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts
index e62da75913f8..bc44b8f43b9c 100644
--- a/packages/client-runtime/src/linkRequest.test.ts
+++ b/packages/client-runtime/src/linkRequest.test.ts
@@ -1,4 +1,10 @@
-import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts";
+import {
+ EnvironmentId,
+ type PeerLinkSummary,
+ type ServerConfig,
+ ThreadId,
+ TurnItemId,
+} from "@t3tools/contracts";
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { describe, expect, it } from "vite-plus/test";
@@ -80,20 +86,11 @@ describe("linkRequestAnswerInput", () => {
access: "auto",
pairingCode: "abc",
}),
- ).toMatchObject({ answer: { urls: ["https://box.ts.net"] } });
- // A machine known by name but typed in by address must still answer as that machine.
- expect(
- linkRequestAnswerInput(item, {
- type: "link",
- target: {
- url: "https://box.ts.net",
- machine: { environmentId: vps.environmentId, label: "VPS" },
- },
- access: "auto",
- pairingCode: "abc",
- }),
- ).toMatchObject({
- answer: { environmentId: vps.environmentId, label: "VPS", urls: ["https://box.ts.net"] },
+ ).toEqual({
+ threadId: item.threadId,
+ turnItemId: item.id,
+ // A typed address links alone: it names no machine, whatever the card names.
+ answer: { type: "link", urls: ["https://box.ts.net"], access: "auto", pairingCode: "abc" },
});
});
@@ -203,6 +200,17 @@ const discovered = (
error: Option.none(),
});
+const link = (
+ id: string,
+ options: Partial> = {},
+) => ({
+ environmentId: EnvironmentId.make(id),
+ label: options.label ?? id,
+ urls: options.urls ?? [],
+ status: options.status ?? "reachable",
+ access: options.access ?? "auto",
+});
+
describe("linkableMachines", () => {
it("lists the other machines with reported addresses before saved ones, once each", () => {
const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
@@ -216,7 +224,7 @@ describe("linkableMachines", () => {
linkableMachines({
environments: [here, vps, mini],
threadEnvironmentId: here.environmentId,
- links: [{ environmentId: mini.environmentId, status: "unreachable", access: "read-only" }],
+ links: [link(mini.environmentId, { status: "unreachable", access: "read-only" })],
connect: new Map(),
}),
).toEqual([
@@ -289,9 +297,9 @@ describe("linkableMachines", () => {
environments: [here, vps, mini],
threadEnvironmentId: here.environmentId,
links: [
- { environmentId: vps.environmentId, status: "expired", access: "auto" },
- { environmentId: mini.environmentId, status: "unreachable", access: "auto" },
- { environmentId: EnvironmentId.make("environment-old"), status: "expired", access: "auto" },
+ link(vps.environmentId, { status: "expired" }),
+ link(mini.environmentId, { status: "unreachable" }),
+ link("environment-old", { status: "expired" }),
],
connect: new Map([["environment-old", discovered("environment-old", "Old box")]]),
});
@@ -302,19 +310,64 @@ describe("linkableMachines", () => {
]);
});
- it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => {
+ it("offers where the environment linked a machine, and lists one only its link knows", () => {
const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
- const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
+ const vps = presentation("environment-vps", "VPS", { reported: ["https://vps.ts.net"] });
const listed = linkableMachines({
environments: [here, vps],
threadEnvironmentId: here.environmentId,
links: [
- {
- environmentId: EnvironmentId.make("environment-old"),
- status: "reachable",
- access: "auto",
- },
+ // The link's addresses come last, once each, and never this client's loopback.
+ link(vps.environmentId, {
+ urls: ["https://vps.ts.net", "https://vps.example.com", "http://127.0.0.1:3773"],
+ }),
+ link("environment-box", {
+ label: "Box",
+ urls: ["https://box.ts.net"],
+ access: "read-only",
+ }),
+ // An expired link still names the machine and where it answered, for linking it again.
+ link("environment-old", {
+ label: "Old box",
+ urls: ["https://old.ts.net"],
+ status: "expired",
+ }),
+ link("environment-local", { label: "Local", urls: ["http://localhost:3774"] }),
],
+ connect: new Map([["environment-box", discovered("environment-box", "Box")]]),
+ });
+ expect(listed).toEqual([
+ expect.objectContaining({
+ label: "VPS",
+ linkedAccess: "auto",
+ urls: ["https://vps.ts.net", "https://vps.example.com"],
+ }),
+ expect.objectContaining({
+ label: "Box",
+ connectOnly: true,
+ linkedAccess: "read-only",
+ urls: ["https://environment-box.t3.example", "https://box.ts.net"],
+ }),
+ {
+ environmentId: EnvironmentId.make("environment-old"),
+ label: "Old box",
+ machine: "server",
+ connected: false,
+ connectOnly: false,
+ linkedAccess: null,
+ urls: ["https://old.ts.net"],
+ },
+ expect.objectContaining({ label: "Local", linkedAccess: "auto", urls: [] }),
+ ]);
+ });
+
+ it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => {
+ const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
+ const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
+ const listed = linkableMachines({
+ environments: [here, vps],
+ threadEnvironmentId: here.environmentId,
+ links: [link("environment-old")],
connect: new Map([
// This environment and saved machines are listed once, as saved.
[here.environmentId, discovered(here.environmentId, "Here")],
@@ -495,28 +548,23 @@ describe("linkRequestTarget", () => {
expect(linkRequestTarget({}, [box], null)).toEqual({ kind: "none" });
});
- it("keeps a link the machine has only when it allows the access asked for", () => {
- const linked = { ...box, linkedAccess: "approval-required" } as const;
+ it("keeps a link the machine has unless the agent asked for more access than it allows", () => {
+ const linked = { ...box, linkedAccess: "read-only" } as const;
const target = linkRequestTarget({ environmentId: box.environmentId }, [linked], null);
+ // No access named: the agent takes the link as it is, as the server does without a card.
expect(linkRequestKeepsLink({}, target)).toBe(true);
expect(linkRequestKeepsLink({ requestedAccess: "read-only" }, target)).toBe(true);
- expect(linkRequestKeepsLink({ requestedAccess: "approval-required" }, target)).toBe(true);
// A weaker link is linked again, with the access the user picks.
+ expect(linkRequestKeepsLink({ requestedAccess: "approval-required" }, target)).toBe(false);
expect(linkRequestKeepsLink({ requestedAccess: "full-access" }, target)).toBe(false);
- // Asking for no access asks for the default, which read-only does not allow.
- const readOnly = { ...box, linkedAccess: "read-only" } as const;
- expect(
- linkRequestKeepsLink(
- {},
- linkRequestTarget({ environmentId: box.environmentId }, [readOnly], null),
- ),
- ).toBe(false);
+ // No link to keep.
expect(
linkRequestKeepsLink(
{},
linkRequestTarget({ environmentId: box.environmentId }, [box], null),
),
).toBe(false);
+ expect(linkRequestKeepsLink({}, { kind: "address" })).toBe(false);
});
});
diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts
index 0749cec25bba..9ffa8376270b 100644
--- a/packages/client-runtime/src/linkRequest.ts
+++ b/packages/client-runtime/src/linkRequest.ts
@@ -88,10 +88,10 @@ export interface LinkableMachine {
/** The access of the thread's environment's link to it, or null when it has none. */
readonly linkedAccess: AuthMcpClientAccess | null;
/**
- * Where the client knows it answers, most preferred first: the addresses it
- * reports, then its saved routes, then its T3 Connect address. The server
- * keeps only those that answer as this machine. Empty for a machine reached
- * only over SSH or loopback, which name this client's device.
+ * Where it answers, most preferred first: the addresses it reports, then its
+ * saved routes, then its T3 Connect address, then where the thread's environment
+ * linked it. The server keeps only those that answer as this machine. Empty for
+ * a machine reached only over SSH or loopback, which name this client's device.
*/
readonly urls: ReadonlyArray;
}
@@ -103,10 +103,10 @@ const isLoopbackUrl = (url: string) => {
};
/**
- * The catalog's machines other than the thread's own, in catalog order, then those only T3
- * Connect knows. `links` are the thread environment's; an expired one no longer counts as
- * linked. `connect` is what relay discovery found, and a server reaches a machine there as a
- * browser does, so its Connect address is usable.
+ * The catalog's machines other than the thread's own, then those only T3 Connect knows, then
+ * those only the thread environment's links know. An expired link no longer counts as linked,
+ * but still names the machine and where the environment reached it. A server reaches a machine
+ * on T3 Connect as a browser does, so its Connect address is usable.
*/
export function linkableMachines(input: {
readonly environments: ReadonlyArray<
@@ -114,14 +114,19 @@ export function linkableMachines(input: {
>;
/** Null lists every machine, for a view that is not about one environment. */
readonly threadEnvironmentId: EnvironmentId | null;
- readonly links: ReadonlyArray>;
+ readonly links: ReadonlyArray<
+ Pick
+ >;
readonly connect: ReadonlyMap;
}): ReadonlyArray {
- const linkedAccess = new Map(
- input.links.flatMap((link) =>
- link.status === "expired" ? [] : [[link.environmentId, link.access] as const],
- ),
- );
+ const links = new Map(input.links.map((link) => [link.environmentId as string, link]));
+ const linkedAccess = (environmentId: string) => {
+ const link = links.get(environmentId);
+ return link === undefined || link.status === "expired" ? null : link.access;
+ };
+ const linkUrls = (environmentId: string) => links.get(environmentId)?.urls ?? [];
+ const usable = (urls: ReadonlyArray) =>
+ [...new Set(urls)].filter((url) => !isLoopbackUrl(url));
const saved = input.environments
.filter((environment) => environment.environmentId !== input.threadEnvironmentId)
.map((environment) => {
@@ -139,23 +144,19 @@ export function linkableMachines(input: {
machine: resolveEnvironmentMachineKind(environment.serverConfig),
connected: environment.connection.phase === "connected",
connectOnly: false,
- linkedAccess: linkedAccess.get(environment.environmentId) ?? null,
- urls: [
- ...new Set([
- ...reported,
- ...routes,
- ...(connect === undefined ? [] : [connect.httpBaseUrl]),
- ]),
- ].filter((url) => !isLoopbackUrl(url)),
+ linkedAccess: linkedAccess(environment.environmentId),
+ urls: usable([
+ ...reported,
+ ...routes,
+ ...(connect === undefined ? [] : [connect.httpBaseUrl]),
+ ...linkUrls(environment.environmentId),
+ ]),
};
});
- const savedIds = new Set(saved.map((machine) => machine.environmentId));
+ const known = new Set(saved.map((m) => m.environmentId));
+ if (input.threadEnvironmentId !== null) known.add(input.threadEnvironmentId);
const connectOnly = [...input.connect.values()]
- .filter(
- ({ environment }) =>
- environment.environmentId !== input.threadEnvironmentId &&
- !savedIds.has(environment.environmentId),
- )
+ .filter(({ environment }) => !known.has(environment.environmentId))
.map(({ environment, status }) => {
const descriptor = Option.getOrUndefined(status)?.descriptor;
return {
@@ -166,11 +167,23 @@ export function linkableMachines(input: {
),
connected: false,
connectOnly: true,
- linkedAccess: linkedAccess.get(environment.environmentId) ?? null,
- urls: [environment.endpoint.httpBaseUrl].filter((url) => !isLoopbackUrl(url)),
+ linkedAccess: linkedAccess(environment.environmentId),
+ urls: usable([environment.endpoint.httpBaseUrl, ...linkUrls(environment.environmentId)]),
};
});
- return [...saved, ...connectOnly];
+ for (const machine of connectOnly) known.add(machine.environmentId);
+ const linkOnly = input.links
+ .filter((link) => !known.has(link.environmentId))
+ .map((link) => ({
+ environmentId: link.environmentId,
+ label: link.label,
+ machine: resolveEnvironmentMachineKind(null),
+ connected: false,
+ connectOnly: false,
+ linkedAccess: linkedAccess(link.environmentId),
+ urls: usable(link.urls),
+ }));
+ return [...saved, ...connectOnly, ...linkOnly];
}
const words = (text: string) =>
@@ -279,8 +292,9 @@ export function linkRequestTarget(
}
/**
- * Whether the card answers with the link its machine already has: only one with at least the
- * access asked for, else the default. Linking again over a weaker one renews it.
+ * Whether the card answers with the link its machine already has. An agent that asks for
+ * more access than the link has gets it linked again, which raises it; one that names no
+ * access takes the link as it is.
*/
export const linkRequestKeepsLink = (
item: Pick,
@@ -288,7 +302,8 @@ export const linkRequestKeepsLink = (
): boolean =>
target.kind === "machine" &&
target.linkedAccess !== null &&
- mcpClientAccessCovers(target.linkedAccess, linkRequestDefaultAccess(item));
+ (item.requestedAccess === undefined ||
+ mcpClientAccessCovers(target.linkedAccess, item.requestedAccess));
/** What a link request card shows: the actions while pending, otherwise a one-line outcome. */
export type LinkRequestDisplay =
@@ -362,15 +377,12 @@ export function linkRequestAnswerInput(
| {
readonly type: "link";
/**
- * The machine picked, or an address typed in its place: for a machine this app knows
- * by name but has no address for, the link must still answer as that machine.
+ * The machine picked, or an address typed in its place. A typed address links
+ * alone, whatever machine the card names: only this app's own addresses name one.
*/
readonly target:
| Pick
- | {
- readonly url: string;
- readonly machine?: Pick;
- };
+ | { readonly url: string };
readonly access: AuthMcpClientAccess;
readonly pairingCode: string;
}
@@ -385,16 +397,7 @@ export function linkRequestAnswerInput(
if ("url" in target) {
const url = target.url.trim();
if (url.length === 0) return null;
- return {
- ...base,
- answer: {
- type: "link",
- ...target.machine,
- urls: [url],
- access: answer.access,
- pairingCode,
- },
- };
+ return { ...base, answer: { type: "link", urls: [url], access: answer.access, pairingCode } };
}
const [first, ...rest] = target.urls;
if (first === undefined) return null;
From 47e51368f0b1cbc16fefee6589ed3501618c7d9c Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 18 Nov 2026 19:42:50 +0000
Subject: [PATCH 5/5] fix(server): keep the environment link tool description
within the context budget
The raised-access guidance grew the MCP tool list by 94 bytes and failed
the Agent Context Budget gate. Say the same in fewer words.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/mcp/toolkits/orchestrator/tools.ts | 2 +-
apps/server/src/provider/agentContextBudget.json | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index 6a1ee280c3d1..e53793a54af1 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -336,7 +336,7 @@ const EnvironmentLinksTool = Tool.make("t3_environment_links", {
const EnvironmentLinkTool = Tool.make("t3_environment_link", {
description:
- "Ask the user to link another machine, in a card. For a machine the user names that is not linked, or linked with less access than the work needs. Pass `hint` from their words, `environmentId` when one names it (already linked: returns `linked`, unless `requestedAccess` is above the link's), `url` only when the user gave an address. Returns `pending`; the outcome arrives as a message in this thread. Do not wait, poll, or call it again to check. Never ask for a pairing code in chat.",
+ "Ask the user, in a card, to link a machine they name that is unlinked or linked below the access needed. Pass `hint` from their words, `environmentId` when one names it (returns `linked` if it has `requestedAccess`), `url` only if the user gave one. Returns `pending`; the outcome arrives as a message here. Do not wait, poll, or call it again. Never ask for a pairing code in chat.",
parameters: OrchestratorMcpEnvironmentLinkInput,
success: OrchestratorMcpEnvironmentLinkResult,
failure: OrchestratorMcpFailure,
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index 902878e0c577..d75f8f60a3ff 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 6245,
"codexAdditionalContextBytes": 7639,
- "mcpToolListJsonBytes": 57845
+ "mcpToolListJsonBytes": 57742
}