--access `.
+To link many machines at once, choose **Link several…** (it appears once this
+app has two other machines saved). Tick the machines, pick one access level for
+all of them, and confirm once. A machine can be ticked when this app is
+connected to it with a session that manages access there and has an address
+another machine can reach; the list says why when it cannot. Each machine
+reports its own result, and the ones that failed stay ticked so you can try
+only those again. Machines already linked are left as they are.
+
+For machines no app is connected to, put one ` ` per
+line in a file (make each code with `t3 pair` on that machine) and run
+`t3 environment link --from --access `, or `--from -` to read
+standard input. It prints a result per line, leaves machines already linked as
+they are, and exits non-zero if any line failed, so the same file can be run
+again with fresh codes for the failures.
+
You can also ask an agent to link a machine by name, such as "delegate this to
my vps". It shows a card in the thread where you pick the machine the same way
and the access, then approve. An address the agent gives that this app does
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 003abc03ac65f..182c28a319120 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -103,6 +103,10 @@
"types": "./src/secretRequest.ts",
"default": "./src/secretRequest.ts"
},
+ "./link-batch": {
+ "types": "./src/linkBatch.ts",
+ "default": "./src/linkBatch.ts"
+ },
"./link-request": {
"types": "./src/linkRequest.ts",
"default": "./src/linkRequest.ts"
diff --git a/packages/client-runtime/src/linkBatch.test.ts b/packages/client-runtime/src/linkBatch.test.ts
new file mode 100644
index 0000000000000..4854eecbce233
--- /dev/null
+++ b/packages/client-runtime/src/linkBatch.test.ts
@@ -0,0 +1,182 @@
+import { EnvironmentId, PeerLinkError } from "@t3tools/contracts";
+import * as Result from "effect/Result";
+import { describe, expect, it } from "vite-plus/test";
+
+import { linkBatchCandidates, linkBatchSummary, linkListState, runLinkBatch } from "./linkBatch.ts";
+import type { LinkableMachine } from "./linkRequest.ts";
+
+const machine = (name: string, overrides: Partial = {}): LinkableMachine => ({
+ environmentId: EnvironmentId.make(`environment-${name}`),
+ label: name,
+ machine: "server",
+ connected: true,
+ connectOnly: false,
+ linked: false,
+ urls: [`https://${name}.example.ts.net`, `http://100.64.0.1:3773`],
+ ...overrides,
+});
+const id = (name: string) => EnvironmentId.make(`environment-${name}`);
+
+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("offline", { connected: false }),
+ machine("connect", { connected: false, connectOnly: true }),
+ machine("viewer"),
+ machine("loopback", { urls: [] }),
+ ];
+ const writable = new Set([id("ready"), id("linked"), id("offline"), id("loopback")]);
+ expect(
+ linkBatchCandidates(machines, writable, "loaded").map(({ machine, blocked }) => [
+ machine.label,
+ blocked,
+ ]),
+ ).toEqual([
+ ["ready", null],
+ ["linked", "linked"],
+ ["offline", "not_connected"],
+ ["connect", "not_connected"],
+ ["viewer", "no_access"],
+ ["loopback", "no_address"],
+ ]);
+ });
+
+ it("offers no machine until the linking environment's links have loaded", () => {
+ // With no list, a linked machine reads as unlinked.
+ const machines = [machine("ready"), machine("linked-but-unlisted")];
+ const writable = new Set(machines.map((entry) => entry.environmentId));
+ const blockedWhen = (query: Parameters[0]) =>
+ linkBatchCandidates(machines, writable, linkListState(query)).map(({ blocked }) => blocked);
+ expect(linkListState({ data: null, error: null })).toBe("loading");
+ expect(linkListState({ data: null, error: "The environment request failed." })).toBe("failed");
+ expect(blockedWhen({ data: null, error: null })).toEqual(["links_unknown", "links_unknown"]);
+ expect(blockedWhen({ data: null, error: "failed" })).toEqual([
+ "links_unknown",
+ "links_unknown",
+ ]);
+ expect(blockedWhen({ data: { links: [] }, error: null })).toEqual([null, null]);
+ });
+});
+
+describe("runLinkBatch", () => {
+ it("links each machine with its own code, reports each failure, and retries only those", async () => {
+ const machines = ["a", "b", "c", "d", "e"].map((name) => machine(name));
+ const linked: Array = [];
+ const failures: Record = {
+ b: new PeerLinkError({
+ reason: "pairing_rejected",
+ message: "The peer refused the sign-in.",
+ }),
+ c: new PeerLinkError({ reason: "unreachable", message: "c did not answer." }),
+ d: new PeerLinkError({
+ reason: "unreachable",
+ message: "d answered as another environment, Impostor.",
+ answeredAs: "Impostor",
+ }),
+ };
+ const seen: Array = [];
+ const outcomes = await runLinkBatch({
+ machines,
+ access: "auto",
+ mint: async (environmentId) =>
+ environmentId === id("e")
+ ? Result.fail(new Error("no session"))
+ : Result.succeed(`code-for-${environmentId}`),
+ link: async (input) => {
+ linked.push(input);
+ const failure = failures[input.expectedLabel ?? ""];
+ return failure === undefined ? Result.succeed(null) : Result.fail(failure);
+ },
+ refreshLinks: () => {},
+ onOutcome: (environmentId) => seen.push(environmentId),
+ });
+
+ expect(linked[0]).toEqual({
+ url: "https://a.example.ts.net",
+ alternateUrls: ["http://100.64.0.1:3773"],
+ expectedEnvironmentId: id("a"),
+ expectedLabel: "a",
+ pairingCode: `code-for-${id("a")}`,
+ access: "auto",
+ });
+ // A machine with no code is never linked.
+ expect(linked.length).toBe(4);
+ expect(Object.fromEntries(outcomes)).toEqual({
+ [id("a")]: { kind: "linked" },
+ [id("b")]: {
+ kind: "failed",
+ failure: "code_refused",
+ detail: "The peer refused the sign-in.",
+ },
+ [id("c")]: { kind: "failed", failure: "unreachable", detail: "c did not answer." },
+ [id("d")]: {
+ kind: "failed",
+ failure: "wrong_environment",
+ detail: "d answered as another environment, Impostor.",
+ },
+ [id("e")]: { kind: "failed", failure: "no_code", detail: null },
+ });
+ expect(seen.toSorted()).toEqual(machines.map((entry) => entry.environmentId));
+ expect(linkBatchSummary(outcomes)).toEqual({
+ linked: 1,
+ failed: [id("b"), id("c"), id("d"), id("e")],
+ });
+ });
+
+ it("never shows a failure that may carry the request and its pairing code", async () => {
+ const outcomes = await runLinkBatch({
+ machines: [machine("a")],
+ access: "auto",
+ mint: async () => Result.succeed("secret-code"),
+ link: async (input) => Result.fail(new Error(`request failed: ${JSON.stringify(input)}`)),
+ refreshLinks: () => {},
+ });
+ expect(outcomes.get(id("a"))).toEqual({ kind: "failed", failure: "other", detail: null });
+ });
+
+ it("opens at most four pairings at once", async () => {
+ let open = 0;
+ let most = 0;
+ await runLinkBatch({
+ machines: Array.from({ length: 10 }, (_, index) => machine(`vm-${index}`)),
+ access: "auto",
+ mint: async () => {
+ open += 1;
+ most = Math.max(most, open);
+ return Result.succeed("code");
+ },
+ link: async () => {
+ await Promise.resolve();
+ open -= 1;
+ return Result.succeed(null);
+ },
+ refreshLinks: () => {},
+ });
+ expect(most).toBe(4);
+ });
+
+ it("refreshes the links list once for the whole batch, after its last link", async () => {
+ const events: Array = [];
+ const run = (names: ReadonlyArray, fails: boolean) =>
+ runLinkBatch({
+ machines: names.map((name) => machine(name)),
+ access: "auto",
+ mint: async () => Result.succeed("code"),
+ link: async () => {
+ await Promise.resolve();
+ events.push("link");
+ return fails ? Result.fail(new Error("refused")) : Result.succeed(null);
+ },
+ refreshLinks: () => events.push("refresh"),
+ });
+ const names = Array.from({ length: 12 }, (_, index) => `vm-${index}`);
+ await run(names, false);
+ expect(events).toEqual([...names.map(() => "link"), "refresh"]);
+ // A retry batch is one more refresh; a batch that linked nothing changed no list.
+ await run(names.slice(0, 3), false);
+ await run(names.slice(0, 3), true);
+ expect(events.filter((event) => event === "refresh").length).toBe(2);
+ });
+});
diff --git a/packages/client-runtime/src/linkBatch.ts b/packages/client-runtime/src/linkBatch.ts
new file mode 100644
index 0000000000000..f7f97fabe71c6
--- /dev/null
+++ b/packages/client-runtime/src/linkBatch.ts
@@ -0,0 +1,188 @@
+import {
+ type AuthMcpClientAccess,
+ type EnvironmentId,
+ type PeerLinkCreateInput,
+ type PeerLinkFailureKind,
+ peerLinkFailureKind,
+} from "@t3tools/contracts";
+import * as Result from "effect/Result";
+import { mFallback, msg } from "gt-i18n";
+import type { MFunctionType } from "gt-i18n/types";
+
+import type { LinkableMachine } from "./linkRequest.ts";
+
+/** Pairings a batch opens at once, so a fleet is not signed in to all at the same moment. */
+const LINK_BATCH_CONCURRENCY = 4;
+
+/**
+ * Why a batch cannot link a machine: the client mints each pairing code there
+ * with its own session, and sends it only to addresses it already has for it.
+ */
+export type LinkBatchBlock =
+ | "links_unknown"
+ | "linked"
+ | "not_connected"
+ | "no_access"
+ | "no_address";
+
+/** Whether the linking environment's own links are known yet. */
+export type LinkListState = "loading" | "failed" | "loaded";
+
+export const linkListState = (query: {
+ readonly data: unknown;
+ readonly error: unknown;
+}): LinkListState => (query.data !== null ? "loaded" : query.error !== null ? "failed" : "loading");
+
+export interface LinkBatchCandidate {
+ readonly machine: LinkableMachine;
+ readonly blocked: LinkBatchBlock | null;
+}
+
+/**
+ * `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
+ * already linked would replace its working token, so none is offered.
+ */
+export const linkBatchCandidates = (
+ machines: ReadonlyArray,
+ writable: ReadonlySet,
+ links: LinkListState,
+): ReadonlyArray =>
+ machines.map((machine) => ({
+ machine,
+ blocked:
+ links !== "loaded"
+ ? "links_unknown"
+ : machine.linked
+ ? "linked"
+ : !machine.connected
+ ? "not_connected"
+ : !writable.has(machine.environmentId)
+ ? "no_access"
+ : machine.urls.length === 0
+ ? "no_address"
+ : null,
+ }));
+
+export const linkBatchBlockLabel = (
+ blocked: LinkBatchBlock,
+ resolve: MFunctionType = mFallback,
+): string => {
+ switch (blocked) {
+ case "links_unknown":
+ return resolve(msg("Not known yet whether it is linked"));
+ case "linked":
+ return resolve(msg("Already linked"));
+ case "not_connected":
+ return resolve(msg("This app is not connected to it"));
+ case "no_access":
+ return resolve(msg("Your session there cannot create pairing codes"));
+ case "no_address":
+ return resolve(msg("No address another machine can reach"));
+ }
+};
+
+export type LinkBatchFailure = PeerLinkFailureKind | "no_code";
+
+export type LinkBatchOutcome =
+ | { readonly kind: "linked" }
+ | { readonly kind: "failed"; readonly failure: LinkBatchFailure; readonly detail: string | null };
+
+export const linkBatchFailureLabel = (
+ failure: LinkBatchFailure,
+ resolve: MFunctionType = mFallback,
+): string => {
+ switch (failure) {
+ case "unreachable":
+ return resolve(msg("Unreachable"));
+ case "code_refused":
+ return resolve(msg("Pairing code refused"));
+ case "wrong_environment":
+ return resolve(msg("Another environment answered"));
+ case "no_code":
+ return resolve(msg("Could not get a pairing code there"));
+ case "other":
+ return resolve(msg("Could not link"));
+ }
+};
+
+/**
+ * Only the linking environment's own error passes its message through:
+ * anything else may carry the request, and with it the pairing code.
+ */
+const linkFailure = (failure: unknown): LinkBatchOutcome => {
+ if (
+ typeof failure === "object" &&
+ failure !== null &&
+ "_tag" in failure &&
+ failure._tag === "PeerLinkError" &&
+ "reason" in failure &&
+ "message" in failure &&
+ typeof failure.message === "string"
+ ) {
+ const error = failure as unknown as Parameters[0];
+ return { kind: "failed", failure: peerLinkFailureKind(error), detail: failure.message };
+ }
+ return { kind: "failed", failure: "other", detail: null };
+};
+
+type BatchMachine = Pick;
+
+/**
+ * Links each machine as a single link is made: a one-use code minted on that
+ * machine with the client's session there, then handed to the linking
+ * environment with the addresses the client has for it. A failure stops only
+ * its own machine. Codes stay in this call and are never reported.
+ */
+export async function runLinkBatch(input: {
+ readonly machines: ReadonlyArray;
+ readonly access: AuthMcpClientAccess;
+ readonly mint: (
+ environmentId: EnvironmentId,
+ access: AuthMcpClientAccess,
+ ) => Promise>;
+ readonly link: (input: PeerLinkCreateInput) => Promise>;
+ /** Called once, at the end: listing probes every linked machine, so `link` must not refresh. */
+ readonly refreshLinks: () => void;
+ readonly onOutcome?: (environmentId: EnvironmentId, outcome: LinkBatchOutcome) => void;
+}): Promise> {
+ const outcomes = new Map();
+ const linkOne = async (machine: BatchMachine): Promise => {
+ const [url, ...alternateUrls] = machine.urls;
+ if (url === undefined) return { kind: "failed", failure: "unreachable", detail: null };
+ const minted = await input.mint(machine.environmentId, input.access);
+ if (Result.isFailure(minted)) return { kind: "failed", failure: "no_code", detail: null };
+ const linked = await input.link({
+ url,
+ ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
+ expectedEnvironmentId: machine.environmentId,
+ expectedLabel: machine.label,
+ pairingCode: minted.success,
+ access: input.access,
+ });
+ return Result.isSuccess(linked) ? { kind: "linked" } : linkFailure(linked.failure);
+ };
+ const queue = [...input.machines];
+ const worker = async () => {
+ for (let machine = queue.shift(); machine !== undefined; machine = queue.shift()) {
+ const outcome = await linkOne(machine).catch((): LinkBatchOutcome => ({
+ kind: "failed",
+ failure: "other",
+ detail: null,
+ }));
+ outcomes.set(machine.environmentId, outcome);
+ input.onOutcome?.(machine.environmentId, outcome);
+ }
+ };
+ await Promise.all(Array.from({ length: LINK_BATCH_CONCURRENCY }, worker));
+ if ([...outcomes.values()].some((outcome) => outcome.kind === "linked")) input.refreshLinks();
+ return outcomes;
+}
+
+/** How a batch went, and the machines a retry would run again. */
+export const linkBatchSummary = (outcomes: ReadonlyMap) => {
+ const failed = [...outcomes].flatMap(([environmentId, outcome]) =>
+ outcome.kind === "failed" ? [environmentId] : [],
+ );
+ return { linked: outcomes.size - failed.length, failed };
+};
diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts
index 9295bf1b40156..9b355e29085ed 100644
--- a/packages/client-runtime/src/state/peerLinks.ts
+++ b/packages/client-runtime/src/state/peerLinks.ts
@@ -24,6 +24,11 @@ export function createPeerLinkEnvironmentAtoms(
onSuccess: ({ environmentId }, registry) =>
Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))),
}),
+ // Leaves the list alone: a batch refreshes it once, when it ends (`runLinkBatch`).
+ linkInBatch: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:peer-links:link-in-batch",
+ tag: WS_METHODS.peerLinksLink,
+ }),
unlink: createEnvironmentRpcCommand(runtime, {
label: "environment-data:peer-links:unlink",
tag: WS_METHODS.peerLinksUnlink,
diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts
index f8cf83c1fdbdd..0d72b978e2609 100644
--- a/packages/contracts/src/peerLink.ts
+++ b/packages/contracts/src/peerLink.ts
@@ -70,9 +70,25 @@ export class PeerLinkError extends Schema.TaggedError()("PeerLink
"disabled",
]),
message: Schema.String,
+ /** The environment that answered at the addresses of the one the user picked, when one did. */
+ answeredAs: Schema.optionalKey(Schema.String),
cause: Schema.optionalKey(Schema.Defect()),
}) {}
+/** What went wrong with one link, as a batch reports it per machine. */
+export type PeerLinkFailureKind = "unreachable" | "code_refused" | "wrong_environment" | "other";
+
+export const peerLinkFailureKind = (
+ error: Pick,
+): PeerLinkFailureKind =>
+ error.answeredAs !== undefined
+ ? "wrong_environment"
+ : error.reason === "unreachable" || error.reason === "not_a_t3_environment"
+ ? "unreachable"
+ : error.reason === "pairing_rejected"
+ ? "code_refused"
+ : "other";
+
/**
* The user's answer to an agent asking to link an environment. The pairing
* code is used once to link and is never recorded; the thread learns only the