From 9972fbd14b6c76b439c4d944ff3ac4e56bf3ddad Mon Sep 17 00:00:00 2001
From: Orin
Date: Wed, 18 Nov 2026 06:20:15 -0800
Subject: [PATCH 1/8] 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 1ee34663431b8..bc59b741ea66c 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 a33bb47d7ec17..6f6f64668aed4 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 81c25774a9000..86fd16626786e 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 e62da75913f8b..bc44b8f43b9c2 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 0749cec25bba7..9ffa8376270bb 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/8] 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 6a1ee280c3d1d..e53793a54af1a 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 902878e0c5777..d75f8f60a3ffd 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
}
From 0a9ac398a02bde8afd8aa0531a8c89f561489d78 Mon Sep 17 00:00:00 2001
From: Orin
Date: Sun, 22 Nov 2026 17:48:40 -0800
Subject: [PATCH 6/8] fix(web,mobile): auto-minted pairing codes go only to
addresses this client knows
Machines in the link pickers had the thread environment's peer-link
addresses merged into their own. A machine reached only over SSH, or one
whose own addresses did not answer, could then get a pairing code minted
by this client and sent to an address that only claimed to be it.
Link addresses now stay in their own `linkUrls`. They still spare the user
from typing an address, but a minted code goes only to the client's own
addresses, and an address an agent names matches a machine only there.
Co-Authored-By: Claude Opus 5.5
---
.../src/features/threads/LinkRequestCard.tsx | 16 +++++---
.../src/components/chat/LinkRequestCard.tsx | 16 +++++---
.../settings/LinkedEnvironmentsSettings.tsx | 19 +++++++---
packages/client-runtime/src/linkBatch.test.ts | 1 +
.../client-runtime/src/linkRequest.test.ts | 33 +++++++++++++---
packages/client-runtime/src/linkRequest.ts | 38 ++++++++++++++-----
6 files changed, 91 insertions(+), 32 deletions(-)
diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx
index bc59b741ea66c..10020827193e0 100644
--- a/apps/mobile/src/features/threads/LinkRequestCard.tsx
+++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx
@@ -11,6 +11,7 @@ import {
type LinkRequestItem,
linkRequestKeepsLink,
linkRequestTarget,
+ linkTargetUrls,
rankMachinesByHint,
} from "@t3tools/client-runtime/link-request";
import {
@@ -234,13 +235,15 @@ function LinkRequestSheet(props: {
const connected = usePreparedConnection(targetId);
const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
const needsAddress =
- target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
+ target.kind === "address" ||
+ (target.kind === "machine" && target.urls.length === 0 && target.linkUrls.length === 0);
// This phone mints a code there when it is connected with a session that may
- // create pairing links, and only for its own addresses: anything can answer
- // as that machine at one typed in, so that one gets a code the user fetched.
+ // create pairing links, and only for its own addresses: anything can answer as
+ // that machine at one typed in or only a link reached, so those get a code the user fetched.
const canMint =
targetId !== null &&
- !needsAddress &&
+ target.kind === "machine" &&
+ target.urls.length > 0 &&
Option.isSome(connected) &&
mayMint &&
!mintFailed.has(targetId);
@@ -270,7 +273,10 @@ function LinkRequestSheet(props: {
}
return linkRequestAnswerInput(item, {
type: "link",
- target: target.kind === "machine" && target.urls.length > 0 ? target : { url: address },
+ target:
+ target.kind === "machine" && !needsAddress
+ ? { ...target, urls: linkTargetUrls(target, canMint) }
+ : { url: address },
access,
pairingCode: code,
});
diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx
index 86fd16626786e..3c52f66185e1b 100644
--- a/apps/web/src/components/chat/LinkRequestCard.tsx
+++ b/apps/web/src/components/chat/LinkRequestCard.tsx
@@ -12,6 +12,7 @@ import {
linkRequestKeepsLink,
linkRequestTarget,
linkRequestTargetName,
+ linkTargetUrls,
rankMachinesByHint,
} from "@t3tools/client-runtime/link-request";
import {
@@ -221,13 +222,15 @@ function LinkRequestDialog(props: {
const connected = usePreparedConnection(targetId);
const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
const needsAddress =
- target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
+ target.kind === "address" ||
+ (target.kind === "machine" && target.urls.length === 0 && target.linkUrls.length === 0);
// This client mints a code there when it is connected with a session that may
- // create pairing links, and only for its own addresses: anything can answer
- // as that machine at one typed in, so that one gets a code the user fetched.
+ // create pairing links, and only for its own addresses: anything can answer as
+ // that machine at one typed in or only a link reached, so those get a code the user fetched.
const canMint =
targetId !== null &&
- !needsAddress &&
+ target.kind === "machine" &&
+ target.urls.length > 0 &&
Option.isSome(connected) &&
mayMint &&
!mintFailed.has(targetId);
@@ -278,7 +281,10 @@ function LinkRequestDialog(props: {
}
return linkRequestAnswerInput(item, {
type: "link",
- target: target.kind === "machine" && target.urls.length > 0 ? target : { url: address },
+ target:
+ target.kind === "machine" && !needsAddress
+ ? { ...target, urls: linkTargetUrls(target, canMint) }
+ : { url: address },
access,
pairingCode: code,
});
diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
index e5a53cc33ce94..199a3b6966f53 100644
--- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
+++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
@@ -4,7 +4,11 @@ import {
linkBatchFailureLabel,
linkWithMintedCode,
} from "@t3tools/client-runtime/link-batch";
-import { ANOTHER_ADDRESS, linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
+import {
+ ANOTHER_ADDRESS,
+ linkRequestFailureMessage,
+ linkTargetUrls,
+} from "@t3tools/client-runtime/link-request";
import {
AuthAccessWriteScope,
type AuthMcpClientAccess,
@@ -273,6 +277,7 @@ export function LinkEnvironmentDialog({
connectOnly: false,
linkedAccess: null,
urls: route.urls,
+ linkUrls: [],
})),
];
// Null until the user picks; with no other machines known, only an address is left.
@@ -315,13 +320,15 @@ export function LinkEnvironmentDialog({
const connected = usePreparedConnection(targetId);
const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
// A picked machine that left the list has no address here either.
- const needsAddress = selected !== null && (machine === null || machine.urls.length === 0);
+ const needsAddress =
+ selected !== null &&
+ (machine === null || (machine.urls.length === 0 && machine.linkUrls.length === 0));
// This client mints a code there when it is connected with a session that may
- // create pairing links, and only for its own addresses: anything can answer
- // as that machine at one typed in, so that one gets a code the user fetched.
+ // create pairing links, and only for its own addresses: anything can answer as
+ // that machine at one typed in or only a link reached, so those get a code the user fetched.
const canMint =
targetId !== null &&
- !needsAddress &&
+ (machine?.urls.length ?? 0) > 0 &&
Option.isSome(connected) &&
mayMint &&
!mintFailed.has(targetId);
@@ -395,7 +402,7 @@ export function LinkEnvironmentDialog({
};
const submit = async () => {
const [url, ...alternateUrls] =
- machine === null || needsAddress ? [address.trim()] : machine.urls;
+ machine === null || needsAddress ? [address.trim()] : linkTargetUrls(machine, canMint);
if (inFlight.current || !ready || url === undefined) return;
inFlight.current = true;
setBusy(true);
diff --git a/packages/client-runtime/src/linkBatch.test.ts b/packages/client-runtime/src/linkBatch.test.ts
index 10140127bbca6..614bfe5f532ad 100644
--- a/packages/client-runtime/src/linkBatch.test.ts
+++ b/packages/client-runtime/src/linkBatch.test.ts
@@ -19,6 +19,7 @@ const machine = (name: string, overrides: Partial = {}): Linkab
connectOnly: false,
linkedAccess: null,
urls: [`https://${name}.example.ts.net`, `http://100.64.0.1:3773`],
+ linkUrls: [],
...overrides,
});
const id = (name: string) => EnvironmentId.make(`environment-${name}`);
diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts
index bc44b8f43b9c2..d2c3bdc32354a 100644
--- a/packages/client-runtime/src/linkRequest.test.ts
+++ b/packages/client-runtime/src/linkRequest.test.ts
@@ -24,6 +24,7 @@ import {
linkRequestKeepsLink,
linkRequestTarget,
linkRequestTargetName,
+ linkTargetUrls,
rankMachinesByHint,
} from "./linkRequest.ts";
@@ -236,6 +237,7 @@ describe("linkableMachines", () => {
connectOnly: false,
linkedAccess: null,
urls: ["https://vps.ts.net", "https://vps.example.com"],
+ linkUrls: [],
},
{
environmentId: mini.environmentId,
@@ -245,6 +247,7 @@ describe("linkableMachines", () => {
connectOnly: false,
linkedAccess: "read-only",
urls: [],
+ linkUrls: [],
},
]);
});
@@ -310,14 +313,15 @@ describe("linkableMachines", () => {
]);
});
- it("offers where the environment linked a machine, and lists one only its link knows", () => {
+ it("keeps where only the environment's link reached a machine apart from its own addresses", () => {
const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
const vps = presentation("environment-vps", "VPS", { reported: ["https://vps.ts.net"] });
const listed = linkableMachines({
environments: [here, vps],
threadEnvironmentId: here.environmentId,
links: [
- // The link's addresses come last, once each, and never this client's loopback.
+ // Anything can answer as the VPS where only the link reached it: kept apart, 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"],
}),
@@ -340,13 +344,15 @@ describe("linkableMachines", () => {
expect.objectContaining({
label: "VPS",
linkedAccess: "auto",
- urls: ["https://vps.ts.net", "https://vps.example.com"],
+ urls: ["https://vps.ts.net"],
+ linkUrls: ["https://vps.example.com"],
}),
expect.objectContaining({
label: "Box",
connectOnly: true,
linkedAccess: "read-only",
- urls: ["https://environment-box.t3.example", "https://box.ts.net"],
+ urls: ["https://environment-box.t3.example"],
+ linkUrls: ["https://box.ts.net"],
}),
{
environmentId: EnvironmentId.make("environment-old"),
@@ -355,9 +361,16 @@ describe("linkableMachines", () => {
connected: false,
connectOnly: false,
linkedAccess: null,
- urls: ["https://old.ts.net"],
+ urls: [],
+ linkUrls: ["https://old.ts.net"],
},
- expect.objectContaining({ label: "Local", linkedAccess: "auto", urls: [] }),
+ expect.objectContaining({ label: "Local", linkedAccess: "auto", urls: [], linkUrls: [] }),
+ ]);
+ // A code this client mints goes only to its own addresses; one the user fetched, to both.
+ expect(linkTargetUrls(listed[0]!, true)).toEqual(["https://vps.ts.net"]);
+ expect(linkTargetUrls(listed[0]!, false)).toEqual([
+ "https://vps.ts.net",
+ "https://vps.example.com",
]);
});
@@ -389,6 +402,7 @@ describe("linkableMachines", () => {
connectOnly: true,
linkedAccess: null,
urls: ["https://environment-mini.t3.example"],
+ linkUrls: [],
});
expect(listed[2]).toMatchObject({ machine: "server", linkedAccess: "auto" });
@@ -468,6 +482,7 @@ describe("rankMachinesByHint", () => {
connectOnly: false,
linkedAccess: null,
urls: [],
+ linkUrls: [],
}) as const,
);
expect(linkRequestInitialMachine({ hint: "vps" }, listed)).toBe("environment-vps");
@@ -497,6 +512,7 @@ describe("linkRequestTarget", () => {
connectOnly: false,
linkedAccess: null,
urls: ["http://10.0.0.2:3773", "https://box.t3connect.example/"],
+ linkUrls: ["https://box.peer.example"],
} as const;
it("takes a machine from an address the agent gave only where this app already reaches it", () => {
@@ -508,6 +524,10 @@ describe("linkRequestTarget", () => {
};
expect(linkRequestTarget(unfamiliar, [box], null)).toEqual({ kind: "address" });
expect(linkRequestTarget(unfamiliar, [box], box.environmentId)).toEqual({ kind: "address" });
+ // Nor is an address only the environment's link reached it at.
+ expect(linkRequestTarget({ url: "https://box.peer.example" }, [box], null)).toEqual({
+ kind: "address",
+ });
expect(linkRequestTargetName(unfamiliar)).toBe("https://other.example");
// A username in the address must not pass for the host the code goes to.
expect(linkRequestTargetName({ url: "https://box.t3connect.example@other.example/x" })).toBe(
@@ -521,6 +541,7 @@ describe("linkRequestTarget", () => {
environmentId: box.environmentId,
label: "Box",
urls: box.urls,
+ linkUrls: box.linkUrls,
linkedAccess: null,
});
expect(linkRequestTarget({ url: "http://box.t3connect.example" }, [box], null)).toEqual({
diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts
index 9ffa8376270bb..cea1c945b3233 100644
--- a/packages/client-runtime/src/linkRequest.ts
+++ b/packages/client-runtime/src/linkRequest.ts
@@ -88,14 +88,25 @@ 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 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.
+ * Where this 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.
*/
readonly urls: ReadonlyArray;
+ /**
+ * Where only the thread's environment's link reached it. Anything can answer
+ * there as this machine, so a code this client mints never goes to them.
+ */
+ readonly linkUrls: ReadonlyArray;
}
+/** Where a link sends its pairing code: one this client minted goes only to its own addresses. */
+export const linkTargetUrls = (
+ machine: Pick,
+ minted: boolean,
+): ReadonlyArray => (minted ? machine.urls : [...machine.urls, ...machine.linkUrls]);
+
/** A loopback address names whichever machine opens it: the linking server, not this one. */
const isLoopbackUrl = (url: string) => {
const hostname = parsedUrl(url)?.hostname;
@@ -124,9 +135,15 @@ export function linkableMachines(input: {
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 addresses = (environmentId: string, own: ReadonlyArray) => {
+ const urls = usable(own);
+ const linkUrls = usable(links.get(environmentId)?.urls ?? []).filter(
+ (url) => !urls.includes(url),
+ );
+ return { urls, linkUrls };
+ };
const saved = input.environments
.filter((environment) => environment.environmentId !== input.threadEnvironmentId)
.map((environment) => {
@@ -145,11 +162,10 @@ export function linkableMachines(input: {
connected: environment.connection.phase === "connected",
connectOnly: false,
linkedAccess: linkedAccess(environment.environmentId),
- urls: usable([
+ ...addresses(environment.environmentId, [
...reported,
...routes,
...(connect === undefined ? [] : [connect.httpBaseUrl]),
- ...linkUrls(environment.environmentId),
]),
};
});
@@ -168,7 +184,7 @@ export function linkableMachines(input: {
connected: false,
connectOnly: true,
linkedAccess: linkedAccess(environment.environmentId),
- urls: usable([environment.endpoint.httpBaseUrl, ...linkUrls(environment.environmentId)]),
+ ...addresses(environment.environmentId, [environment.endpoint.httpBaseUrl]),
};
});
for (const machine of connectOnly) known.add(machine.environmentId);
@@ -181,7 +197,7 @@ export function linkableMachines(input: {
connected: false,
connectOnly: false,
linkedAccess: linkedAccess(link.environmentId),
- urls: usable(link.urls),
+ ...addresses(link.environmentId, []),
}));
return [...saved, ...connectOnly, ...linkOnly];
}
@@ -242,7 +258,7 @@ export const ANOTHER_ADDRESS = "another-address";
/**
* What a link request links: a machine from the client's catalog, or an address.
- * `urls` is empty when the client knows no direct address for the machine,
+ * With neither `urls` nor `linkUrls`, nothing knows an address for the machine,
* so the user types one.
*/
export type LinkRequestTarget =
@@ -252,6 +268,7 @@ export type LinkRequestTarget =
readonly environmentId: EnvironmentId;
readonly label: string;
readonly urls: ReadonlyArray;
+ readonly linkUrls: ReadonlyArray;
readonly linkedAccess: AuthMcpClientAccess | null;
}
| { readonly kind: "address" };
@@ -287,6 +304,7 @@ export function linkRequestTarget(
environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
label: machine?.label ?? linkRequestTargetName(item, resolve),
urls: machine?.urls ?? [],
+ linkUrls: machine?.linkUrls ?? [],
linkedAccess: machine?.linkedAccess ?? null,
};
}
From ee87bddd6885aae315555fe7b2e63cf30aea3caf Mon Sep 17 00:00:00 2001
From: Orin
Date: Sun, 22 Nov 2026 17:58:49 -0800
Subject: [PATCH 7/8] fix(server): keeping a link answers a card only when it
covers the access asked
The server accepted "use this link" for any unexpired link, even one with
less access than the card asked for. A client with a stale list of links
could record a read-only link as the answer to a full-access request, and
the agent woke believing it had that access.
The answer now checks the link against the card's requested access. A link
that falls short fails with a new `link_too_weak` reason and the card stays
open to link again. The cards translate it in every locale.
Co-Authored-By: Claude Opus 5.5
---
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 | 15 +++++++++++++++
apps/server/src/peer/PeerLinkRequests.ts | 14 ++++++++++----
apps/web/src/i18n/translations/de.json | 1 +
apps/web/src/i18n/translations/en.json | 1 +
apps/web/src/i18n/translations/es.json | 1 +
apps/web/src/i18n/translations/fr.json | 1 +
apps/web/src/i18n/translations/ja.json | 1 +
apps/web/src/i18n/translations/ko.json | 1 +
apps/web/src/i18n/translations/pt-BR.json | 1 +
apps/web/src/i18n/translations/ru.json | 1 +
apps/web/src/i18n/translations/sv.json | 1 +
apps/web/src/i18n/translations/zh.json | 1 +
packages/client-runtime/src/linkRequest.ts | 14 ++++++++++----
packages/contracts/src/peerLink.ts | 1 +
24 files changed, 56 insertions(+), 8 deletions(-)
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 8c35325ec522f..0b172dda8fc61 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Verknüpfen fehlgeschlagen: {failure}",
"acd01e781e2355cc": "Anfrage beendet",
"8855350e81d45c45": "Diese Verknüpfung wurde entfernt oder ist abgelaufen. Verknüpfe den Computer erneut.",
+ "c3e4bd0213cdc043": "Diese Verknüpfung erlaubt weniger, als diese Anfrage verlangt. Verknüpfe den Computer erneut.",
"97e4c50a99272f63": "Die Anfrage konnte nicht beantwortet werden. Versuche es erneut.",
"605a491783d18b3f": "Dieser Thread konnte nicht über {via} gelesen werden",
"50f19209548b70d9": "{via} braucht möglicherweise ein Update, bevor es verknüpfte Threads lesen kann.",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index eb0d0a62a512c..6b4771d2ca092 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Could not link: {failure}",
"acd01e781e2355cc": "Request ended",
"8855350e81d45c45": "That link was removed or expired. Link the machine again.",
+ "c3e4bd0213cdc043": "That link allows less than this request asks for. Link the machine again.",
"97e4c50a99272f63": "Could not answer the request. Try again.",
"605a491783d18b3f": "Could not read this thread through {via}",
"50f19209548b70d9": "{via} may need an update before it can read linked threads.",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index 1a3f9111fc753..c263fe8dbb128 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "No se pudo vincular: {failure}",
"acd01e781e2355cc": "Solicitud finalizada",
"8855350e81d45c45": "Ese vínculo se eliminó o caducó. Vuelve a vincular la máquina.",
+ "c3e4bd0213cdc043": "Ese vínculo permite menos de lo que pide esta solicitud. Vuelve a vincular la máquina.",
"97e4c50a99272f63": "No se pudo responder a la solicitud. Inténtalo de nuevo.",
"605a491783d18b3f": "No se pudo leer este hilo a través de {via}",
"50f19209548b70d9": "Puede que {via} necesite actualizarse para poder leer hilos vinculados.",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index eb407628c4225..9613cf0a85fdd 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Association impossible : {failure}",
"acd01e781e2355cc": "Demande terminée",
"8855350e81d45c45": "Cette association a été supprimée ou a expiré. Associez à nouveau la machine.",
+ "c3e4bd0213cdc043": "Cette association autorise moins que ce que demande cette requête. Associez à nouveau la machine.",
"97e4c50a99272f63": "Impossible de répondre à la demande. Réessayez.",
"605a491783d18b3f": "Impossible de lire ce fil via {via}",
"50f19209548b70d9": "{via} a peut-être besoin d’une mise à jour pour lire les fils associés.",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index 9ff3a8cf8157c..8ccbb77001a2c 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "リンクできませんでした: {failure}",
"acd01e781e2355cc": "リクエストが終了しました",
"8855350e81d45c45": "そのリンクは削除されたか、期限切れです。マシンをもう一度リンクしてください。",
+ "c3e4bd0213cdc043": "そのリンクで許可されている範囲は、このリクエストが求める範囲より狭いです。マシンをもう一度リンクしてください。",
"97e4c50a99272f63": "リクエストに応答できませんでした。もう一度お試しください。",
"605a491783d18b3f": "{via} 経由でこのスレッドを読み取れませんでした",
"50f19209548b70d9": "リンクされたスレッドを読み取るには、{via} の更新が必要な可能性があります。",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index 751adad6aaac7..18eb2ed15d3ad 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "연결할 수 없음: {failure}",
"acd01e781e2355cc": "요청 종료됨",
"8855350e81d45c45": "해당 연결이 삭제되었거나 만료되었습니다. 머신을 다시 연결하세요.",
+ "c3e4bd0213cdc043": "해당 연결은 이 요청이 요구하는 것보다 적은 권한만 허용합니다. 머신을 다시 연결하세요.",
"97e4c50a99272f63": "요청에 응답할 수 없습니다. 다시 시도하세요.",
"605a491783d18b3f": "{via}을(를) 통해 이 스레드를 읽지 못했습니다",
"50f19209548b70d9": "연결된 스레드를 읽으려면 {via}을(를) 업데이트해야 할 수 있습니다.",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 1cfa1a855d9b3..0493a48f4bebf 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Não foi possível vincular: {failure}",
"acd01e781e2355cc": "Solicitação encerrada",
"8855350e81d45c45": "Esse vínculo foi removido ou expirou. Vincule a máquina novamente.",
+ "c3e4bd0213cdc043": "Esse vínculo permite menos do que esta solicitação pede. Vincule a máquina novamente.",
"97e4c50a99272f63": "Não foi possível responder à solicitação. Tente novamente.",
"605a491783d18b3f": "Não foi possível ler esta thread por {via}",
"50f19209548b70d9": "Talvez {via} precise de uma atualização para ler threads vinculadas.",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index d99e486c0d8f9..df2a3e62d154e 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Не удалось привязать: {failure}",
"acd01e781e2355cc": "Запрос завершён",
"8855350e81d45c45": "Эта привязка удалена или истекла. Привяжите машину снова.",
+ "c3e4bd0213cdc043": "Эта привязка разрешает меньше, чем требует этот запрос. Привяжите машину снова.",
"97e4c50a99272f63": "Не удалось ответить на запрос. Повторите попытку.",
"605a491783d18b3f": "Не удалось прочитать этот тред через {via}",
"50f19209548b70d9": "Возможно, {via} нужно обновить, чтобы читать привязанные треды.",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index cd8d97284dffa..25952de28f26d 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Kunde inte länka: {failure}",
"acd01e781e2355cc": "Begäran avslutades",
"8855350e81d45c45": "Länken har tagits bort eller gått ut. Länka maskinen igen.",
+ "c3e4bd0213cdc043": "Länken tillåter mindre än den här begäran kräver. Länka maskinen igen.",
"97e4c50a99272f63": "Kunde inte svara på begäran. Försök igen.",
"605a491783d18b3f": "Det gick inte att läsa den här tråden via {via}",
"50f19209548b70d9": "{via} kan behöva uppdateras innan den kan läsa länkade trådar.",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 70555fb0bcbc4..30433dc6f4869 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "无法关联:{failure}",
"acd01e781e2355cc": "请求已结束",
"8855350e81d45c45": "该关联已被移除或已过期。请重新关联这台机器。",
+ "c3e4bd0213cdc043": "该关联允许的权限低于此请求的要求。请重新关联这台机器。",
"97e4c50a99272f63": "无法回复此请求。请重试。",
"605a491783d18b3f": "无法通过 {via} 读取此会话",
"50f19209548b70d9": "{via} 可能需要更新后才能读取关联的会话。",
diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts
index 9b7bf8e633abf..60593343c9349 100644
--- a/apps/server/src/peer/PeerLinkRequests.test.ts
+++ b/apps/server/src/peer/PeerLinkRequests.test.ts
@@ -1112,6 +1112,21 @@ it.live("a machine linked with less access than asked goes through the card, whi
}
expect((yield* linkCards(a)).filter((item) => item.linkStatus === "pending")).toEqual([card]);
+ // Keeping a link with less access than asked is no answer, from a client whose list
+ // still shows it covering the request say; the card stays open to link again.
+ const kept = yield* a.requests
+ .answer({
+ threadId,
+ turnItemId: card.id,
+ answer: { type: "use-existing", environmentId: box.environmentId },
+ })
+ .pipe(Effect.flip);
+ expect(kept.reason).toBe("link_too_weak");
+ expect((yield* linkCards(a)).find((item) => item.id === card.id)).toMatchObject({
+ linkStatus: "pending",
+ });
+ expect((yield* outcomeMessages(a)).messages).toHaveLength(0);
+
// Linking again over the old link replaces it; nothing is unlinked first.
const pairing = yield* b.auth.issuePairingCredential();
yield* a.requests.answer({
diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts
index 7123d001d6ecf..2fea5fea9d590 100644
--- a/apps/server/src/peer/PeerLinkRequests.ts
+++ b/apps/server/src/peer/PeerLinkRequests.ts
@@ -5,6 +5,7 @@
* (provider CLIs abandon a long tool call): the answer reaches the agent as a notification.
*/
import {
+ type AuthMcpClientAccess,
CommandId,
type EnvironmentId,
mcpClientAccessCovers,
@@ -305,19 +306,24 @@ const make = Effect.gen(function* () {
/** Links the machine the user picked, or finds the link they chose to keep. */
const answerOutcome = (
answer: PeerLinkRequestAnswerInput["answer"],
+ requestedAccess: AuthMcpClientAccess | undefined,
): 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.
+ // A client's list of links can lag one removed or replaced 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 PeerLinkRequestError({ reason: "link_gone" })),
- onSome: (linked) => Effect.succeed(linkedOutcome(linked)),
+ onSome: (linked) =>
+ requestedAccess === undefined ||
+ mcpClientAccessCovers(linked.access, requestedAccess)
+ ? Effect.succeed(linkedOutcome(linked))
+ : Effect.fail(new PeerLinkRequestError({ reason: "link_too_weak" })),
}),
),
);
@@ -378,7 +384,7 @@ const make = Effect.gen(function* () {
linkStatus: "failed",
failure: "This request is from before an update. Ask for the link again.",
}
- : yield* answerOutcome(input.answer);
+ : yield* answerOutcome(input.answer, card.requestedAccess);
// If Stop closed the card while linking, the card keeps that; the link
// itself stands and Settings lists it.
yield* lifecycleLocks.withLock(
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 636d26fdcbcda..bb01f66dc6c19 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Verknüpfen fehlgeschlagen: {failure}",
"acd01e781e2355cc": "Anfrage beendet",
"8855350e81d45c45": "Diese Verknüpfung wurde entfernt oder ist abgelaufen. Verknüpfe den Computer erneut.",
+ "c3e4bd0213cdc043": "Diese Verknüpfung erlaubt weniger, als diese Anfrage verlangt. Verknüpfe den Computer erneut.",
"97e4c50a99272f63": "Die Anfrage konnte nicht beantwortet werden. Versuche es erneut.",
"605a491783d18b3f": "Dieser Thread konnte nicht über {via} gelesen werden",
"50f19209548b70d9": "{via} braucht möglicherweise ein Update, bevor es verknüpfte Threads lesen kann.",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index cc03957edba15..3f7063eb86f15 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Could not link: {failure}",
"acd01e781e2355cc": "Request ended",
"8855350e81d45c45": "That link was removed or expired. Link the machine again.",
+ "c3e4bd0213cdc043": "That link allows less than this request asks for. Link the machine again.",
"97e4c50a99272f63": "Could not answer the request. Try again.",
"605a491783d18b3f": "Could not read this thread through {via}",
"50f19209548b70d9": "{via} may need an update before it can read linked threads.",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index a8b057913df05..b4b7b37b523bb 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "No se pudo vincular: {failure}",
"acd01e781e2355cc": "Solicitud finalizada",
"8855350e81d45c45": "Ese vínculo se eliminó o caducó. Vuelve a vincular la máquina.",
+ "c3e4bd0213cdc043": "Ese vínculo permite menos de lo que pide esta solicitud. Vuelve a vincular la máquina.",
"97e4c50a99272f63": "No se pudo responder a la solicitud. Inténtalo de nuevo.",
"605a491783d18b3f": "No se pudo leer este hilo a través de {via}",
"50f19209548b70d9": "Puede que {via} necesite actualizarse para poder leer hilos vinculados.",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 17eb85696fd30..bd14a16762820 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Association impossible : {failure}",
"acd01e781e2355cc": "Demande terminée",
"8855350e81d45c45": "Cette association a été supprimée ou a expiré. Associez à nouveau la machine.",
+ "c3e4bd0213cdc043": "Cette association autorise moins que ce que demande cette requête. Associez à nouveau la machine.",
"97e4c50a99272f63": "Impossible de répondre à la demande. Réessayez.",
"605a491783d18b3f": "Impossible de lire ce fil via {via}",
"50f19209548b70d9": "{via} a peut-être besoin d’une mise à jour pour lire les fils associés.",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 777b3b91719f6..ad9272baba618 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "リンクできませんでした: {failure}",
"acd01e781e2355cc": "リクエストが終了しました",
"8855350e81d45c45": "そのリンクは削除されたか、期限切れです。マシンをもう一度リンクしてください。",
+ "c3e4bd0213cdc043": "そのリンクで許可されている範囲は、このリクエストが求める範囲より狭いです。マシンをもう一度リンクしてください。",
"97e4c50a99272f63": "リクエストに応答できませんでした。もう一度お試しください。",
"605a491783d18b3f": "{via} 経由でこのスレッドを読み取れませんでした",
"50f19209548b70d9": "リンクされたスレッドを読み取るには、{via} の更新が必要な可能性があります。",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index 579b0b6db6b1a..a4dde2f3716d7 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "연결할 수 없음: {failure}",
"acd01e781e2355cc": "요청 종료됨",
"8855350e81d45c45": "해당 연결이 삭제되었거나 만료되었습니다. 머신을 다시 연결하세요.",
+ "c3e4bd0213cdc043": "해당 연결은 이 요청이 요구하는 것보다 적은 권한만 허용합니다. 머신을 다시 연결하세요.",
"97e4c50a99272f63": "요청에 응답할 수 없습니다. 다시 시도하세요.",
"605a491783d18b3f": "{via}을(를) 통해 이 스레드를 읽지 못했습니다",
"50f19209548b70d9": "연결된 스레드를 읽으려면 {via}을(를) 업데이트해야 할 수 있습니다.",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index f64f5305e1516..d93e80f667541 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Não foi possível vincular: {failure}",
"acd01e781e2355cc": "Solicitação encerrada",
"8855350e81d45c45": "Esse vínculo foi removido ou expirou. Vincule a máquina novamente.",
+ "c3e4bd0213cdc043": "Esse vínculo permite menos do que esta solicitação pede. Vincule a máquina novamente.",
"97e4c50a99272f63": "Não foi possível responder à solicitação. Tente novamente.",
"605a491783d18b3f": "Não foi possível ler esta thread por {via}",
"50f19209548b70d9": "Talvez {via} precise de uma atualização para ler threads vinculadas.",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 784feda972092..9b109e5afcc2a 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Не удалось привязать: {failure}",
"acd01e781e2355cc": "Запрос завершён",
"8855350e81d45c45": "Эта привязка удалена или истекла. Привяжите машину снова.",
+ "c3e4bd0213cdc043": "Эта привязка разрешает меньше, чем требует этот запрос. Привяжите машину снова.",
"97e4c50a99272f63": "Не удалось ответить на запрос. Повторите попытку.",
"605a491783d18b3f": "Не удалось прочитать этот тред через {via}",
"50f19209548b70d9": "Возможно, {via} нужно обновить, чтобы читать привязанные треды.",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 06fb0276b89b8..52b57c49e4994 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "Kunde inte länka: {failure}",
"acd01e781e2355cc": "Begäran avslutades",
"8855350e81d45c45": "Länken har tagits bort eller gått ut. Länka maskinen igen.",
+ "c3e4bd0213cdc043": "Länken tillåter mindre än den här begäran kräver. Länka maskinen igen.",
"97e4c50a99272f63": "Kunde inte svara på begäran. Försök igen.",
"605a491783d18b3f": "Det gick inte att läsa den här tråden via {via}",
"50f19209548b70d9": "{via} kan behöva uppdateras innan den kan läsa länkade trådar.",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index 91efdd87db5e4..4e4f4fb802679 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -119,6 +119,7 @@
"21be308917bd450e": "无法关联:{failure}",
"acd01e781e2355cc": "请求已结束",
"8855350e81d45c45": "该关联已被移除或已过期。请重新关联这台机器。",
+ "c3e4bd0213cdc043": "该关联允许的权限低于此请求的要求。请重新关联这台机器。",
"97e4c50a99272f63": "无法回复此请求。请重试。",
"605a491783d18b3f": "无法通过 {via} 读取此会话",
"50f19209548b70d9": "{via} 可能需要更新后才能读取关联的会话。",
diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts
index cea1c945b3233..ed8c2f5fb2292 100644
--- a/packages/client-runtime/src/linkRequest.ts
+++ b/packages/client-runtime/src/linkRequest.ts
@@ -448,16 +448,22 @@ export function linkRequestFailureMessage(
failure: unknown,
resolve: MFunctionType = mFallback,
): string {
- if (
+ const reason =
typeof failure === "object" &&
failure !== null &&
"_tag" in failure &&
failure._tag === "PeerLinkRequestError" &&
- "reason" in failure &&
- failure.reason === "link_gone"
- ) {
+ "reason" in failure
+ ? failure.reason
+ : undefined;
+ if (reason === "link_gone") {
return resolve(msg("That link was removed or expired. Link the machine again."));
}
+ if (reason === "link_too_weak") {
+ return resolve(
+ msg("That link allows less than this request asks for. Link the machine again."),
+ );
+ }
if (
typeof failure === "object" &&
failure !== null &&
diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts
index e2981ba541b48..04f5f5aba07ed 100644
--- a/packages/contracts/src/peerLink.ts
+++ b/packages/contracts/src/peerLink.ts
@@ -262,6 +262,7 @@ const PEER_LINK_REQUEST_FAILURE_MESSAGES = {
not_found: "This link request no longer exists.",
already_answered: "This link request was already answered.",
link_gone: "That link was removed or expired. Link the machine again.",
+ link_too_weak: "That link allows less than this request asks for. Link the machine again.",
record_failed: "Could not update the link request.",
} as const;
From 8e73f5dcd50ef907be3abfdcbfba4841c472ffa7 Mon Sep 17 00:00:00 2001
From: Orin
Date: Sun, 22 Nov 2026 18:20:00 -0800
Subject: [PATCH 8/8] fix(web,mobile): a link's old address is shown for the
user to check, never used silently
A machine known only through the environment's link skipped the address
step, so a pasted pairing code went to the link's old address without the
user seeing it or the warning that anything there can claim to be that
machine. A stale address could not be corrected either.
Answers that name a machine now go only to the client's own addresses. When
it has none, the address field shows again, filled in with where the link
reached the machine, so the user sees it with its warning and can change it.
Co-Authored-By: Claude Opus 5.5
---
.../src/features/threads/LinkRequestCard.tsx | 23 +++++++--------
.../src/components/chat/LinkRequestCard.tsx | 27 ++++++++----------
.../settings/LinkedEnvironmentsSettings.tsx | 28 +++++++++----------
.../client-runtime/src/linkRequest.test.ts | 18 +++++++-----
packages/client-runtime/src/linkRequest.ts | 19 +++++++------
5 files changed, 57 insertions(+), 58 deletions(-)
diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx
index 10020827193e0..f52057a121b5c 100644
--- a/apps/mobile/src/features/threads/LinkRequestCard.tsx
+++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx
@@ -10,8 +10,8 @@ import {
linkRequestInitialMachine,
type LinkRequestItem,
linkRequestKeepsLink,
+ linkRequestSuggestedAddress,
linkRequestTarget,
- linkTargetUrls,
rankMachinesByHint,
} from "@t3tools/client-runtime/link-request";
import {
@@ -209,7 +209,8 @@ function LinkRequestSheet(props: {
const listed = useLinkableMachines(props.environmentId, true);
const machines = useMemo(() => rankMachinesByHint(listed, item.hint), [listed, item.hint]);
const [choice, setChoice] = useState(null);
- const [address, setAddress] = useState(item.url ?? "");
+ // Null until the user types; until then the field holds the suggested address.
+ const [typedAddress, setAddress] = useState(null);
const [access, setAccess] = useState(() => linkRequestDefaultAccess(item));
const [pairingCode, setPairingCode] = useState("");
const [busy, setBusy] = useState(false);
@@ -225,6 +226,7 @@ function LinkRequestSheet(props: {
});
const selected = choice ?? linkRequestInitialMachine(item, machines);
const target = linkRequestTarget(item, machines, selected, m);
+ const address = typedAddress ?? linkRequestSuggestedAddress(item, target);
const targetName =
target.kind === "machine"
? target.label
@@ -235,15 +237,13 @@ function LinkRequestSheet(props: {
const connected = usePreparedConnection(targetId);
const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
const needsAddress =
- target.kind === "address" ||
- (target.kind === "machine" && target.urls.length === 0 && target.linkUrls.length === 0);
+ target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
// This phone mints a code there when it is connected with a session that may
- // create pairing links, and only for its own addresses: anything can answer as
- // that machine at one typed in or only a link reached, so those get a code the user fetched.
+ // create pairing links, and only for its own addresses: anything can answer
+ // as that machine at one typed in, so that one gets a code the user fetched.
const canMint =
targetId !== null &&
- target.kind === "machine" &&
- target.urls.length > 0 &&
+ !needsAddress &&
Option.isSome(connected) &&
mayMint &&
!mintFailed.has(targetId);
@@ -273,10 +273,7 @@ function LinkRequestSheet(props: {
}
return linkRequestAnswerInput(item, {
type: "link",
- target:
- target.kind === "machine" && !needsAddress
- ? { ...target, urls: linkTargetUrls(target, canMint) }
- : { url: address },
+ target: target.kind === "machine" && target.urls.length > 0 ? target : { url: address },
access,
pairingCode: code,
});
@@ -382,7 +379,7 @@ function LinkRequestSheet(props: {
/>
) : null}
- {needsAddress && item.url === undefined ? (
+ {needsAddress && item.url === undefined && !useExisting ? (
(null);
- const [address, setAddress] = useState(item.url ?? "");
+ // Null until the user types; until then the field holds the suggested address.
+ const [typedAddress, setAddress] = useState(null);
const [access, setAccess] = useState(() => linkRequestDefaultAccess(item));
const [pairingCode, setPairingCode] = useState("");
const [step, setStep] = useState("machine");
@@ -209,6 +210,7 @@ function LinkRequestDialog(props: {
});
const selected = choice ?? linkRequestInitialMachine(item, machines);
const target = linkRequestTarget(item, machines, selected, messages);
+ const address = typedAddress ?? linkRequestSuggestedAddress(item, target);
const targetName =
target.kind === "machine" ? target.label : linkRequestTargetName(item, messages);
// Without a catalog entry or an address, the name is the generic "a machine".
@@ -222,21 +224,19 @@ function LinkRequestDialog(props: {
const connected = usePreparedConnection(targetId);
const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
const needsAddress =
- target.kind === "address" ||
- (target.kind === "machine" && target.urls.length === 0 && target.linkUrls.length === 0);
+ target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
// This client mints a code there when it is connected with a session that may
- // create pairing links, and only for its own addresses: anything can answer as
- // that machine at one typed in or only a link reached, so those get a code the user fetched.
+ // create pairing links, and only for its own addresses: anything can answer
+ // as that machine at one typed in, so that one gets a code the user fetched.
const canMint =
targetId !== null &&
- target.kind === "machine" &&
- target.urls.length > 0 &&
+ !needsAddress &&
Option.isSome(connected) &&
mayMint &&
!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 = linkRequestKeepsLink(item, target);
+ // An address the agent gave is already filled in; only one the user must type is asked for.
+ const asksAddress = needsAddress && item.url === undefined && !useExisting;
// A named machine with an address it answers at has nothing to choose before access.
const steps: ReadonlyArray =
pickMachine || asksAddress ? ["machine", "access"] : ["access"];
@@ -247,7 +247,7 @@ function LinkRequestDialog(props: {
const reset = () => {
setChoice(null);
- setAddress(item.url ?? "");
+ setAddress(null);
setAccess(linkRequestDefaultAccess(item));
setPairingCode("");
setStep("machine");
@@ -281,10 +281,7 @@ function LinkRequestDialog(props: {
}
return linkRequestAnswerInput(item, {
type: "link",
- target:
- target.kind === "machine" && !needsAddress
- ? { ...target, urls: linkTargetUrls(target, canMint) }
- : { url: address },
+ target: target.kind === "machine" && target.urls.length > 0 ? target : { url: address },
access,
pairingCode: code,
});
diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
index 199a3b6966f53..e5a46a965adaf 100644
--- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
+++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
@@ -4,11 +4,7 @@ import {
linkBatchFailureLabel,
linkWithMintedCode,
} from "@t3tools/client-runtime/link-batch";
-import {
- ANOTHER_ADDRESS,
- linkRequestFailureMessage,
- linkTargetUrls,
-} from "@t3tools/client-runtime/link-request";
+import { ANOTHER_ADDRESS, linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
import {
AuthAccessWriteScope,
type AuthMcpClientAccess,
@@ -282,7 +278,8 @@ export function LinkEnvironmentDialog({
];
// Null until the user picks; with no other machines known, only an address is left.
const [choice, setChoice] = useState(prefill?.choice ?? null);
- const [address, setAddress] = useState(prefill?.address ?? "");
+ // Null until the user types; until then the field holds the suggested address.
+ const [typedAddress, setAddress] = useState(null);
const [pairingCode, setPairingCode] = useState("");
const [access, setAccess] = useState("approval-required");
const [busy, setBusy] = useState(false);
@@ -308,6 +305,10 @@ export function LinkEnvironmentDialog({
const [throughFailed, setThroughFailed] = useState>(new Set());
const [alsoLinkBack, setAlsoLinkBack] = useState(false);
const selected = choice ?? (machines.length === 0 ? ANOTHER_ADDRESS : null);
+ const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null;
+ // Where the environment's link reached the machine: shown for the user to check, since
+ // anything can answer there as it.
+ const address = typedAddress ?? machine?.linkUrls[0] ?? prefill?.address ?? "";
// Only for the machine the dialog opened for: another choice or address is another machine.
const prefilledThrough =
prefill?.through !== undefined &&
@@ -315,20 +316,17 @@ export function LinkEnvironmentDialog({
address === (prefill.address ?? "")
? prefill.through
: null;
- const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null;
const targetId = machine?.environmentId ?? null;
const connected = usePreparedConnection(targetId);
const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
// A picked machine that left the list has no address here either.
- const needsAddress =
- selected !== null &&
- (machine === null || (machine.urls.length === 0 && machine.linkUrls.length === 0));
+ const needsAddress = selected !== null && (machine === null || machine.urls.length === 0);
// This client mints a code there when it is connected with a session that may
- // create pairing links, and only for its own addresses: anything can answer as
- // that machine at one typed in or only a link reached, so those get a code the user fetched.
+ // create pairing links, and only for its own addresses: anything can answer
+ // as that machine at one typed in, so that one gets a code the user fetched.
const canMint =
targetId !== null &&
- (machine?.urls.length ?? 0) > 0 &&
+ !needsAddress &&
Option.isSome(connected) &&
mayMint &&
!mintFailed.has(targetId);
@@ -351,7 +349,7 @@ export function LinkEnvironmentDialog({
setOpen(next);
if (!next) {
setChoice(prefill?.choice ?? null);
- setAddress(prefill?.address ?? "");
+ setAddress(null);
setPairingCode("");
setAccess("approval-required");
setMintFailed(new Set());
@@ -402,7 +400,7 @@ export function LinkEnvironmentDialog({
};
const submit = async () => {
const [url, ...alternateUrls] =
- machine === null || needsAddress ? [address.trim()] : linkTargetUrls(machine, canMint);
+ machine === null || needsAddress ? [address.trim()] : machine.urls;
if (inFlight.current || !ready || url === undefined) return;
inFlight.current = true;
setBusy(true);
diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts
index d2c3bdc32354a..30492930b87f4 100644
--- a/packages/client-runtime/src/linkRequest.test.ts
+++ b/packages/client-runtime/src/linkRequest.test.ts
@@ -22,9 +22,9 @@ import {
linkRequestFailureMessage,
linkRequestInitialMachine,
linkRequestKeepsLink,
+ linkRequestSuggestedAddress,
linkRequestTarget,
linkRequestTargetName,
- linkTargetUrls,
rankMachinesByHint,
} from "./linkRequest.ts";
@@ -366,12 +366,6 @@ describe("linkableMachines", () => {
},
expect.objectContaining({ label: "Local", linkedAccess: "auto", urls: [], linkUrls: [] }),
]);
- // A code this client mints goes only to its own addresses; one the user fetched, to both.
- expect(linkTargetUrls(listed[0]!, true)).toEqual(["https://vps.ts.net"]);
- expect(linkTargetUrls(listed[0]!, false)).toEqual([
- "https://vps.ts.net",
- "https://vps.example.com",
- ]);
});
it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => {
@@ -567,6 +561,16 @@ describe("linkRequestTarget", () => {
expect(linkRequestTarget({}, [box], box.environmentId)).toMatchObject({ kind: "machine" });
expect(linkRequestTarget({}, [box], ANOTHER_ADDRESS)).toEqual({ kind: "address" });
expect(linkRequestTarget({}, [box], null)).toEqual({ kind: "none" });
+ // Where only the environment's link reached it is no address of its own: the user
+ // starts from it, and sees it, before a code goes there.
+ const linkedOnly = { ...box, urls: [] };
+ const target = linkRequestTarget({ environmentId: box.environmentId }, [linkedOnly], null);
+ expect(target).toMatchObject({ kind: "machine", urls: [] });
+ expect(linkRequestSuggestedAddress({}, target)).toBe("https://box.peer.example");
+ expect(linkRequestSuggestedAddress({ url: "https://other.example" }, { kind: "address" })).toBe(
+ "https://other.example",
+ );
+ expect(linkRequestSuggestedAddress({}, { kind: "none" })).toBe("");
});
it("keeps a link the machine has unless the agent asked for more access than it allows", () => {
diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts
index ed8c2f5fb2292..dcdbe270abdb4 100644
--- a/packages/client-runtime/src/linkRequest.ts
+++ b/packages/client-runtime/src/linkRequest.ts
@@ -96,17 +96,11 @@ export interface LinkableMachine {
readonly urls: ReadonlyArray;
/**
* Where only the thread's environment's link reached it. Anything can answer
- * there as this machine, so a code this client mints never goes to them.
+ * there as this machine, so these only suggest an address the user checks.
*/
readonly linkUrls: ReadonlyArray;
}
-/** Where a link sends its pairing code: one this client minted goes only to its own addresses. */
-export const linkTargetUrls = (
- machine: Pick,
- minted: boolean,
-): ReadonlyArray => (minted ? machine.urls : [...machine.urls, ...machine.linkUrls]);
-
/** A loopback address names whichever machine opens it: the linking server, not this one. */
const isLoopbackUrl = (url: string) => {
const hostname = parsedUrl(url)?.hostname;
@@ -258,7 +252,7 @@ export const ANOTHER_ADDRESS = "another-address";
/**
* What a link request links: a machine from the client's catalog, or an address.
- * With neither `urls` nor `linkUrls`, nothing knows an address for the machine,
+ * `urls` is empty when the client knows no direct address for the machine,
* so the user types one.
*/
export type LinkRequestTarget =
@@ -309,6 +303,15 @@ export function linkRequestTarget(
};
}
+/**
+ * Where a card's address field starts: the agent's address, else where the environment's
+ * link reached the machine. The user sees it, with its warning, before a code goes there.
+ */
+export const linkRequestSuggestedAddress = (
+ item: Pick,
+ target: LinkRequestTarget,
+): string => item.url ?? (target.kind === "machine" ? target.linkUrls[0] : undefined) ?? "";
+
/**
* 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