\" />);\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/linkBatch.test.ts b/packages/client-runtime/src/linkBatch.test.ts
index 605d1b968060d..10140127bbca6 100644
--- a/packages/client-runtime/src/linkBatch.test.ts
+++ b/packages/client-runtime/src/linkBatch.test.ts
@@ -17,7 +17,7 @@ const machine = (name: string, overrides: Partial = {}): Linkab
machine: "server",
connected: true,
connectOnly: false,
- linked: false,
+ linkedAccess: null,
urls: [`https://${name}.example.ts.net`, `http://100.64.0.1:3773`],
...overrides,
});
@@ -27,7 +27,7 @@ describe("linkBatchCandidates", () => {
it("offers only machines the client can mint a code on and has an address for", () => {
const machines = [
machine("ready"),
- machine("linked", { linked: true, connected: false }),
+ machine("linked", { linkedAccess: "read-only", connected: false }),
machine("offline", { connected: false }),
machine("connect", { connected: false, connectOnly: true }),
machine("viewer"),
diff --git a/packages/client-runtime/src/linkBatch.ts b/packages/client-runtime/src/linkBatch.ts
index acc4980c56c77..f15619d4ee42d 100644
--- a/packages/client-runtime/src/linkBatch.ts
+++ b/packages/client-runtime/src/linkBatch.ts
@@ -41,7 +41,7 @@ export interface LinkBatchCandidate {
/**
* `writable` holds the machines where this client's session may create pairing codes.
- * Until `links` has loaded, no machine's `linked` is known, and linking one that is
+ * Until `links` has loaded, no machine's `linkedAccess` is known, and linking one that is
* already linked would replace its working token, so none is offered.
*/
export const linkBatchCandidates = (
@@ -54,7 +54,7 @@ export const linkBatchCandidates = (
blocked:
links !== "loaded"
? "links_unknown"
- : machine.linked
+ : machine.linkedAccess !== null
? "linked"
: !machine.connected
? "not_connected"
diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts
index 70d33176a6873..f6e9566495de6 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";
@@ -15,6 +21,7 @@ import {
linkRequestDisplay,
linkRequestFailureMessage,
linkRequestInitialMachine,
+ linkRequestKeepsLink,
linkRequestTarget,
linkRequestTargetName,
rankMachinesByHint,
@@ -79,7 +86,12 @@ describe("linkRequestAnswerInput", () => {
access: "auto",
pairingCode: "abc",
}),
- ).toMatchObject({ answer: { 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" },
+ });
});
it("refuses a blank code, a blank address, or a machine with no address", () => {
@@ -188,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"] });
@@ -201,7 +224,7 @@ describe("linkableMachines", () => {
linkableMachines({
environments: [here, vps, mini],
threadEnvironmentId: here.environmentId,
- links: [{ environmentId: mini.environmentId, status: "unreachable" }],
+ links: [link(mini.environmentId, { status: "unreachable", access: "read-only" })],
connect: new Map(),
}),
).toEqual([
@@ -211,7 +234,7 @@ describe("linkableMachines", () => {
machine: "laptop",
connected: true,
connectOnly: false,
- linked: false,
+ linkedAccess: null,
urls: ["https://vps.ts.net", "https://vps.example.com"],
},
{
@@ -220,7 +243,7 @@ describe("linkableMachines", () => {
machine: "server",
connected: false,
connectOnly: false,
- linked: true,
+ linkedAccess: "read-only",
urls: [],
},
]);
@@ -274,16 +297,67 @@ describe("linkableMachines", () => {
environments: [here, vps, mini],
threadEnvironmentId: here.environmentId,
links: [
- { environmentId: vps.environmentId, status: "expired" },
- { environmentId: mini.environmentId, status: "unreachable" },
- { environmentId: EnvironmentId.make("environment-old"), status: "expired" },
+ 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")]]),
});
- expect(listed.map((machine) => [machine.label, machine.linked])).toEqual([
- ["VPS", false],
- ["Mini", true],
- ["Old box", false],
+ expect(listed.map((machine) => [machine.label, machine.linkedAccess])).toEqual([
+ ["VPS", null],
+ ["Mini", "auto"],
+ ["Old box", null],
+ ]);
+ });
+
+ 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", { 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.
+ 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: [] }),
]);
});
@@ -293,7 +367,7 @@ describe("linkableMachines", () => {
const listed = linkableMachines({
environments: [here, vps],
threadEnvironmentId: here.environmentId,
- links: [{ environmentId: EnvironmentId.make("environment-old"), status: "reachable" }],
+ links: [link("environment-old")],
connect: new Map([
// This environment and saved machines are listed once, as saved.
[here.environmentId, discovered(here.environmentId, "Here")],
@@ -313,10 +387,10 @@ describe("linkableMachines", () => {
machine: "mac-mini",
connected: false,
connectOnly: true,
- linked: false,
+ linkedAccess: null,
urls: ["https://environment-mini.t3.example"],
});
- expect(listed[2]).toMatchObject({ machine: "server", linked: true });
+ expect(listed[2]).toMatchObject({ machine: "server", linkedAccess: "auto" });
// A Connect record that publishes only a loopback address gives the machine none.
const local = discovered("environment-local", "Local");
@@ -392,7 +466,7 @@ describe("rankMachinesByHint", () => {
machine: "server",
connected: true,
connectOnly: false,
- linked: false,
+ linkedAccess: null,
urls: [],
}) as const,
);
@@ -421,7 +495,7 @@ describe("linkRequestTarget", () => {
machine: "server",
connected: true,
connectOnly: false,
- linked: false,
+ linkedAccess: null,
urls: ["http://10.0.0.2:3773", "https://box.t3connect.example/"],
} as const;
@@ -447,7 +521,7 @@ describe("linkRequestTarget", () => {
environmentId: box.environmentId,
label: "Box",
urls: box.urls,
- linked: false,
+ linkedAccess: null,
});
expect(linkRequestTarget({ url: "http://box.t3connect.example" }, [box], null)).toEqual({
kind: "address",
@@ -473,13 +547,42 @@ describe("linkRequestTarget", () => {
expect(linkRequestTarget({}, [box], ANOTHER_ADDRESS)).toEqual({ kind: "address" });
expect(linkRequestTarget({}, [box], null)).toEqual({ kind: "none" });
});
+
+ 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);
+ // 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);
+ // No link to keep.
+ expect(
+ linkRequestKeepsLink(
+ {},
+ linkRequestTarget({ environmentId: box.environmentId }, [box], null),
+ ),
+ ).toBe(false);
+ expect(linkRequestKeepsLink({}, { kind: "address" })).toBe(false);
+ });
});
describe("linkRequestFailureMessage", () => {
- it("passes through only known user-facing errors", () => {
+ it("names every answer failure in the client's words, and nothing it does not know", () => {
+ const named = (reason: string) =>
+ linkRequestFailureMessage({ _tag: "PeerLinkRequestError", reason, message: "server copy" });
+ expect(named("not_found")).toBe("This link request no longer exists.");
+ expect(named("already_answered")).toBe("This link request was already answered.");
+ expect(named("load_failed")).toBe("Could not load the link request.");
+ expect(named("record_failed")).toBe("Could not update the link request.");
+ expect(named("link_gone")).toBe("That link was removed or expired. Link the machine again.");
+ // A reason from a newer server, or none at all, never shows the server's English.
+ expect(named("unknown")).toBe("Could not answer the request. Try again.");
+ expect(named("link_frozen")).toBe("Could not answer the request. Try again.");
expect(
- linkRequestFailureMessage({ _tag: "PeerLinkRequestError", message: "Already answered." }),
- ).toBe("Already answered.");
+ linkRequestFailureMessage({ _tag: "EnvironmentAuthorizationError", message: "No scope." }),
+ ).toBe("No scope.");
expect(linkRequestFailureMessage({ _tag: "SchemaError", message: "code=abc" })).toBe(
"Could not answer the request. Try again.",
);
diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts
index 6da1c29d1b189..94c15be4185e4 100644
--- a/packages/client-runtime/src/linkRequest.ts
+++ b/packages/client-runtime/src/linkRequest.ts
@@ -3,9 +3,11 @@ import {
type AuthMcpClientAccess,
type EnvironmentId,
type EnvironmentMachineKind,
+ mcpClientAccessCovers,
type OrchestrationV2TurnItem,
type PeerLinkRequestAnswerInput,
type PeerLinkName,
+ type PeerLinkRequestFailureReason,
type PeerLinkSummary,
resolveEnvironmentMachineKind,
type ServerConfig,
@@ -84,13 +86,13 @@ export interface LinkableMachine {
readonly connected: boolean;
/** Found on the user's T3 Connect account rather than saved in this client. */
readonly connectOnly: boolean;
- /** Whether the thread's environment already has a link to it. */
- readonly linked: boolean;
+ /** 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;
}
@@ -102,10 +104,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<
@@ -113,12 +115,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 linkedIds = new Set(
- input.links.flatMap((link) => (link.status === "expired" ? [] : [link.environmentId])),
- );
+ 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) => {
@@ -136,23 +145,19 @@ export function linkableMachines(input: {
machine: resolveEnvironmentMachineKind(environment.serverConfig),
connected: environment.connection.phase === "connected",
connectOnly: false,
- linked: linkedIds.has(environment.environmentId),
- 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 {
@@ -163,11 +168,23 @@ export function linkableMachines(input: {
),
connected: false,
connectOnly: true,
- linked: linkedIds.has(environment.environmentId),
- 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) =>
@@ -236,7 +253,7 @@ export type LinkRequestTarget =
readonly environmentId: EnvironmentId;
readonly label: string;
readonly urls: ReadonlyArray;
- readonly linked: boolean;
+ readonly linkedAccess: AuthMcpClientAccess | null;
}
| { readonly kind: "address" };
@@ -271,10 +288,24 @@ export function linkRequestTarget(
environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
label: machine?.label ?? linkRequestTargetName(item, resolve),
urls: machine?.urls ?? [],
- linked: machine?.linked ?? false,
+ linkedAccess: machine?.linkedAccess ?? null,
};
}
+/**
+ * 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,
+ target: LinkRequestTarget,
+): boolean =>
+ target.kind === "machine" &&
+ target.linkedAccess !== null &&
+ (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 =
| { readonly kind: "pending" }
@@ -346,7 +377,10 @@ export function linkRequestAnswerInput(
answer:
| {
readonly type: "link";
- /** The machine picked, or an address typed in its place. */
+ /**
+ * 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 };
@@ -382,11 +416,19 @@ export function linkRequestAnswerInput(
}
/** Failures whose message is written for the user and never echoes the request payload. */
-const USER_FACING_FAILURE_TAGS = new Set([
- "PeerLinkRequestError",
- "EnvironmentAuthorizationError",
- "PeerPairingCodeError",
-]);
+const USER_FACING_FAILURE_TAGS = new Set(["EnvironmentAuthorizationError", "PeerPairingCodeError"]);
+
+const GENERIC_FAILURE = msg("Could not answer the request. Try again.");
+
+/** The contract's English reasons, in the client's languages. */
+const LINK_REQUEST_FAILURE_MESSAGES: Record = {
+ load_failed: msg("Could not load the link request."),
+ not_found: msg("This link request no longer exists."),
+ already_answered: msg("This link request was already answered."),
+ link_gone: msg("That link was removed or expired. Link the machine again."),
+ record_failed: msg("Could not update the link request."),
+ unknown: GENERIC_FAILURE,
+};
/**
* Inline error copy for a failed answer. Only known errors pass their message
@@ -397,6 +439,19 @@ export function linkRequestFailureMessage(
failure: unknown,
resolve: MFunctionType = mFallback,
): string {
+ if (
+ typeof failure === "object" &&
+ failure !== null &&
+ "_tag" in failure &&
+ failure._tag === "PeerLinkRequestError"
+ ) {
+ const reason = "reason" in failure ? failure.reason : undefined;
+ return resolve(
+ typeof reason === "string" && reason in LINK_REQUEST_FAILURE_MESSAGES
+ ? LINK_REQUEST_FAILURE_MESSAGES[reason as PeerLinkRequestFailureReason]
+ : GENERIC_FAILURE,
+ );
+ }
if (
typeof failure === "object" &&
failure !== null &&
@@ -409,5 +464,5 @@ export function linkRequestFailureMessage(
) {
return errorDisplayMessage(failure, resolve) ?? failure.message;
}
- return resolve(msg("Could not answer the request. Try again."));
+ return resolve(GENERIC_FAILURE);
}
diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts
index 0f76e9cfb3dea..941511bd088dc 100644
--- a/packages/client-runtime/src/state/peerLinks.ts
+++ b/packages/client-runtime/src/state/peerLinks.ts
@@ -133,7 +133,8 @@ export function createPeerLinkEnvironmentAtoms(
key: ({ environmentId, input }) =>
JSON.stringify([environmentId, input.threadId, input.turnItemId]),
},
- onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
+ // Also after a failure: an agent may have unlinked the machine the card still showed.
+ onSettled: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
}),
};
}
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index 826ffeb6b258e..93aae9090724f 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -276,6 +276,13 @@ export const AuthMcpClientAccess = Schema.Literals([
]);
export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
+/** Whether `granted` allows everything `wanted` does; the levels are listed weakest first. */
+export const mcpClientAccessCovers = (
+ granted: AuthMcpClientAccess,
+ wanted: AuthMcpClientAccess,
+): boolean =>
+ AuthMcpClientAccess.literals.indexOf(granted) >= AuthMcpClientAccess.literals.indexOf(wanted);
+
/** The scopes an agent session gets for an access level, and a pairing code must carry. */
export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray =>
access === "read-only"
diff --git a/packages/contracts/src/peerLink.test.ts b/packages/contracts/src/peerLink.test.ts
new file mode 100644
index 0000000000000..8fe020a8095e5
--- /dev/null
+++ b/packages/contracts/src/peerLink.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "@effect/vitest";
+import * as Schema from "effect/Schema";
+
+import { PeerLinkRequestError } from "./peerLink.ts";
+
+const decodeError = Schema.decodeUnknownSync(PeerLinkRequestError);
+const encodeError = Schema.encodeSync(PeerLinkRequestError);
+
+describe("PeerLinkRequestError", () => {
+ it("decodes a reason from a newer server as unknown, and known reasons as themselves", () => {
+ const known = decodeError({ _tag: "PeerLinkRequestError", reason: "link_gone" });
+ expect(known.reason).toBe("link_gone");
+ expect(known.message).toBe("That link was removed or expired. Link the machine again.");
+ expect(encodeError(known)).toMatchObject({ reason: "link_gone" });
+
+ const newer = decodeError({ _tag: "PeerLinkRequestError", reason: "link_frozen" });
+ expect(newer.reason).toBe("unknown");
+ expect(newer.message).toBe("Could not answer the request. Try again.");
+ });
+});
diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts
index 3b367c04eaecb..5d662157bca3d 100644
--- a/packages/contracts/src/peerLink.ts
+++ b/packages/contracts/src/peerLink.ts
@@ -1,3 +1,4 @@
+import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { AuthEnvironmentScope, AuthMcpClientAccess } from "./auth.ts";
@@ -241,14 +242,17 @@ const PEER_LINK_REQUEST_FAILURE_MESSAGES = {
load_failed: "Could not load the link request.",
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.",
record_failed: "Could not update the link request.",
+ unknown: "Could not answer the request. Try again.",
} as const;
+/** A reason this version does not know, from a newer server, decodes as `unknown`. */
export const PeerLinkRequestFailureReason = Schema.Literals(
Object.keys(PEER_LINK_REQUEST_FAILURE_MESSAGES) as Array<
keyof typeof PEER_LINK_REQUEST_FAILURE_MESSAGES
>,
-);
+).pipe(Schema.catchDecoding(() => Effect.succeedSome("unknown" as const)));
export type PeerLinkRequestFailureReason = typeof PeerLinkRequestFailureReason.Type;
/**