From 2036897ef857cd2e2c02a5ee318c372df43ae8a9 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:31:28 +0000 Subject: [PATCH 1/3] feat: the app and its server see the same environments The app connected to its own saved environments while agents used the server's peer links, so each saw machines the other did not. The local server now keeps one list: its links plus the connections its clients report (addresses and versions, never credentials). Settings and t3_environment_links both read it, and each entry says why it is on one side only and offers the fix. - Adding a connection can also link it for agents, approved in the Add environment dialog and done with the client's own session. - A linked machine can be added to the app in one click: the peer mints a one-time code capped at the link's access (read-only unless the link is full access and not narrowed), revocable there. - Removing a connection offers to forget its link, and the reverse. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/mcp/McpInvocationContext.ts | 21 ++ .../src/mcp/toolkits/orchestrator/handlers.ts | 56 ++++- .../src/mcp/toolkits/orchestrator/tools.ts | 15 ++ .../src/observability/RpcInstrumentation.ts | 3 + apps/server/src/peer/LinkAppPairing.test.ts | 78 +++++++ apps/server/src/peer/PeerForwarding.ts | 104 ++++++++- apps/server/src/peer/PeerLinks.ts | 53 ++++- apps/server/src/peer/PeerMcpClient.test.ts | 2 + .../server/src/peer/knownEnvironments.test.ts | 143 ++++++++++++ apps/server/src/peer/knownEnvironments.ts | 114 ++++++++++ .../src/provider/agentContextBudget.json | 2 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 10 + .../settings/AddEnvironmentDialog.tsx | 44 ++++ .../settings/ConnectionsSettings.tsx | 28 ++- ...inkedEnvironmentsSettings.browser.test.tsx | 35 ++- .../settings/LinkedEnvironmentsSettings.tsx | 203 +++++++++++++++--- apps/web/src/routes/__root.tsx | 3 + apps/web/src/state/knownEnvironments.ts | 39 ++++ apps/web/src/state/peerLinks.ts | 167 +++++++++++++- docs/user/remote-access.md | 12 ++ .../client-runtime/src/linkRequest.test.ts | 153 ++++++++++++- packages/client-runtime/src/linkRequest.ts | 139 ++++++++++-- .../client-runtime/src/state/peerLinks.ts | 36 +++- .../contracts/src/clientRpcPermissions.ts | 4 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/orchestratorMcp.ts | 23 ++ packages/contracts/src/peerLink.ts | 89 ++++++++ packages/contracts/src/rpc.ts | 27 +++ 31 files changed, 1524 insertions(+), 85 deletions(-) create mode 100644 apps/server/src/peer/LinkAppPairing.test.ts create mode 100644 apps/server/src/peer/knownEnvironments.test.ts create mode 100644 apps/server/src/peer/knownEnvironments.ts create mode 100644 apps/web/src/state/knownEnvironments.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 9599adbba2bd..02455cd0172e 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -93,6 +93,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope, [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope, [WS_METHODS.peerLinksList]: AuthAccessReadScope, + [WS_METHODS.peerLinksEnvironments]: AuthAccessReadScope, [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope, [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope, [WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index d7d309280e21..3b4dc9eb0768 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -294,6 +294,7 @@ export const make = Effect.gen(function* () { threadInbox: true, mcpModeLimitHeader: true, linkFence: true, + linkedAppPairing: true, mcpApprovalCodes: true, mcpHostedApproval: true, shellThreadFamilies: true, diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index e306e775dc8a..8cca204209e8 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -106,6 +106,20 @@ export const clientModeCeiling = (client: McpClientCaller | undefined): ClientMo }; }; +/** + * The access a client app added through a link gets (`t3_link_app_pairing`). A + * client session has no runtime-mode ceiling, so it may act only when the link + * may act in any mode: full access, not narrowed. Anything else reads. + */ +export const linkedAppAccess = (client: McpClientCaller): "read-only" | "full-access" => { + const ceiling = clientModeCeiling(client); + return client.access === "full-access" && + ceiling.runtimeMode === "full-access" && + ceiling.interactionMode === "default" + ? "full-access" + : "read-only"; +}; + /** * A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed * itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose. @@ -256,3 +270,10 @@ export const requireThreadScope = (scope: McpInvocationScope, operation: string) scope.thread === undefined ? Effect.fail(threadCallerRequired(operation)) : Effect.succeed(scope as McpThreadInvocationScope); + +/** `McpSchema.EnabledWhen` for tools only another environment's link may call. */ +export const onlyForLinks = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope?.client?.linked === true && scope.linkedEnvironments !== false; +}; diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index dfa1ad58545e..f49890eafa69 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -1,6 +1,10 @@ -import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import { mcpClientScopes, OrchestratorMcpFailure } from "@t3tools/contracts"; import { OrchestratorToolkit } from "./tools.ts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as EnvironmentAuth from "../../../auth/EnvironmentAuth.ts"; import * as PeerForwarding from "../../../peer/PeerForwarding.ts"; import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts"; @@ -12,6 +16,49 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts"; import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; +/** + * The link already holds this access here, so the client it adds holds no more. Auth is taken + * once, when the handlers are built, so harnesses that never pair need not provide it. + */ +export const linkAppPairing = Effect.map( + Effect.serviceOption(EnvironmentAuth.EnvironmentAuth), + (environmentAuth) => + McpToolAccess.reads(() => + Effect.gen(function* () { + const { client } = yield* McpInvocationContext.McpInvocationContext; + if (client?.linked !== true) { + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Only a linked T3 Code environment can add this one to its app.", + }); + } + if (Option.isNone(environmentAuth)) { + return yield* new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "This environment cannot issue pairing codes here.", + }); + } + const access = McpInvocationContext.linkedAppAccess(client); + const issued = yield* environmentAuth.value + .issuePairingCredential({ + scopes: mcpClientScopes(access), + label: `${client.label} (app)`, + }) + .pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ code: "capability_denied", message: error.message }), + ), + ); + return { + credential: issued.credential, + expiresAt: DateTime.formatIso(issued.expiresAt), + access, + }; + }), + ), +); + const handlers = { orchestrator_capabilities: McpToolAccess.reads((input) => Effect.gen(function* () { @@ -237,6 +284,9 @@ const handlers = { return yield* service.interruptThread(scope, input); }), ), -} satisfies McpToolAccess.Handlers; +} satisfies Omit, "t3_link_app_pairing">; -export const layer = McpToolAccess.toLayer(OrchestratorToolkit, handlers); +export const layer = McpToolAccess.toLayer( + OrchestratorToolkit, + Effect.map(linkAppPairing, (pairing) => ({ ...handlers, t3_link_app_pairing: pairing })), +); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 252693b32156..de6959d2e807 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -7,6 +7,7 @@ import { OrchestratorMcpEnvironmentLinksResult, OrchestratorMcpEnvironmentUnlinkInput, OrchestratorMcpEnvironmentUnlinkResult, + OrchestratorMcpLinkAppPairingResult, OrchestratorMcpCreateThreadsInput, OrchestratorMcpCreateThreadsResult, OrchestratorMcpDelegateTaskInput, @@ -362,6 +363,19 @@ const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", { .annotate(Tool.Idempotent, true) .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileLinksOff); +// Offered to another environment's link only, never to an agent. +export const LinkAppPairingTool = Tool.make("t3_link_app_pairing", { + description: + "For a linked T3 Code environment: a one-time pairing code that adds this environment to its own app, at no more than the link's access.", + success: OrchestratorMcpLinkAppPairingResult, + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [McpInvocationContext.McpInvocationContext], +}) + .annotate(Tool.Title, "Add this environment to a linked app") + .annotate(Tool.Destructive, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.onlyForLinks); + export const OrchestratorToolkit = Toolkit.make( OrchestratorCapabilitiesTool, DelegateTaskTool, @@ -383,4 +397,5 @@ export const OrchestratorToolkit = Toolkit.make( EnvironmentLinksTool, EnvironmentLinkTool, EnvironmentUnlinkTool, + LinkAppPairingTool, ); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 6ffd88b2ab78..7602662e73d1 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -69,6 +69,9 @@ const RPC_AGGREGATES = { [WS_METHODS.peerLinksList]: "peerLinks", [WS_METHODS.peerLinksLink]: "peerLinks", [WS_METHODS.peerLinksUnlink]: "peerLinks", + [WS_METHODS.peerLinksAddToApp]: "peerLinks", + [WS_METHODS.peerLinksEnvironments]: "peerLinks", + [WS_METHODS.peerLinksReportAppConnections]: "peerLinks", [WS_METHODS.peerLinksAnswerRequest]: "peerLinks", [WS_METHODS.serverGetSettings]: "server", [WS_METHODS.serverUpdateSettings]: "server", diff --git a/apps/server/src/peer/LinkAppPairing.test.ts b/apps/server/src/peer/LinkAppPairing.test.ts new file mode 100644 index 000000000000..3d006696c536 --- /dev/null +++ b/apps/server/src/peer/LinkAppPairing.test.ts @@ -0,0 +1,78 @@ +import { NodeHttpServer } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import { + type AuthMcpClientAccess, + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + OrchestratorMcpLinkAppPairingResult, + type RuntimeMode, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { Toolkit } from "effect/ai"; + +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import * as McpToolAccess from "../mcp/McpToolAccess.ts"; +import { linkAppPairing } from "../mcp/toolkits/orchestrator/handlers.ts"; +import { LinkAppPairingTool } from "../mcp/toolkits/orchestrator/tools.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts"; + +const toolkit = Toolkit.make(LinkAppPairingTool); + +it.effect.each<{ + readonly access: AuthMcpClientAccess; + readonly narrowedTo: RuntimeMode; + readonly added: "read-only" | "full-access"; +}>([ + { access: "read-only", narrowedTo: "full-access", added: "read-only" }, + { access: "auto", narrowedTo: "full-access", added: "read-only" }, + { access: "full-access", narrowedTo: "auto", added: "read-only" }, + { access: "full-access", narrowedTo: "full-access", added: "full-access" }, +])( + "a $access link narrowed to $narrowedTo adds a $added app there", + ({ access, narrowedTo, added }) => + Effect.scoped( + Effect.gen(function* () { + const box = descriptorOf("environment-box", "Box", { linkedAppPairing: true }); + const handlers = McpToolAccess.toLayer( + toolkit, + Effect.map(linkAppPairing, (pairing) => ({ t3_link_app_pairing: pairing })), + ); + const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers)); + const context = yield* Layer.build( + layerLinkingEnvironment(descriptorOf("environment-a", "A")), + ); + yield* linkTo(Context.get(context, PeerLinks.PeerLinks), b, access); + const issued = yield* Context.get(context, PeerMcpClient.PeerMcpClient).call({ + environmentId: box.environmentId, + tool: "t3_link_app_pairing", + arguments: {}, + limits: { runtimeMode: narrowedTo, interactionMode: "default" }, + success: OrchestratorMcpLinkAppPairingResult, + }); + expect(issued.access).toBe(added); + // The peer lists it with its pairing links, so it can be revoked there before use. + const listed = (yield* b.auth.listPairingLinks()).find( + (link) => link.label === "T3 Code · A (app)", + ); + expect(listed?.permissions).toContain(AuthOrchestrationReadScope); + expect(listed?.permissions?.includes(AuthOrchestrationOperateScope)).toBe( + added === "full-access", + ); + // Asking for more when it is spent gets no more than it carries. + if (added === "read-only") { + const broader = yield* b.auth + .exchangeBootstrapCredentialForAccessToken( + issued.credential, + [AuthOrchestrationOperateScope], + { deviceType: "desktop" }, + ) + .pipe(Effect.flip); + expect(broader._tag).toBe("ServerAuthScopeNotGrantedError"); + } + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index 365fb55f206c..d549ab7b0aa8 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -2,13 +2,15 @@ import { type EnvironmentId, OrchestratorMcpFailure, type OrchestratorMcpEnvironmentLinksResult, + OrchestratorMcpLinkAppPairingResult, OrchestratorMcpThreadInterruptInput, OrchestratorMcpThreadInterruptResult, OrchestratorMcpThreadReadInput, OrchestratorMcpThreadReadResult, OrchestratorMcpThreadWaitInput, OrchestratorMcpThreadWaitResult, - type PeerLinkError, + type PeerLinkAppPairing, + PeerLinkError, RuntimeMode, type ThreadId, } from "@t3tools/contracts"; @@ -108,6 +110,14 @@ export class PeerForwarding extends Context.Service< environmentId: EnvironmentId, params: Tool.Parameters, ) => Effect.Effect, OrchestratorMcpFailure>; + /** + * A one-time pairing credential `environmentId` mints over its link, so this + * server's own client can add it as a connection. The peer caps it at the + * link's access and lists it under its Authorized clients. + */ + readonly addToApp: ( + environmentId: EnvironmentId, + ) => Effect.Effect; /** The environments this one links to, as an agent sees them. */ readonly links: ( scope: Scope, @@ -338,17 +348,37 @@ const make = Effect.gen(function* () { function* (scope) { yield* forwardingCaller(scope); yield* requireEnabled; - const listed = yield* links.list.pipe(Effect.mapError(linkStorageFailure)); + // The same list Settings shows, so agents and the app never disagree on what exists. + const known = yield* links.environments.pipe(Effect.mapError(linkStorageFailure)); + const inAppOnly = known.flatMap((environment) => + environment.link === null && environment.issue !== null + ? [ + { + environmentId: environment.environmentId, + label: environment.label, + serverVersion: environment.serverVersion, + why: environment.issue.message, + }, + ] + : [], + ); return { environmentId: scope.environmentId, - links: listed.map((link) => ({ - environmentId: link.environmentId, - label: link.label, - status: link.status, - access: link.access, - expiresAt: DateTime.formatIso(link.expiresAt), - lastError: link.lastError, - })), + links: known.flatMap(({ link }) => + link === null + ? [] + : [ + { + environmentId: link.environmentId, + label: link.label, + status: link.status, + access: link.access, + expiresAt: DateTime.formatIso(link.expiresAt), + lastError: link.lastError, + }, + ], + ), + ...(inAppOnly.length === 0 ? {} : { inAppOnly }), notListed: NOT_LISTED, }; }, @@ -379,7 +409,61 @@ const make = Effect.gen(function* () { }), ); + const addToApp: PeerForwarding["Service"]["addToApp"] = Effect.fn("PeerForwarding.addToApp")( + function* (environmentId) { + if (!(yield* links.enabled)) { + return yield* new PeerLinkError({ + reason: "disabled", + message: PeerLinks.LINKED_ENVIRONMENTS_OFF, + }); + } + const resolved = yield* links.resolve(environmentId); + const { label, urls } = resolved.link; + if (resolved.capabilities.linkedAppPairing !== true) { + return yield* new PeerLinkError({ + reason: "incompatible", + message: `${label} runs a T3 Code version that cannot add itself to this app. Update ${label}, then try again.`, + }); + } + // Full access here narrows nothing: the peer caps the credential at the link's access. + const issued = yield* peers + .call({ + environmentId, + tool: "t3_link_app_pairing", + arguments: {}, + limits: { runtimeMode: "full-access", interactionMode: "default" }, + expectedIncarnation: resolved.incarnation, + success: OrchestratorMcpLinkAppPairingResult, + }) + .pipe( + Effect.mapError( + (failure) => + new PeerLinkError({ + reason: failure.code === "capability_denied" ? "pairing_rejected" : "unreachable", + message: failure.message, + }), + ), + ); + const expiresAt = DateTime.make(issued.expiresAt); + if (Option.isNone(expiresAt)) { + return yield* new PeerLinkError({ + reason: "incompatible", + message: `${label} answered in a shape this version does not understand. Update both environments.`, + }); + } + return { + environmentId, + label, + urls: [resolved.url, ...urls.filter((url) => url !== resolved.url)], + credential: issued.credential, + expiresAt: DateTime.toUtc(expiresAt.value), + access: issued.access, + }; + }, + ); + return PeerForwarding.of({ + addToApp, call, callNative, readThread, diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 8371591dde05..100997dafaf0 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -1,10 +1,12 @@ import { + type AppConnectionReport, AuthMcpClientAccess, AuthMcpRegistrationError, AuthMcpTokenError, EnvironmentHttpApi, EnvironmentId, type ExecutionEnvironmentCapabilities, + type KnownEnvironment, MCP_PEER_LINK_SOFTWARE_ID, type PeerLink, type PeerLinkCreateInput, @@ -25,6 +27,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Redacted from "effect/Redacted"; +import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; @@ -39,6 +42,7 @@ import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassifi import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ServerSettings from "../serverSettings.ts"; +import { knownEnvironments } from "./knownEnvironments.ts"; const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier) .add(EnvironmentHttpApi.groups.metadata) @@ -81,6 +85,8 @@ export interface ResolvedPeerLink { readonly token: string; /** The session `token` belongs to, from the same stored link: see `PeerLinks.session`. */ readonly incarnation: string; + /** What the peer said it supports when it answered at `url`. */ + readonly capabilities: ExecutionEnvironmentCapabilities; } export const LINKED_ENVIRONMENTS_OFF = @@ -99,6 +105,19 @@ export class PeerLinks extends Context.Service< readonly enabled: Effect.Effect; readonly link: (input: PeerLinkCreateInput) => Effect.Effect; readonly list: Effect.Effect, PeerLinkError>; + /** + * Replaces what one client session says its app holds. Kept in memory: a + * client reports again whenever it connects or its connections change. + */ + readonly reportAppConnections: ( + sessionId: string, + connections: ReadonlyArray, + ) => Effect.Effect; + /** + * Every environment this one knows, links and app connections in one list, + * each saying why it is on one side only. Settings and agents both read it. + */ + readonly environments: Effect.Effect, PeerLinkError>; /** * Machines automatic placement never uses or contacts (server settings). Unreadable settings * fail, so placement contacts nobody rather than everyone. @@ -622,7 +641,12 @@ const make = Effect.gen(function* () { ), ).pipe(Effect.timeoutOption(LIST_PROBE_TIMEOUT), Effect.orElseSucceed(Option.none)); if (Option.isNone(answered)) return { ...link, status: "unreachable" }; - return { ...(yield* withLabel(link, answered.value.label)), status: "reachable" }; + return { + ...(yield* withLabel(link, answered.value.label)), + status: "reachable", + appPairing: answered.value.capabilities.linkedAppPairing === true, + serverVersion: answered.value.serverVersion, + }; }); const list: PeerLinks["Service"]["list"] = Effect.gen(function* () { @@ -633,6 +657,30 @@ const make = Effect.gen(function* () { }); }); + // A client holds at most a catalog's worth; more is not a real app. + const MAX_REPORTED_CONNECTIONS = 200; + const appReports = yield* Ref.make>>( + new Map(), + ); + const reportAppConnections: PeerLinks["Service"]["reportAppConnections"] = ( + sessionId, + connections, + ) => + Ref.update(appReports, (current) => + new Map(current).set(sessionId, connections.slice(0, MAX_REPORTED_CONNECTIONS)), + ); + + const environments: PeerLinks["Service"]["environments"] = Effect.gen(function* () { + const self = yield* environment.getDescriptor; + const links = yield* list; + const reports = yield* Ref.get(appReports); + return knownEnvironments({ + self: self.environmentId, + links, + reports: [...reports.values()].flat(), + }); + }); + const stored: PeerLinks["Service"]["stored"] = Effect.flatMap(readRows, (rows) => Effect.forEach(rows, toLink), ); @@ -718,6 +766,7 @@ const make = Effect.gen(function* () { url, token: new TextDecoder().decode(stored.value), incarnation: row.value.secret_name, + capabilities: peer.capabilities, }; }, ); @@ -748,6 +797,8 @@ const make = Effect.gen(function* () { enabled, link, list, + reportAppConnections, + environments, stored, placementExclusions, session, diff --git a/apps/server/src/peer/PeerMcpClient.test.ts b/apps/server/src/peer/PeerMcpClient.test.ts index 70b610dfa291..3dcf0697afae 100644 --- a/apps/server/src/peer/PeerMcpClient.test.ts +++ b/apps/server/src/peer/PeerMcpClient.test.ts @@ -71,6 +71,7 @@ const probeThrough = Effect.fn(function* (http: HttpClient.HttpClient) { url: "https://peer.example", token: "fixture", incarnation: "fixture-session", + capabilities: box.capabilities, }), recordOutcome: () => Effect.void, }), @@ -301,6 +302,7 @@ it.effect("renews a missing peer session once and reuses its replacement", () => url: "https://peer.example", token: "fixture", incarnation: "fixture-session", + capabilities: box.capabilities, }), recordOutcome: (_, outcome) => Effect.sync(() => outcomes.push(outcome.error)), }), diff --git a/apps/server/src/peer/knownEnvironments.test.ts b/apps/server/src/peer/knownEnvironments.test.ts new file mode 100644 index 000000000000..902b5d89662a --- /dev/null +++ b/apps/server/src/peer/knownEnvironments.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "@effect/vitest"; +import { + type AppConnectionReport, + EnvironmentId, + type KnownEnvironmentAction, + type PeerLinkSummary, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import { knownEnvironments } from "./knownEnvironments.ts"; + +const self = EnvironmentId.make("laptop"); + +const link = ( + id: string, + label: string, + overrides: Partial = {}, +): PeerLinkSummary => ({ + environmentId: EnvironmentId.make(id), + label, + urls: [`https://${id}.example.ts.net`], + access: "full-access", + linkedAt: DateTime.makeUnsafe("2026-11-01T00:00:00Z"), + expiresAt: DateTime.makeUnsafe("2026-12-01T00:00:00Z"), + lastReachedAt: null, + lastError: null, + status: "reachable", + appPairing: true, + serverVersion: "0.1.10", + ...overrides, +}); + +const app = ( + id: string, + label: string, + overrides: Partial = {}, +): AppConnectionReport => ({ + environmentId: EnvironmentId.make(id), + label, + urls: [`https://${id}.example.ts.net`], + serverVersion: "0.1.10", + keepsLinkLimits: true, + ...overrides, +}); + +describe("knownEnvironments", () => { + it.each<{ + readonly name: string; + readonly links: ReadonlyArray; + readonly reports: ReadonlyArray; + readonly action: KnownEnvironmentAction | null | "none"; + readonly message?: string; + }>([ + { + name: "an app connection too old to link asks for an update", + links: [], + reports: [ + app("crown", "Crown", { + serverVersion: "0.1.2", + keepsLinkLimits: false, + urls: ["http://192.168.0.27:3773"], + }), + ], + action: "update", + message: "Crown 0.1.2 is too old to link, so agents here cannot work there. Update it.", + }, + { + name: "an app connection reached only over LAN http asks for a safe address", + links: [], + reports: [app("box", "Box", { urls: ["http://192.168.0.9:3773"] })], + action: "add-address", + }, + { + name: "an app connection with a Tailscale address offers to link", + links: [], + reports: [app("box", "Box", { urls: ["http://box.tail1234.ts.net:3773"] })], + action: "link", + }, + { + name: "a link the app lacks offers to add it", + links: [link("asus", "ASUS")], + reports: [], + action: "add-to-app", + }, + { + name: "a link to a peer too old to add itself asks for an update", + links: [link("r720", "R720", { appPairing: false, serverVersion: "0.1.8" })], + reports: [], + action: "update", + message: "R720 0.1.8 is linked for agents but too old to add to the app. Update it.", + }, + { + name: "a silent link says why it cannot be added now", + links: [link("r720", "R720", { status: "unreachable" })], + reports: [], + action: null, + }, + { + name: "an expired link asks to link again even when the app has it", + links: [link("asus", "ASUS", { status: "expired" })], + reports: [app("asus", "ASUS")], + action: "relink", + }, + { + name: "a machine on both sides has no issue", + links: [link("asus", "ASUS")], + reports: [app("asus", "ASUS")], + action: "none", + }, + ])("$name", ({ links, reports, action, message }) => { + const [entry, ...rest] = knownEnvironments({ self, links, reports }); + expect(rest).toEqual([]); + expect(entry?.issue === null ? "none" : entry?.issue.action).toBe(action); + if (message !== undefined) expect(entry?.issue?.message).toBe(message); + }); + + it("lists each machine once, named as the app names it, and never itself", () => { + const listed = knownEnvironments({ + self, + links: [link("asus", "asus-box", { urls: ["https://asus.example.ts.net"] })], + reports: [ + app("laptop", "This laptop"), + app("asus", "ASUS", { urls: ["http://asus.tail1.ts.net:3773"] }), + app("crown", "Crown", { keepsLinkLimits: false }), + app("crown", "Crown", { urls: ["http://crown.tail1.ts.net:3773"] }), + ], + }); + expect(listed.map((entry) => [entry.environmentId, entry.label, entry.inApp])).toEqual([ + ["asus", "ASUS", true], + ["crown", "Crown", true], + ]); + expect(listed[0]?.urls).toEqual([ + "https://asus.example.ts.net", + "http://asus.tail1.ts.net:3773", + ]); + expect(listed[1]?.urls).toEqual([ + "https://crown.example.ts.net", + "http://crown.tail1.ts.net:3773", + ]); + expect(listed[0]?.link?.access).toBe("full-access"); + expect(listed[1]?.link).toBeNull(); + }); +}); diff --git a/apps/server/src/peer/knownEnvironments.ts b/apps/server/src/peer/knownEnvironments.ts new file mode 100644 index 000000000000..bd5f396a99ac --- /dev/null +++ b/apps/server/src/peer/knownEnvironments.ts @@ -0,0 +1,114 @@ +import type { + AppConnectionReport, + EnvironmentId, + KnownEnvironment, + KnownEnvironmentIssue, + PeerLinkSummary, +} from "@t3tools/contracts"; +import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification"; + +const versioned = (label: string, version: string | null) => + version === null ? label : `${label} ${version}`; + +/** Where this server would send a link's credentials: https, or plain http only over Tailscale. */ +const linkableUrl = (url: string) => { + const parsed = URL.parse(url); + if (parsed === null || isLocalLoopbackHost(parsed.hostname)) return false; + return ( + parsed.protocol === "https:" || (parsed.protocol === "http:" && isTailnetHost(parsed.hostname)) + ); +}; + +/** Why an environment is on only one side, and the one action that fixes it. */ +const environmentIssue = (input: { + readonly label: string; + readonly serverVersion: string | null; + readonly link: PeerLinkSummary | null; + readonly app: AppConnectionReport | undefined; +}): KnownEnvironmentIssue | null => { + const { label, link, app } = input; + const named = versioned(label, input.serverVersion); + if (link !== null) { + if (link.status === "expired") { + return { + action: "relink", + message: `The link to ${label} expired. Link it again with a new pairing code.`, + }; + } + if (app !== undefined) return null; + if (link.status === "unreachable") { + return { + action: null, + message: `${label} is linked for agents but not in the app, and is not answering, so it cannot be added now.`, + }; + } + return link.appPairing === true + ? { action: "add-to-app", message: `${label} is linked for agents but not in the app.` } + : { + action: "update", + message: `${named} is linked for agents but too old to add to the app. Update it.`, + }; + } + if (app === undefined) return null; + if (app.keepsLinkLimits === false) { + return { + action: "update", + message: `${named} is too old to link, so agents here cannot work there. Update it.`, + }; + } + if (!app.urls.some(linkableUrl)) { + return { + action: "add-address", + message: `The app reaches ${label} only over plain http, which would send a link's credentials unencrypted. Add its https or Tailscale address, then link it.`, + }; + } + return { + action: "link", + message: `${label} is in the app but not linked, so agents here cannot work there.`, + }; +}; + +/** + * One list of the environments this one knows: its links, in their order, then those only its + * clients' apps hold. A machine on both sides is one entry, named as the app names it. + */ +export function knownEnvironments(input: { + readonly self: EnvironmentId; + readonly links: ReadonlyArray; + readonly reports: Iterable; +}): ReadonlyArray { + const app = new Map(); + for (const report of input.reports) { + if (report.environmentId === input.self) continue; + const seen = app.get(report.environmentId); + app.set( + report.environmentId, + seen === undefined ? report : { ...seen, urls: [...new Set([...seen.urls, ...report.urls])] }, + ); + } + const linked = input.links.filter((link) => link.environmentId !== input.self); + const linkedIds = new Set(linked.map((link) => link.environmentId)); + const entry = ( + environmentId: EnvironmentId, + link: PeerLinkSummary | null, + report: AppConnectionReport | undefined, + ) => { + const label = report?.label ?? link?.label ?? ""; + const serverVersion = link?.serverVersion ?? report?.serverVersion ?? null; + return { + environmentId, + label, + urls: [...new Set([...(link?.urls ?? []), ...(report?.urls ?? [])])], + serverVersion, + link, + inApp: report !== undefined, + issue: environmentIssue({ label, serverVersion, link, app: report }), + } satisfies KnownEnvironment; + }; + return [ + ...linked.map((link) => entry(link.environmentId, link, app.get(link.environmentId))), + ...[...app.values()] + .filter((report) => !linkedIds.has(report.environmentId)) + .map((report) => entry(report.environmentId, null, report)), + ]; +} diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index ab49f2b6c830..b1c8a7898fa9 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 52637 + "mcpToolListJsonBytes": 52881 } diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index d79969d62a98..d932d108532a 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -102,6 +102,7 @@ import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as RpcAuthorization from "./auth/RpcAuthorization.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; +import * as PeerForwarding from "./peer/PeerForwarding.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as PreviewManager from "./preview/Manager.ts"; @@ -845,6 +846,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}), Layer.mock(PairingGrantStore.PairingGrantStore)({}), Layer.mock(PeerLinks.PeerLinks)({}), + Layer.mock(PeerForwarding.PeerForwarding)({}), Layer.mock(PeerLinkRequests.PeerLinkRequests)({}), Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }), Layer.mock(PreviewManager.PreviewManager)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index feb2ef6ac65a..01d4ae9c6750 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -7,6 +7,7 @@ import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; +import * as PeerForwarding from "./peer/PeerForwarding.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as DateTime from "effect/DateTime"; @@ -1549,6 +1550,7 @@ export const layerWsRpc = ( const serverSettings = yield* ServerSettings.ServerSettingsService; const secretResolver = yield* SecretResolver.SecretResolver; const peerLinks = yield* PeerLinks.PeerLinks; + const peerForwarding = yield* PeerForwarding.PeerForwarding; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; @@ -2747,6 +2749,12 @@ export const layerWsRpc = ( [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), + [WS_METHODS.peerLinksAddToApp]: ({ environmentId }) => + peerForwarding.addToApp(environmentId), + [WS_METHODS.peerLinksEnvironments]: (_input) => + peerLinks.environments.pipe(Effect.map((environments) => ({ environments }))), + [WS_METHODS.peerLinksReportAppConnections]: ({ connections }) => + peerLinks.reportAppConnections(currentSessionId, connections), [WS_METHODS.peerLinksAnswerRequest]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerLinkRequests.answer(input)), @@ -3654,6 +3662,7 @@ export const layer = Layer.unwrap( const pullRequests = yield* PullRequestService.PullRequestService; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const peerLinks = yield* PeerLinks.PeerLinks; + const peerForwarding = yield* PeerForwarding.PeerForwarding; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; const sql = yield* SqlClient.SqlClient; return HttpRouter.add( @@ -3749,6 +3758,7 @@ export const layer = Layer.unwrap( ), ), Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)), + Layer.provide(Layer.succeed(PeerForwarding.PeerForwarding, peerForwarding)), Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)), Layer.provide( SourceControlDiscovery.layer.pipe( diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index 1002f188c78d..b2e2bfde2328 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -3,6 +3,8 @@ import { ChevronsLeftRightEllipsisIcon, PlusIcon, TerminalIcon } from "lucide-re import { useAtomValue } from "@effect/atom-react"; import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react"; import { + AuthAccessWriteScope, + type AuthMcpClientAccess, type DesktopDiscoveredSshHost, type DesktopSshEnvironmentTarget, } from "@t3tools/contracts"; @@ -48,6 +50,10 @@ import { connectSshEnvironment as connectSshEnvironmentAtom, } from "~/connection/onboarding"; import { useEnvironmentQuery } from "~/state/query"; +import { linkOnConnect, usePeerLinkHosts } from "~/state/peerLinks"; +import { useEnvironmentsWithScope } from "~/state/session"; +import { Checkbox } from "../ui/checkbox"; +import { LinkAccessPicker } from "./LinkAccessPicker"; import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desktopSshHosts"; import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -96,6 +102,12 @@ export function AddEnvironmentDialog({ reportFailure: false, }); const relayDiscoveryState = useRelayEnvironmentDiscovery(); + // Adding is the approval: the user sees, and can untick, the link it also asks for. + const peerLinkHosts = usePeerLinkHosts(); + const linkableFrom = useEnvironmentsWithScope(peerLinkHosts, AuthAccessWriteScope); + const linkHosts = peerLinkHosts.filter((host) => linkableFrom.has(host.environmentId)); + const [linkForAgents, setLinkForAgents] = useState(true); + const [linkAccess, setLinkAccess] = useState("approval-required"); const savedDesktopSshEnvironmentKeys = (() => { const keys = new Set(); for (const environment of savedEnvironments) { @@ -252,6 +264,13 @@ export function AddEnvironmentDialog({ return; } + if (routeTarget === null && linkForAgents) { + linkOnConnect( + result.value, + linkAccess, + linkHosts.map((host) => host.environmentId), + ); + } handleOpenChange(false); toastManager.add( routeTarget @@ -476,6 +495,31 @@ export function AddEnvironmentDialog({ ) : null} {renderRemoteFields()} + {routeTarget === null && linkHosts.length > 0 ? ( +
+ + {linkForAgents ? ( + + ) : null} +
+ ) : null} {error ?

{error}

: null} + {canAddToApp && row.action === "add-to-app" ? ( + + ) : null} + {canUnlink ? ( + + ) : null} ) : null} @@ -180,11 +304,18 @@ function LinkedEnvironmentRow({ ); } -function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) { +function LinkEnvironmentAction({ + environmentId, + preselect, +}: { + readonly environmentId: EnvironmentId; + /** Opens on this machine, from its own row. */ + readonly preselect?: EnvironmentId; +}) { const [open, setOpen] = useState(false); const machines = useLinkableMachines(environmentId, open); // Null until the user picks; with no other machines known, only an address is left. - const [choice, setChoice] = useState(null); + const [choice, setChoice] = useState(preselect ?? null); const [address, setAddress] = useState(""); const [pairingCode, setPairingCode] = useState(""); const [access, setAccess] = useState("approval-required"); @@ -218,7 +349,7 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi const handleOpenChange = (next: boolean) => { setOpen(next); if (!next) { - setChoice(null); + setChoice(preselect ?? null); setAddress(""); setPairingCode(""); setAccess("approval-required"); @@ -277,10 +408,16 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi > - - Link - + preselect === undefined ? ( + + ) : ( + + ) } /> diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 19c69c8c0708..be65b66483ae 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -60,6 +60,7 @@ import { readProject } from "../state/entities"; import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; +import { AppConnectionReporter, LinkOnConnectCoordinator } from "../state/peerLinks"; export const Route = createRootRoute({ beforeLoad: async ({ location }) => { @@ -194,6 +195,8 @@ function RootRouteBranch() { + + {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} diff --git a/apps/web/src/state/knownEnvironments.ts b/apps/web/src/state/knownEnvironments.ts new file mode 100644 index 000000000000..a06c493cca11 --- /dev/null +++ b/apps/web/src/state/knownEnvironments.ts @@ -0,0 +1,39 @@ +import { + knownEnvironmentRows, + type KnownEnvironmentRow, + reachesOverLoopback, +} from "@t3tools/client-runtime/link-request"; +import type { EnvironmentId } from "@t3tools/contracts"; + +import { useEnvironments } from "./environments"; +import { peerLinkEnvironment } from "./peerLinks"; +import { useEnvironmentQuery } from "./query"; + +/** + * Every environment `environmentId` knows, from one list it owns: its links and the + * connections its clients' apps hold, each with why it is on one side only. Joined with + * whether this client holds and reaches each. Settings and the sidebar read it. + */ +export function useKnownEnvironments(environmentId: EnvironmentId | null): { + readonly rows: ReadonlyArray; + readonly error: string | null; + readonly loading: boolean; + readonly isPending: boolean; + readonly refresh: () => void; +} { + const { environments } = useEnvironments(); + const known = useEnvironmentQuery( + environmentId === null ? null : peerLinkEnvironment.environments({ environmentId, input: {} }), + ); + const host = environments.find((environment) => environment.environmentId === environmentId); + return { + rows: knownEnvironmentRows(known.data?.environments ?? [], environments, { + label: host?.label ?? "That environment", + onHostMachine: host !== undefined && reachesOverLoopback(host), + }), + error: known.error, + loading: environmentId !== null && !known.data, + isPending: known.isPending, + refresh: known.refresh, + }; +} diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts index b19276c6f88b..ca5639958fc7 100644 --- a/apps/web/src/state/peerLinks.ts +++ b/apps/web/src/state/peerLinks.ts @@ -1,15 +1,26 @@ import { useAtomValue } from "@effect/atom-react"; import { + appConnectionReports, linkableMachines, linkedEnvironmentNames, + linkRequestFailureMessage, offersLinkedEnvironments, } from "@t3tools/client-runtime/link-request"; import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; -import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts"; -import { Atom } from "effect/reactivity"; +import { + AuthAccessReadScope, + AuthAccessWriteScope, + type AuthMcpClientAccess, + type EnvironmentId, +} from "@t3tools/contracts"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { AsyncResult, Atom } from "effect/reactivity"; import { useEffect, useEffectEvent } from "react"; import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { stackedThreadToast, toastManager } from "../components/ui/toast"; +import { mintPairingCodeOn } from "./peerPairingCode"; import { useEnvironmentIdentities, useEnvironments } from "./environments"; import { environmentPresentations } from "./presentation"; import { relayEnvironmentDiscovery } from "./relay"; @@ -92,3 +103,155 @@ export function useLinkableMachines(environmentId: EnvironmentId, enabled: boole connect: discovery.environments, }); } + +/** + * The hosts among `hosts` whose loaded list links `target`, for offering to unlink there too. + * A list not loaded yet counts as not linking: the offer is a convenience, never the only way. + */ +export function hostsLinking( + hosts: ReadonlyArray<{ readonly environmentId: EnvironmentId }>, + target: EnvironmentId, +): ReadonlyArray { + return hosts.flatMap(({ environmentId }) => { + if (environmentId === target) return []; + const known = AsyncResult.getOrElse( + appAtomRegistry.get(peerLinkEnvironment.environments({ environmentId, input: {} })), + () => null, + ); + return known?.environments.some( + (environment) => environment.environmentId === target && environment.link !== null, + ) + ? [environmentId] + : []; + }); +} + +/** + * Tells each connected environment that offers links which connections this app holds, so + * its own list, and its agents, see them. Addresses and versions only, never a credential. + */ +export function AppConnectionReporter() { + const { environments } = useEnvironments(); + const hosts = usePeerLinkHosts(); + const reportable = useEnvironmentsWithScope(hosts, AuthAccessWriteScope); + const report = useAtomCommand(peerLinkEnvironment.reportAppConnections, { + reportFailure: false, + }); + const connections = appConnectionReports(environments); + const key = JSON.stringify([[...reportable].toSorted(), connections]); + // Takes the snapshot it fires for, so the effect names what it depends on. + const send = useEffectEvent((_snapshot: string) => { + for (const environmentId of reportable) { + void report({ environmentId, input: { connections } }); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes this app's connections to each server, outside React, when they or the servers change + useEffect(() => send(key), [key]); + return null; +} + +/** + * Links `machine` from `hostId` with a code this client mints there with its own session, + * the way the Link dialog does. Resolves to the failure to show, or null once linked. + */ +export async function linkFromThisApp( + hostId: EnvironmentId, + machine: { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly urls: ReadonlyArray; + }, + access: AuthMcpClientAccess, +): Promise { + const [url, ...alternateUrls] = machine.urls; + if (url === undefined) + return `This app has no address for ${machine.label} that another machine can reach.`; + const code = await mintPairingCodeOn(machine.environmentId, access); + if (code._tag === "Failure") return linkRequestFailureMessage(code.failure); + const linked = await peerLinkEnvironment.link.run(appAtomRegistry, { + environmentId: hostId, + input: { + url, + ...(alternateUrls.length > 0 ? { alternateUrls } : {}), + expectedEnvironmentId: machine.environmentId, + expectedLabel: machine.label, + pairingCode: code.success, + access, + }, + }); + return linked._tag === "Success" ? null : String(squashAtomCommandFailure(linked)); +} + +/** Links the user chose while adding a connection, kept until that connection connects. */ +const pendingLinksAtom = Atom.make< + ReadonlyMap< + EnvironmentId, + { readonly access: AuthMcpClientAccess; readonly hosts: ReadonlyArray } + > +>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("peer-links:pending-on-connect")); + +/** Links `environmentId` from `hosts` once this app connects to it: adding it was the approval. */ +export function linkOnConnect( + environmentId: EnvironmentId, + access: AuthMcpClientAccess, + hosts: ReadonlyArray, +) { + const hostsElsewhere = hosts.filter((host) => host !== environmentId); + if (hostsElsewhere.length === 0) return; + appAtomRegistry.set( + pendingLinksAtom, + new Map(appAtomRegistry.get(pendingLinksAtom)).set(environmentId, { + access, + hosts: hostsElsewhere, + }), + ); +} + +/** Carries out `linkOnConnect` choices as their connections come up. */ +export function LinkOnConnectCoordinator() { + const pending = useAtomValue(pendingLinksAtom); + const { environments } = useEnvironments(); + const ready = environments.filter( + (environment) => + pending.has(environment.environmentId) && + environment.connection.phase === "connected" && + environment.serverConfig !== null, + ); + const link = useEffectEvent(() => { + if (ready.length === 0) return; + const remaining = new Map(pending); + for (const environment of ready) { + const choice = pending.get(environment.environmentId); + remaining.delete(environment.environmentId); + const [report] = appConnectionReports([environment]); + if (choice === undefined || report === undefined) continue; + if (report.keepsLinkLimits === false) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: `${report.label} was added but not linked`, + description: `${report.label}${report.serverVersion === null ? "" : ` ${report.serverVersion}`} is too old to link, so agents cannot work there. Update it, then link it from Linked environments.`, + }), + ); + continue; + } + for (const host of choice.hosts) { + void linkFromThisApp(host, report, choice.access).then((failure) => + toastManager.add( + failure === null + ? { type: "success", title: `Linked ${report.label} for agents` } + : stackedThreadToast({ + type: "error", + title: `${report.label} was added but not linked`, + description: failure, + }), + ), + ); + } + } + appAtomRegistry.set(pendingLinksAtom, remaining); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links a machine on another server once its connection here comes up + useEffect(() => link(), [ready.map((environment) => environment.environmentId).join("\n")]); + return null; +} diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index c963e22b8d6a..f6e7c124d3cd 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -390,6 +390,18 @@ an address you trust: the code is sent there. removes it here. - Links last 30 days. Link again with a new pairing code to renew one. +The app and its machine keep one list of your environments: what this machine +links and what the app connects to. **Linked environments** shows a machine +that is on only one side with the reason and the fix, and agents see the same +reasons. When you add an environment in **Settings → Environments**, leave **Also link it +for agents** ticked to link it once it connects. A linked machine the app is +not connected to has **Add to this app**, which adds it at no more than the +link's access: a full-access link adds a full client, anything less adds a +read-only one, and that machine lists it under **Sharing & access**. An +environment too old for either shows **Update it**. Removing an environment +offers to forget its link too, and forgetting a link offers to remove the +environment from the app. + An agent can also hand a task to a linked machine with `delegate_task`: it runs there as an ordinary thread, in the project with the same repository (or the one `target.projectId` names), and this thread wakes with its result when it diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts index dc8a1b94db9e..0fe4daffe4ea 100644 --- a/packages/client-runtime/src/linkRequest.test.ts +++ b/packages/client-runtime/src/linkRequest.test.ts @@ -1,5 +1,12 @@ -import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { + EnvironmentId, + type KnownEnvironment, + type ServerConfig, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay"; +import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { describe, expect, it } from "vite-plus/test"; @@ -9,6 +16,9 @@ import type { EnvironmentPresentation } from "./connection/presentation.ts"; import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts"; import { ANOTHER_ADDRESS, + appConnectionReports, + appPairingAddress, + knownEnvironmentRows, linkableMachines, linkedEnvironmentNames, linkRequestAnswerInput, @@ -337,6 +347,147 @@ describe("linkableMachines", () => { }); }); +describe("appConnectionReports", () => { + it("reports where each connection answers and whether it can be linked, and nothing else", () => { + const configured = ( + environment: ReturnType, + serverVersion: string, + capabilities: object, + ) => ({ + ...environment, + serverConfig: { + environment: { serverVersion, capabilities }, + directEndpoints: [], + } as unknown as ServerConfig, + }); + const crown = configured( + presentation("environment-crown", "Crown", { saved: ["http://192.168.0.27:3773"] }), + "0.1.2", + {}, + ); + const vps = configured( + presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] }), + "0.1.10", + { mcpModeLimitHeader: true, linkFence: true }, + ); + const mini = presentation("environment-mini", "Mini", { connected: false }); + expect(appConnectionReports([crown, vps, mini])).toEqual([ + { + environmentId: crown.environmentId, + label: "Crown", + urls: ["http://192.168.0.27:3773"], + serverVersion: "0.1.2", + keepsLinkLimits: false, + }, + { + environmentId: vps.environmentId, + label: "VPS", + urls: ["https://vps.ts.net"], + serverVersion: "0.1.10", + keepsLinkLimits: true, + }, + // Never reached, so whether it can be linked is unknown rather than "too old". + { + environmentId: mini.environmentId, + label: "Mini", + urls: [], + serverVersion: null, + keepsLinkLimits: null, + }, + ]); + }); +}); + +describe("knownEnvironmentRows", () => { + const known = ( + id: string, + action: "link" | "add-to-app" | null, + linked: boolean, + ): KnownEnvironment => ({ + environmentId: EnvironmentId.make(id), + label: id, + urls: [], + serverVersion: null, + link: linked + ? { + environmentId: EnvironmentId.make(id), + label: id, + urls: [`https://${id}.example.ts.net`], + access: "read-only", + linkedAt: DateTime.makeUnsafe("2026-11-01T00:00:00Z"), + expiresAt: DateTime.makeUnsafe("2026-12-01T00:00:00Z"), + lastReachedAt: null, + lastError: null, + status: "reachable", + } + : null, + inApp: !linked, + issue: action === null ? null : { action, message: `${id}: ${action}` }, + }); + + it("offers an action only where this client can take it", () => { + const rows = knownEnvironmentRows( + [ + known("asus", "add-to-app", true), + known("r720", "add-to-app", true), + known("box", "link", false), + known("crown", "link", false), + ], + [ + presentation("r720", "R720", { connected: false }), + presentation("box", "Box"), + presentation("crown", "Crown", { connected: false }), + ], + { label: "Laptop", onHostMachine: true }, + ); + expect( + rows.map((row) => [ + row.environmentId, + row.action, + row.issue?.action ?? null, + row.connected, + row.reachability, + row.linkAccess, + ]), + ).toEqual([ + ["asus", "add-to-app", "add-to-app", false, "reachable", "read-only"], + // Already in this app, before the server heard so: nothing is missing. + ["r720", null, null, false, "reachable", "read-only"], + ["box", "link", "link", true, "reachable", null], + // Only a connected app can mint the code a link needs; the issue still shows. + ["crown", null, "link", false, "unknown", null], + ]); + }); + + it("adds a link's local forward only from the host's own machine", () => { + const base = known("asus", "add-to-app", true); + const forwarded = { + ...base, + link: base.link === null ? null : { ...base.link, urls: ["http://127.0.0.1:13780"] }, + }; + const [onLaptop] = knownEnvironmentRows([forwarded], [], { + label: "Laptop", + onHostMachine: true, + }); + expect([onLaptop?.action, onLaptop?.appAddress]).toEqual([ + "add-to-app", + "http://127.0.0.1:13780", + ]); + // A browser on a phone would open its own loopback: say so instead of offering a dead button. + const [elsewhere] = knownEnvironmentRows([forwarded], [], { + label: "Laptop", + onHostMachine: false, + }); + expect(elsewhere?.action).toBeNull(); + expect(elsewhere?.issue?.message).toBe( + "Laptop reaches asus only at its own local address, which this device cannot open. Add it from the app on Laptop.", + ); + expect( + appPairingAddress(["http://127.0.0.1:13780", "https://asus.example.ts.net"], false), + ).toBe("https://asus.example.ts.net"); + }); +}); + describe("linkedEnvironmentNames", () => { it("names the unexpired links as this client does, else as the link does", () => { const vps = EnvironmentId.make("environment-vps"); diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts index d1cf9e81d9f9..4eeb4840716d 100644 --- a/packages/client-runtime/src/linkRequest.ts +++ b/packages/client-runtime/src/linkRequest.ts @@ -1,6 +1,9 @@ import { + type AppConnectionReport, type AuthMcpClientAccess, type EnvironmentId, + type KnownEnvironment, + type KnownEnvironmentAction, type EnvironmentMachineKind, type OrchestrationV2TurnItem, type PeerLinkRequestAnswerInput, @@ -97,6 +100,127 @@ const isLoopbackUrl = (url: string) => { return hostname !== undefined && isLocalLoopbackHost(hostname); }; +/** Where another machine can reach a saved environment: what it reports, its routes, then Connect. */ +const clientUrls = (environment: EnvironmentPresentation, connectUrl: string | undefined) => + [ + ...new Set([ + ...(environment.serverConfig?.directEndpoints ?? []).map((endpoint) => endpoint.httpBaseUrl), + ...connectionRoutes(environment.entry).flatMap((route) => { + const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route); + return url === null ? [] : [url]; + }), + ...(connectUrl === undefined ? [] : [connectUrl]), + ]), + ].filter((url) => !isLoopbackUrl(url)); + +/** + * What this app tells an environment about the connections it holds: where each answers and + * what it runs. Never a credential. + */ +export function appConnectionReports( + environments: ReadonlyArray, +): ReadonlyArray { + return environments.map((environment) => { + const capabilities = environment.serverConfig?.environment.capabilities; + return { + environmentId: environment.environmentId, + label: environment.entry.target.label, + urls: clientUrls(environment, undefined), + serverVersion: environment.serverConfig?.environment.serverVersion ?? null, + keepsLinkLimits: + capabilities === undefined + ? null + : capabilities.mcpModeLimitHeader === true && capabilities.linkFence === true, + }; + }); +} + +/** + * Whether this client reaches `host` at its own loopback, so the host's loopback addresses, + * such as a link's local forward, are this client's too. Relay and SSH routes say no. + */ +export const reachesOverLoopback = (host: Pick): boolean => + connectionRoutes(host.entry).some((route) => { + const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route); + return url !== null && isLoopbackUrl(url); + }); + +/** + * Where this client can add a linked machine: the link's own address, in its order. A + * loopback one names the host's machine, so it counts only when this client is on it. + */ +export const appPairingAddress = ( + urls: ReadonlyArray, + onHostMachine: boolean, +): string | null => urls.find((url) => onHostMachine || !isLoopbackUrl(url)) ?? null; + +/** An environment the app's server knows, with what this client can see and do about it. */ +export interface KnownEnvironmentRow extends KnownEnvironment { + /** This client holds a connection to it and is connected now. */ + readonly connected: boolean; + /** This client holds a connection to it, connected or not. */ + readonly inThisApp: boolean; + readonly reachability: "reachable" | "unreachable" | "expired" | "unknown"; + readonly linkAccess: AuthMcpClientAccess | null; + /** The issue's action, when this client can take it: only the app holding a machine links it. */ + readonly action: KnownEnvironmentAction | null; + /** Where this client would add the linked machine, or null when it reaches none of its addresses. */ + readonly appAddress: string | null; +} + +/** + * The server's environment list, as this client sees it. Linking needs this + * client's own session there; adding needs this client not to hold it yet. + */ +export function knownEnvironmentRows( + known: ReadonlyArray, + environments: ReadonlyArray< + Pick & { readonly environmentId: EnvironmentId } + >, + host: { readonly label: string; readonly onHostMachine: boolean }, +): ReadonlyArray { + const held = new Map(environments.map((environment) => [environment.environmentId, environment])); + return known.map((environment) => { + const here = held.get(environment.environmentId); + const connected = here?.connection.phase === "connected"; + const wanted = environment.issue?.action ?? null; + const appAddress = + environment.link === null + ? null + : appPairingAddress(environment.link.urls, host.onHostMachine); + const unreachableHere = wanted === "add-to-app" && here === undefined && appAddress === null; + const action = + wanted === "add-to-app" + ? here === undefined && appAddress !== null + ? wanted + : null + : wanted === "link" + ? connected + ? wanted + : null + : wanted; + return { + ...environment, + // This app's own view wins over a report that has not arrived yet. + issue: + wanted === "add-to-app" && here !== undefined + ? null + : unreachableHere + ? { + action: "add-to-app", + message: `${host.label} reaches ${environment.label} only at its own local address, which this device cannot open. Add it from the app on ${host.label}.`, + } + : environment.issue, + appAddress, + connected, + inThisApp: here !== undefined, + reachability: environment.link?.status ?? (connected ? "reachable" : "unknown"), + linkAccess: environment.link?.access ?? null, + action, + }; + }); +} + /** * 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 @@ -117,13 +241,6 @@ export function linkableMachines(input: { const saved = input.environments .filter((environment) => environment.environmentId !== input.threadEnvironmentId) .map((environment) => { - const reported = (environment.serverConfig?.directEndpoints ?? []).map( - (endpoint) => endpoint.httpBaseUrl, - ); - const routes = connectionRoutes(environment.entry).flatMap((route) => { - const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route); - return url === null ? [] : [url]; - }); const connect = input.connect.get(environment.environmentId)?.environment.endpoint; return { environmentId: environment.environmentId, @@ -132,13 +249,7 @@ export function linkableMachines(input: { 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)), + urls: clientUrls(environment, connect?.httpBaseUrl), }; }); const savedIds = new Set(saved.map((machine) => machine.environmentId)); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 9295bf1b4015..472582de568c 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -1,8 +1,8 @@ -import { type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts"; +import { type EnvironmentId, type PeerLinkSummary, WS_METHODS } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import { Atom } from "effect/reactivity"; +import { Atom, type AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; @@ -16,19 +16,42 @@ export function createPeerLinkEnvironmentAtoms( // Listing probes every linked environment, so a list stays fresh briefly. staleTimeMs: 10_000, }); + // The links and the app connections together; Settings and the sidebar read it. + const environments = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:peer-links:environments", + tag: WS_METHODS.peerLinksEnvironments, + staleTimeMs: 10_000, + }); + const refreshLists = (environmentId: EnvironmentId, registry: AtomRegistry.AtomRegistry) => + Effect.sync(() => { + registry.refresh(list({ environmentId, input: {} })); + registry.refresh(environments({ environmentId, input: {} })); + }); return { list, + environments, link: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:link", tag: WS_METHODS.peerLinksLink, - onSuccess: ({ environmentId }, registry) => - Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + onSuccess: ({ environmentId }, registry) => refreshLists(environmentId, registry), }), unlink: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:unlink", tag: WS_METHODS.peerLinksUnlink, + onSuccess: ({ environmentId }, registry) => refreshLists(environmentId, registry), + }), + /** A pairing credential the linked environment mints, for adding it to this app. */ + addToApp: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:add-to-app", + tag: WS_METHODS.peerLinksAddToApp, + }), + /** Tells the environment which connections this app holds, never their credentials. */ + reportAppConnections: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:report-app-connections", + tag: WS_METHODS.peerLinksReportAppConnections, + concurrency: { mode: "latest", key: ({ environmentId }) => environmentId }, onSuccess: ({ environmentId }, registry) => - Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + Effect.sync(() => registry.refresh(environments({ environmentId, input: {} }))), }), // An agent's link card. One answer per card at a time. answerRequest: createEnvironmentRpcCommand(runtime, { @@ -39,8 +62,7 @@ export function createPeerLinkEnvironmentAtoms( key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId, input.turnItemId]), }, - onSuccess: ({ environmentId }, registry) => - Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), + onSuccess: ({ environmentId }, registry) => refreshLists(environmentId, registry), }), }; } diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index df6e4647f32e..e2d54a89c834 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -77,6 +77,10 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.guestShareCreate]: AuthAccessWriteScope, [WS_METHODS.peerLinksLink]: AuthAccessWriteScope, [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope, + // Hands this client a pairing credential for the linked environment. + [WS_METHODS.peerLinksAddToApp]: AuthAccessWriteScope, + // Agents here read what the app reports, so only a client that may link reports it. + [WS_METHODS.peerLinksReportAppConnections]: AuthAccessWriteScope, // A link lets every agent here reach the other environment: Settings' bar. [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope, } as const; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 6188f5f901db..474b8a515ec8 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -184,6 +184,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ (`linkOrigin`). Another environment links to this one only when it is set, since without it that work could change the user's own threads. */ linkFence: Schema.optionalKey(Schema.Boolean), + /** An environment linked to this one can add it to its own client app, at no more than the link's access. */ + linkedAppPairing: Schema.optionalKey(Schema.Boolean), /** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */ mcpApprovalCodes: Schema.optionalKey(Schema.Boolean), /** Agent sign-ins on its T3 Connect address are approved on the hosted app, without a code. */ diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 4f454f9ad758..aaad940f90da 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -4,6 +4,7 @@ import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; import { AuthMcpClientAccess } from "./auth.ts"; +import { PeerLinkAppAccess } from "./peerLink.ts"; import { ContextTransferId, EnvironmentId, @@ -698,6 +699,20 @@ export type OrchestratorMcpEnvironmentLink = typeof OrchestratorMcpEnvironmentLi export const OrchestratorMcpEnvironmentLinksResult = Schema.Struct({ environmentId: EnvironmentId, links: Schema.Array(OrchestratorMcpEnvironmentLink), + /** Machines the user's app holds that are not linked here, so no tool can act there yet. */ + inAppOnly: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + serverVersion: Schema.NullOr(Schema.String), + why: Schema.String.annotate({ + description: + "Why it is not linked and what fixes it. Tell the user; linking still needs their approval.", + }), + }), + ), + ), /** What to do when the machine the user means is not among `links`. */ notListed: Schema.String, }); @@ -946,6 +961,14 @@ export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({ export type OrchestratorMcpEnvironmentUnlinkResult = typeof OrchestratorMcpEnvironmentUnlinkResult.Type; +/** A one-time pairing credential for the linking environment's own client app. */ +export const OrchestratorMcpLinkAppPairingResult = Schema.Struct({ + credential: TrimmedNonEmptyString, + expiresAt: Schema.String, + access: PeerLinkAppAccess, +}); +export type OrchestratorMcpLinkAppPairingResult = typeof OrchestratorMcpLinkAppPairingResult.Type; + export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, scheduledTaskId: ScheduledTaskId, diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index f8cf83c1fdbd..61df1dffdb25 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -29,6 +29,14 @@ export type PeerLinkStatus = typeof PeerLinkStatus.Type; export const PeerLinkSummary = Schema.Struct({ ...PeerLink.fields, status: PeerLinkStatus, + /** + * Whether the peer, as it answered this listing, can add itself to this + * environment's client app (`peerLinks.addToApp`). Absent when it did not + * answer, and from servers from before the feature. + */ + appPairing: Schema.optionalKey(Schema.Boolean), + /** The peer's T3 Code version, as it answered this listing. */ + serverVersion: Schema.optionalKey(Schema.String), }); export type PeerLinkSummary = typeof PeerLinkSummary.Type; @@ -56,6 +64,87 @@ export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type; export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean }); export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type; +export const PeerLinkAddToAppInput = Schema.Struct({ environmentId: EnvironmentId }); +export type PeerLinkAddToAppInput = typeof PeerLinkAddToAppInput.Type; + +/** + * The access a client added through a link gets there. A client session has + * no runtime-mode ceiling, so only a full-access link adds a client that can + * act; every other link adds a read-only one. + */ +export const PeerLinkAppAccess = Schema.Literals(["read-only", "full-access"]); +export type PeerLinkAppAccess = typeof PeerLinkAppAccess.Type; + +/** + * A one-time pairing credential the peer minted over the link, for this + * server's own client to add the peer as a normal connection. The peer lists + * the client under its Authorized clients, where it can be revoked. + */ +export const PeerLinkAppPairing = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + /** Where the peer answered this server, the one that answered first. */ + urls: Schema.NonEmptyArray(TrimmedNonEmptyString), + credential: TrimmedNonEmptyString, + expiresAt: Schema.DateTimeUtc, + access: PeerLinkAppAccess, +}); +export type PeerLinkAppPairing = typeof PeerLinkAppPairing.Type; + +/** + * A connection a client of this environment holds, as the client reports it: + * where it answers and what it runs, never its credential. + */ +export const AppConnectionReport = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + urls: Schema.Array(TrimmedNonEmptyString), + serverVersion: Schema.NullOr(Schema.String), + /** + * It holds a linked agent to its limits (`mcpModeLimitHeader` and `linkFence`), so it can be + * linked. Null when the client has not reached it yet and cannot tell. + */ + keepsLinkLimits: Schema.NullOr(Schema.Boolean), +}); +export type AppConnectionReport = typeof AppConnectionReport.Type; + +export const AppConnectionsReportInput = Schema.Struct({ + connections: Schema.Array(AppConnectionReport), +}); +export type AppConnectionsReportInput = typeof AppConnectionsReportInput.Type; + +/** The one action that brings an environment's two sides back together. */ +export const KnownEnvironmentAction = Schema.Literals([ + "link", + "add-to-app", + "update", + "relink", + "add-address", +]); +export type KnownEnvironmentAction = typeof KnownEnvironmentAction.Type; + +export const KnownEnvironmentIssue = Schema.Struct({ + message: Schema.String, + action: Schema.NullOr(KnownEnvironmentAction), +}); +export type KnownEnvironmentIssue = typeof KnownEnvironmentIssue.Type; + +/** + * An environment this one knows: linked here for its agents, held by one of + * its clients' apps, or both. `issue` says why a side is missing, if one is. + */ +export const KnownEnvironment = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + urls: Schema.Array(TrimmedNonEmptyString), + serverVersion: Schema.NullOr(Schema.String), + link: Schema.NullOr(PeerLinkSummary), + /** A client of this environment reported holding a connection to it. */ + inApp: Schema.Boolean, + issue: Schema.NullOr(KnownEnvironmentIssue), +}); +export type KnownEnvironment = typeof KnownEnvironment.Type; + /** Why linking or calling a peer failed, in words a user can act on. */ export class PeerLinkError extends Schema.TaggedError()("PeerLinkError", { reason: Schema.Literals([ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 5b9636d23ed5..d68878a84a7d 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -21,6 +21,10 @@ import { PeerLinkCreateInput, PeerLinkError, PeerLinkRemoveInput, + PeerLinkAddToAppInput, + PeerLinkAppPairing, + AppConnectionsReportInput, + KnownEnvironment, PeerLinkRemoveResult, PeerLinkRequestAnswerInput, PeerLinkRequestError, @@ -523,6 +527,9 @@ export const WS_METHODS = { peerLinksList: "peerLinks.list", peerLinksLink: "peerLinks.link", peerLinksUnlink: "peerLinks.unlink", + peerLinksAddToApp: "peerLinks.addToApp", + peerLinksEnvironments: "peerLinks.environments", + peerLinksReportAppConnections: "peerLinks.reportAppConnections", peerLinksAnswerRequest: "peerLinks.answerRequest", serverGetSettings: "server.getSettings", serverUpdateSettings: "server.updateSettings", @@ -861,6 +868,23 @@ const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, { error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), }); +const WsPeerLinksAddToAppRpc = Rpc.make(WS_METHODS.peerLinksAddToApp, { + payload: PeerLinkAddToAppInput, + success: PeerLinkAppPairing, + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), +}); + +const WsPeerLinksEnvironmentsRpc = Rpc.make(WS_METHODS.peerLinksEnvironments, { + payload: Schema.Struct({}), + success: Schema.Struct({ environments: Schema.Array(KnownEnvironment) }), + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), +}); + +const WsPeerLinksReportAppConnectionsRpc = Rpc.make(WS_METHODS.peerLinksReportAppConnections, { + payload: AppConnectionsReportInput, + error: EnvironmentAuthorizationError, +}); + const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, { payload: PeerLinkRequestAnswerInput, error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]), @@ -2156,6 +2180,9 @@ export const WsRpcGroup = RpcGroup.make( WsPeerLinksListRpc, WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, + WsPeerLinksAddToAppRpc, + WsPeerLinksEnvironmentsRpc, + WsPeerLinksReportAppConnectionsRpc, WsPeerLinksAnswerRequestRpc, WsServerDiscoverSourceControlRpc, WsServerCheckSecretSourceRpc, From e697aeb6bc744244da0ec91ecbe47ac565f8d3fd Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:16:44 +0000 Subject: [PATCH 2/3] fix: apps decide Add to this app from their own connections Repair round 1 for the bot review of PR #80. 1. The client offers "Add to this app" from its own catalog: a reachable link that can pair, to a machine this client does not hold. Another session's report no longer hides it. The server counts a session's app-connection report only while SessionStore still lists that session as active, so a revoked or expired session's report stops counting. 2. The Forget and "Also remove from this app" confirm dialogs, and docs/user/remote-access.md, say that the other machine still lists this app under Authorized clients and can revoke it there. 3. add() tries the addresses addToApp returns, in order, filtered by the appPairingAddress rule (new appPairingAddresses helper). 4. A pending "link on connect" choice is cleared when the environment is removed, and when it is added again with the box unticked. 5. Reported URLs lose any user:pass@ on the client. The server bounds the label and version to 200 characters, drops URLs longer than 2048, and keeps at most 16 URLs per connection. 6. t3_link_app_pairing refuses a call the link makes for one of its agent threads (client.senderThread). Tests cover an outside agent, a thread caller and a link's agent-thread call getting capability_denied, plus an end-to-end call carrying T3-Sender-Thread that mints nothing. Model: claude-opus-5-5 Task: fix Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/toolkits/orchestrator/handlers.ts | 7 ++ apps/server/src/peer/LinkAppPairing.test.ts | 108 ++++++++++++++++++ apps/server/src/peer/PeerLinks.test.ts | 58 +++++++++- apps/server/src/peer/PeerLinks.ts | 31 ++++- .../server/src/peer/knownEnvironments.test.ts | 15 ++- apps/server/src/peer/knownEnvironments.ts | 15 +++ .../settings/AddEnvironmentDialog.tsx | 18 +-- .../settings/ConnectionsSettings.tsx | 9 +- .../settings/LinkedEnvironmentsSettings.tsx | 45 +++++--- apps/web/src/state/peerLinks.ts | 14 ++- docs/user/remote-access.md | 3 +- .../client-runtime/src/linkRequest.test.ts | 16 ++- packages/client-runtime/src/linkRequest.ts | 82 ++++++++----- 13 files changed, 362 insertions(+), 59 deletions(-) diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index f49890eafa69..50f7d738c0b6 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -32,6 +32,13 @@ export const linkAppPairing = Effect.map( message: "Only a linked T3 Code environment can add this one to its app.", }); } + // A call the link makes for one of its agent threads: an agent never gets a credential. + if (client.senderThread !== undefined) { + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Only the linked environment's app can add this one, not its agents.", + }); + } if (Option.isNone(environmentAuth)) { return yield* new OrchestratorMcpFailure({ code: "orchestration_error", diff --git a/apps/server/src/peer/LinkAppPairing.test.ts b/apps/server/src/peer/LinkAppPairing.test.ts index 3d006696c536..0b438d5ffe1a 100644 --- a/apps/server/src/peer/LinkAppPairing.test.ts +++ b/apps/server/src/peer/LinkAppPairing.test.ts @@ -4,15 +4,22 @@ import { type AuthMcpClientAccess, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + EnvironmentId, + type OrchestratorMcpFailure, OrchestratorMcpLinkAppPairingResult, + ProviderInstanceId, type RuntimeMode, + ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; import { Toolkit } from "effect/ai"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as McpToolAccess from "../mcp/McpToolAccess.ts"; import { linkAppPairing } from "../mcp/toolkits/orchestrator/handlers.ts"; import { LinkAppPairingTool } from "../mcp/toolkits/orchestrator/tools.ts"; @@ -76,3 +83,104 @@ it.effect.each<{ }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + +const caller = ( + client: Partial | undefined, + thread?: McpInvocationContext.McpThreadCaller, +): McpInvocationContext.McpInvocationScope => ({ + environmentId: EnvironmentId.make("environment-box"), + requestNamespace: "caller", + thread, + client: + client === undefined + ? undefined + : { sessionId: "session", label: "Caller", access: "full-access", ...client }, + capabilities: new Set(["orchestration"]), + issuedAt: 0, + linkedEnvironments: true, +}); + +// Discovery offers the tool to links only. The handler must refuse everyone else on its own. +it.effect.each<{ + readonly name: string; + readonly scope: McpInvocationContext.McpInvocationScope; + readonly code: OrchestratorMcpFailure["code"]; +}>([ + { name: "an outside agent", scope: caller({}), code: "capability_denied" }, + { + name: "an agent's thread here", + scope: caller(undefined, { + threadId: ThreadId.make("thread:agent"), + providerSessionId: "provider:agent", + providerInstanceId: ProviderInstanceId.make("codex"), + }), + code: "capability_denied", + }, + { + name: "a link calling for one of its agent threads", + scope: caller({ + linked: true, + senderThread: { + environmentId: EnvironmentId.make("environment-a"), + threadId: ThreadId.make("thread:linked-agent"), + title: "Agent", + }, + }), + code: "capability_denied", + }, + // The link itself gets past both checks, to where this harness has no pairing. + { name: "the link itself", scope: caller({ linked: true }), code: "orchestration_error" }, +])("$name calling t3_link_app_pairing gets $code", ({ scope, code }) => + Effect.gen(function* () { + const built = yield* toolkit; + const { result } = yield* built + .handle("t3_link_app_pairing", {}) + .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)); + expect(result).toMatchObject({ code }); + }).pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer( + McpToolAccess.toLayer( + toolkit, + Effect.map(linkAppPairing, (pairing) => ({ t3_link_app_pairing: pairing })), + ), + ), + ), + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + ), +); + +it.effect("refuses a link's call made for one of its agent threads", () => + Effect.scoped( + Effect.gen(function* () { + const box = descriptorOf("environment-box", "Box", { linkedAppPairing: true }); + const handlers = McpToolAccess.toLayer( + toolkit, + Effect.map(linkAppPairing, (pairing) => ({ t3_link_app_pairing: pairing })), + ); + const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers)); + const context = yield* Layer.build( + layerLinkingEnvironment(descriptorOf("environment-a", "A")), + ); + yield* linkTo(Context.get(context, PeerLinks.PeerLinks), b, "full-access"); + const refused = yield* Context.get(context, PeerMcpClient.PeerMcpClient) + .call({ + environmentId: box.environmentId, + tool: "t3_link_app_pairing", + arguments: {}, + limits: { runtimeMode: "full-access", interactionMode: "default" }, + sender: { + environmentId: EnvironmentId.make("environment-a"), + threadId: ThreadId.make("thread:linked-agent"), + title: "Agent", + }, + success: OrchestratorMcpLinkAppPairingResult, + }) + .pipe(Effect.flip); + expect(refused.code).toBe("capability_denied"); + expect( + (yield* b.auth.listPairingLinks()).some((link) => link.label === "T3 Code · A (app)"), + ).toBe(false); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 6923037b6f7c..3f602b167643 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -3,7 +3,13 @@ import * as NodeFS from "node:fs"; // @effect-diagnostics-next-line nodeBuiltinImport:off - A peer with a certificate this machine does not trust. import * as NodeHttps from "node:https"; import { NodeHttpServer } from "@effect/platform-node"; -import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + EnvironmentId, + type ExecutionEnvironmentDescriptor, + OrchestratorMcpFailure, +} from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -28,6 +34,10 @@ import { } from "effect/http"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as Sqlite from "../persistence/Sqlite.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as McpToolAccess from "../mcp/McpToolAccess.ts"; @@ -913,3 +923,49 @@ it("reads Node's TLS verification code from anywhere in a cause chain", () => { expect(PeerLinks.certificateErrorCode({ cause: { code: "ECONNREFUSED" } })).toBeUndefined(); expect(PeerLinks.certificateErrorCode(new Error("timed out"))).toBeUndefined(); }); + +it.effect("counts a client's app report only while its session is signed in", () => + Effect.gen(function* () { + const layerSessions = SessionStore.layer.pipe( + Layer.provide(Sqlite.layerMemory), + Layer.provide(ServerSecretStore.layer), + Layer.provide( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-a")), + }), + ), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-sessions-" })), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + const context = yield* Layer.build( + layerLinkingEnvironment(descriptorOf("environment-a", "A")).pipe( + Layer.provideMerge(layerSessions), + ), + ); + const links = Context.get(context, PeerLinks.PeerLinks); + const sessions = Context.get(context, SessionStore.SessionStore); + const holds = (id: string) => [ + { + environmentId: EnvironmentId.make(id), + label: id, + urls: [`https://${id}.example.ts.net`], + serverVersion: "0.1.10", + keepsLinkLimits: true, + }, + ]; + const phone = yield* sessions.issue({ subject: "phone" }); + const tablet = yield* sessions.issue({ subject: "tablet", ttl: Duration.hours(1) }); + const laptop = yield* sessions.issue({ subject: "laptop" }); + yield* links.reportAppConnections(phone.sessionId, holds("crown")); + yield* links.reportAppConnections(tablet.sessionId, holds("box")); + yield* links.reportAppConnections(laptop.sessionId, holds("asus")); + const inApp = links.environments.pipe( + Effect.map((known) => known.map((environment) => environment.environmentId)), + ); + expect(yield* inApp).toEqual(["crown", "box", "asus"]); + yield* sessions.revoke(phone.sessionId); + expect(yield* inApp).toEqual(["box", "asus"]); + yield* TestClock.adjust(Duration.hours(1)); + expect(yield* inApp).toEqual(["asus"]); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 100997dafaf0..7a480922b031 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -40,9 +40,10 @@ import * as HttpApiClient from "effect/http-api/HttpApiClient"; import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ServerSettings from "../serverSettings.ts"; -import { knownEnvironments } from "./knownEnvironments.ts"; +import { boundedAppConnectionReport, knownEnvironments } from "./knownEnvironments.ts"; const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier) .add(EnvironmentHttpApi.groups.metadata) @@ -107,7 +108,9 @@ export class PeerLinks extends Context.Service< readonly list: Effect.Effect, PeerLinkError>; /** * Replaces what one client session says its app holds. Kept in memory: a - * client reports again whenever it connects or its connections change. + * client reports again whenever it connects or its connections change. A + * report counts only while its session is active, so a revoked or expired + * session's report drops out. */ readonly reportAppConnections: ( sessionId: string, @@ -667,17 +670,35 @@ const make = Effect.gen(function* () { connections, ) => Ref.update(appReports, (current) => - new Map(current).set(sessionId, connections.slice(0, MAX_REPORTED_CONNECTIONS)), + new Map(current).set( + sessionId, + connections.slice(0, MAX_REPORTED_CONNECTIONS).map(boundedAppConnectionReport), + ), + ); + + // Absent only where no client reports, such as the CLI. + const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); + /** The reports of sessions still signed in: a revoked or expired session's stop counting. */ + const activeReports = Effect.gen(function* () { + const reports = [...(yield* Ref.get(appReports))]; + if (Option.isNone(sessions)) return reports.flatMap(([, connections]) => connections); + const active = new Set( + (yield* sessions.value.listActive().pipe(Effect.catch(failStorage))).map( + (session) => session.sessionId, + ), + ); + return reports.flatMap(([sessionId, connections]) => + active.has(sessionId) ? connections : [], ); + }); const environments: PeerLinks["Service"]["environments"] = Effect.gen(function* () { const self = yield* environment.getDescriptor; const links = yield* list; - const reports = yield* Ref.get(appReports); return knownEnvironments({ self: self.environmentId, links, - reports: [...reports.values()].flat(), + reports: yield* activeReports, }); }); diff --git a/apps/server/src/peer/knownEnvironments.test.ts b/apps/server/src/peer/knownEnvironments.test.ts index 902b5d89662a..c9c68c3c8369 100644 --- a/apps/server/src/peer/knownEnvironments.test.ts +++ b/apps/server/src/peer/knownEnvironments.test.ts @@ -7,7 +7,7 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { knownEnvironments } from "./knownEnvironments.ts"; +import { boundedAppConnectionReport, knownEnvironments } from "./knownEnvironments.ts"; const self = EnvironmentId.make("laptop"); @@ -140,4 +140,17 @@ describe("knownEnvironments", () => { expect(listed[0]?.link?.access).toBe("full-access"); expect(listed[1]?.link).toBeNull(); }); + + it("keeps a client's report to a bounded size", () => { + const urls = Array.from({ length: 40 }, (_, index) => `https://box-${index}.example.ts.net`); + const bounded = boundedAppConnectionReport( + app("box", "B".repeat(5000), { + serverVersion: "9".repeat(5000), + urls: [`https://${"a".repeat(5000)}.example.ts.net`, ...urls], + }), + ); + expect(bounded.label).toHaveLength(200); + expect(bounded.serverVersion).toHaveLength(200); + expect(bounded.urls).toEqual(urls.slice(0, 16)); + }); }); diff --git a/apps/server/src/peer/knownEnvironments.ts b/apps/server/src/peer/knownEnvironments.ts index bd5f396a99ac..caa516291f6b 100644 --- a/apps/server/src/peer/knownEnvironments.ts +++ b/apps/server/src/peer/knownEnvironments.ts @@ -7,6 +7,21 @@ import type { } from "@t3tools/contracts"; import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification"; +const MAX_REPORTED_LABEL = 200; +const MAX_REPORTED_URL = 2048; +const MAX_REPORTED_URLS = 16; + +/** + * A client's report as this server keeps it: label and version cut to size, and only a few + * URLs of a sane length. The client strips their userinfo before sending. + */ +export const boundedAppConnectionReport = (report: AppConnectionReport): AppConnectionReport => ({ + ...report, + label: report.label.slice(0, MAX_REPORTED_LABEL), + serverVersion: report.serverVersion?.slice(0, MAX_REPORTED_LABEL) ?? null, + urls: report.urls.filter((url) => url.length <= MAX_REPORTED_URL).slice(0, MAX_REPORTED_URLS), +}); + const versioned = (label: string, version: string | null) => version === null ? label : `${label} ${version}`; diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index b2e2bfde2328..68f1da1a7c10 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -50,7 +50,7 @@ import { connectSshEnvironment as connectSshEnvironmentAtom, } from "~/connection/onboarding"; import { useEnvironmentQuery } from "~/state/query"; -import { linkOnConnect, usePeerLinkHosts } from "~/state/peerLinks"; +import { forgetLinkOnConnect, linkOnConnect, usePeerLinkHosts } from "~/state/peerLinks"; import { useEnvironmentsWithScope } from "~/state/session"; import { Checkbox } from "../ui/checkbox"; import { LinkAccessPicker } from "./LinkAccessPicker"; @@ -264,12 +264,16 @@ export function AddEnvironmentDialog({ return; } - if (routeTarget === null && linkForAgents) { - linkOnConnect( - result.value, - linkAccess, - linkHosts.map((host) => host.environmentId), - ); + if (routeTarget === null) { + if (linkForAgents && linkHosts.length > 0) { + linkOnConnect( + result.value, + linkAccess, + linkHosts.map((host) => host.environmentId), + ); + } else { + forgetLinkOnConnect(result.value); + } } handleOpenChange(false); toastManager.add( diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index d9d3c343680b..8abc58bea493 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -45,7 +45,12 @@ import { ConnectDeviceApprovalSettings } from "./ConnectDeviceApprovalSettings"; import { EnvironmentIconMenu } from "./EnvironmentIconPicker"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings"; -import { hostsLinking, peerLinkEnvironment, usePeerLinkHosts } from "~/state/peerLinks"; +import { + forgetLinkOnConnect, + hostsLinking, + peerLinkEnvironment, + usePeerLinkHosts, +} from "~/state/peerLinks"; import { LoadBalancingSettings } from "./LoadBalancingSettings"; import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings"; import { Input } from "../ui/input"; @@ -702,6 +707,8 @@ function ConnectionsSettingsContent({ ); return; } + // A link chosen while adding it was for this connection, which is gone. + forgetLinkOnConnect(environmentId); // The way back out of a link: agents there keep it unless the user forgets it too. for (const hostId of linkingHosts) { const host = peerLinkHosts.find((candidate) => candidate.environmentId === hostId); diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 09db15dd4e8e..209a4a5e1e6e 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { ANOTHER_ADDRESS, + appPairingAddresses, type KnownEnvironmentRow, linkRequestFailureMessage, } from "@t3tools/client-runtime/link-request"; @@ -26,7 +27,7 @@ import { mintPairingCodeOn } from "~/state/peerPairingCode"; import { environmentCatalog } from "~/connection/catalog"; import { connectPairing as connectPairingAtom } from "~/connection/onboarding"; import { useKnownEnvironments } from "~/state/knownEnvironments"; -import { peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks"; +import { forgetLinkOnConnect, peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks"; import { useEnvironmentScope, usePreparedConnection } from "~/state/session"; import { useAtomCommand } from "~/state/use-atom-command"; import { accessConfig } from "../auth/ConnectAgentSurface"; @@ -182,7 +183,7 @@ function LinkedEnvironmentRow({ const [busy, setBusy] = useState(false); const forget = async () => { const confirmed = await (requestConfirmDialog( - `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Sharing & access to end the session there too.`, + `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Sharing & access to end the session there too. An app added through this link stays under Authorized clients there until you revoke it.`, { variant: "destructive" }, ) ?? Promise.resolve(false)); if (!confirmed) return; @@ -198,30 +199,46 @@ function LinkedEnvironmentRow({ // The way back out: the app's own connection stays unless the user removes it too. if (!row.inThisApp) return; const alsoRemove = await (requestConfirmDialog( - `Also remove ${row.label} from this app? Its threads stay there; this app forgets its pairing.`, + `Also remove ${row.label} from this app? Its threads stay there; this app forgets its pairing. ${row.label} still lists this app under Authorized clients, where you can revoke it.`, { variant: "destructive" }, ) ?? Promise.resolve(false)); if (!alsoRemove) return; const removed = await removeFromApp(link.environmentId); - if (removed._tag === "Failure" && !isAtomCommandInterrupted(removed)) { + if (removed._tag === "Success") forgetLinkOnConnect(link.environmentId); + else if (!isAtomCommandInterrupted(removed)) { failureToast(`Could not remove ${row.label}`, String(squashAtomCommandFailure(removed))); } }; + const connectAt = async (hosts: ReadonlyArray, pairingCode: string) => { + // A host that does not answer as this machine never receives the code, so the next can. + let result: Awaited> | undefined; + for (const host of hosts) { + result = await connectPairing({ + host, + pairingCode, + expectedEnvironmentId: link.environmentId, + }); + if (result._tag === "Success" || isAtomCommandInterrupted(result)) return result; + } + return result; + }; const add = async () => { - // The link's own address, which this client reaches: see `appPairingAddress`. - const host = row.appAddress; - if (host === null) return; + if (row.appAddress === null) return; setBusy(true); const issued = await addToApp({ environmentId, input: { environmentId: link.environmentId } }); + // Where the peer just answered first, then its other addresses this client reaches. + const hosts = + issued._tag === "Success" ? appPairingAddresses(issued.value.urls, row.onHostMachine) : []; const added = - issued._tag === "Success" - ? await connectPairing({ - host, - pairingCode: issued.value.credential, - expectedEnvironmentId: link.environmentId, - }) - : issued; + issued._tag === "Success" ? await connectAt(hosts, issued.value.credential) : issued; setBusy(false); + if (added === undefined) { + failureToast( + `Could not add ${link.label} to this app`, + `${link.label} answers only at addresses this device cannot open.`, + ); + return; + } if (added._tag === "Failure") { if (!isAtomCommandInterrupted(added)) { failureToast( diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts index ca5639958fc7..01d751fd5a7c 100644 --- a/apps/web/src/state/peerLinks.ts +++ b/apps/web/src/state/peerLinks.ts @@ -197,7 +197,7 @@ export function linkOnConnect( hosts: ReadonlyArray, ) { const hostsElsewhere = hosts.filter((host) => host !== environmentId); - if (hostsElsewhere.length === 0) return; + if (hostsElsewhere.length === 0) return forgetLinkOnConnect(environmentId); appAtomRegistry.set( pendingLinksAtom, new Map(appAtomRegistry.get(pendingLinksAtom)).set(environmentId, { @@ -207,6 +207,18 @@ export function linkOnConnect( ); } +/** + * Drops a `linkOnConnect` choice that has not run yet. Call it when the environment is + * removed, or added again without the link, so an old choice never links it later. + */ +export function forgetLinkOnConnect(environmentId: EnvironmentId) { + const pending = appAtomRegistry.get(pendingLinksAtom); + if (!pending.has(environmentId)) return; + const remaining = new Map(pending); + remaining.delete(environmentId); + appAtomRegistry.set(pendingLinksAtom, remaining); +} + /** Carries out `linkOnConnect` choices as their connections come up. */ export function LinkOnConnectCoordinator() { const pending = useAtomValue(pendingLinksAtom); diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index f6e7c124d3cd..7b50bcea3356 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -400,7 +400,8 @@ link's access: a full-access link adds a full client, anything less adds a read-only one, and that machine lists it under **Sharing & access**. An environment too old for either shows **Update it**. Removing an environment offers to forget its link too, and forgetting a link offers to remove the -environment from the app. +environment from the app. Neither ends the app's access on the other machine: +it still lists this app under **Authorized clients** until you revoke it there. An agent can also hand a task to a linked machine with `delegate_task`: it runs there as an ordinary thread, in the project with the same repository (or the diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts index 0fe4daffe4ea..3a8cf012d1a1 100644 --- a/packages/client-runtime/src/linkRequest.test.ts +++ b/packages/client-runtime/src/linkRequest.test.ts @@ -18,6 +18,7 @@ import { ANOTHER_ADDRESS, appConnectionReports, appPairingAddress, + appPairingAddresses, knownEnvironmentRows, linkableMachines, linkedEnvironmentNames, @@ -366,7 +367,8 @@ describe("appConnectionReports", () => { {}, ); const vps = configured( - presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] }), + // A user:pass@ in a saved address is a credential and is never reported. + presentation("environment-vps", "VPS", { saved: ["https://me:secret@vps.ts.net"] }), "0.1.10", { mcpModeLimitHeader: true, linkFence: true }, ); @@ -403,6 +405,7 @@ describe("knownEnvironmentRows", () => { id: string, action: "link" | "add-to-app" | null, linked: boolean, + inApp = !linked, ): KnownEnvironment => ({ environmentId: EnvironmentId.make(id), label: id, @@ -419,9 +422,10 @@ describe("knownEnvironmentRows", () => { lastReachedAt: null, lastError: null, status: "reachable", + appPairing: true, } : null, - inApp: !linked, + inApp, issue: action === null ? null : { action, message: `${id}: ${action}` }, }); @@ -432,6 +436,8 @@ describe("knownEnvironmentRows", () => { known("r720", "add-to-app", true), known("box", "link", false), known("crown", "link", false), + // Another session's app holds it, so the server's merged view has no issue. + known("mini", null, true, true), ], [ presentation("r720", "R720", { connected: false }), @@ -456,6 +462,8 @@ describe("knownEnvironmentRows", () => { ["box", "link", "link", true, "reachable", null], // Only a connected app can mint the code a link needs; the issue still shows. ["crown", null, "link", false, "unknown", null], + // Another device holding it says nothing about this one, which can still add it. + ["mini", "add-to-app", "add-to-app", false, "reachable", "read-only"], ]); }); @@ -485,6 +493,10 @@ describe("knownEnvironmentRows", () => { expect( appPairingAddress(["http://127.0.0.1:13780", "https://asus.example.ts.net"], false), ).toBe("https://asus.example.ts.net"); + // Adding tries each address the peer just answered at, in order, that this client can open. + const answered = ["https://asus.example.ts.net", "http://127.0.0.1:13780"]; + expect(appPairingAddresses(answered, true)).toEqual(answered); + expect(appPairingAddresses(answered, false)).toEqual(["https://asus.example.ts.net"]); }); }); diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts index 4eeb4840716d..b0a94495b950 100644 --- a/packages/client-runtime/src/linkRequest.ts +++ b/packages/client-runtime/src/linkRequest.ts @@ -100,17 +100,29 @@ const isLoopbackUrl = (url: string) => { return hostname !== undefined && isLocalLoopbackHost(hostname); }; +/** `url` without a `user:pass@` in it, which is a credential and never leaves this client. */ +const withoutUserinfo = (url: string) => { + const parsed = parsedUrl(url); + if (parsed === undefined || (parsed.username === "" && parsed.password === "")) return url; + return `${parsed.protocol}//${parsed.host}${parsed.pathname === "/" ? "" : parsed.pathname}`; +}; + /** Where another machine can reach a saved environment: what it reports, its routes, then Connect. */ const clientUrls = (environment: EnvironmentPresentation, connectUrl: string | undefined) => [ - ...new Set([ - ...(environment.serverConfig?.directEndpoints ?? []).map((endpoint) => endpoint.httpBaseUrl), - ...connectionRoutes(environment.entry).flatMap((route) => { - const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route); - return url === null ? [] : [url]; - }), - ...(connectUrl === undefined ? [] : [connectUrl]), - ]), + ...new Set( + [ + ...(environment.serverConfig?.directEndpoints ?? []).map( + (endpoint) => endpoint.httpBaseUrl, + ), + ...connectionRoutes(environment.entry).flatMap((route) => { + const url = + route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route); + return url === null ? [] : [url]; + }), + ...(connectUrl === undefined ? [] : [connectUrl]), + ].map(withoutUserinfo), + ), ].filter((url) => !isLoopbackUrl(url)); /** @@ -149,10 +161,16 @@ export const reachesOverLoopback = (host: Pick * Where this client can add a linked machine: the link's own address, in its order. A * loopback one names the host's machine, so it counts only when this client is on it. */ +export const appPairingAddresses = ( + urls: ReadonlyArray, + onHostMachine: boolean, +): ReadonlyArray => urls.filter((url) => onHostMachine || !isLoopbackUrl(url)); + +/** The first of `appPairingAddresses`, or null when this client reaches none. */ export const appPairingAddress = ( urls: ReadonlyArray, onHostMachine: boolean, -): string | null => urls.find((url) => onHostMachine || !isLoopbackUrl(url)) ?? null; +): string | null => appPairingAddresses(urls, onHostMachine)[0] ?? null; /** An environment the app's server knows, with what this client can see and do about it. */ export interface KnownEnvironmentRow extends KnownEnvironment { @@ -162,10 +180,15 @@ export interface KnownEnvironmentRow extends KnownEnvironment { readonly inThisApp: boolean; readonly reachability: "reachable" | "unreachable" | "expired" | "unknown"; readonly linkAccess: AuthMcpClientAccess | null; - /** The issue's action, when this client can take it: only the app holding a machine links it. */ + /** + * The issue's action, when this client can take it: only the app holding a machine links it, + * and only an app without it adds it. + */ readonly action: KnownEnvironmentAction | null; /** Where this client would add the linked machine, or null when it reaches none of its addresses. */ readonly appAddress: string | null; + /** This client reaches the server at its own loopback, for `appPairingAddresses`. */ + readonly onHostMachine: boolean; } /** @@ -183,15 +206,30 @@ export function knownEnvironmentRows( return known.map((environment) => { const here = held.get(environment.environmentId); const connected = here?.connection.phase === "connected"; - const wanted = environment.issue?.action ?? null; - const appAddress = - environment.link === null + const { link } = environment; + const appAddress = link === null ? null : appPairingAddress(link.urls, host.onHostMachine); + // Adding is this client's own question: whether another device holds the machine, as the + // server's merged reports say, does not tell whether this one does. + const addable = + link !== null && + link.status === "reachable" && + link.appPairing === true && + here === undefined; + const issue: KnownEnvironment["issue"] = addable + ? { + action: "add-to-app", + message: + appAddress === null + ? `${host.label} reaches ${environment.label} only at its own local address, which this device cannot open. Add it from the app on ${host.label}.` + : `${environment.label} is linked for agents but not in the app.`, + } + : environment.issue?.action === "add-to-app" ? null - : appPairingAddress(environment.link.urls, host.onHostMachine); - const unreachableHere = wanted === "add-to-app" && here === undefined && appAddress === null; + : environment.issue; + const wanted = issue?.action ?? null; const action = wanted === "add-to-app" - ? here === undefined && appAddress !== null + ? appAddress !== null ? wanted : null : wanted === "link" @@ -201,17 +239,9 @@ export function knownEnvironmentRows( : wanted; return { ...environment, - // This app's own view wins over a report that has not arrived yet. - issue: - wanted === "add-to-app" && here !== undefined - ? null - : unreachableHere - ? { - action: "add-to-app", - message: `${host.label} reaches ${environment.label} only at its own local address, which this device cannot open. Add it from the app on ${host.label}.`, - } - : environment.issue, + issue, appAddress, + onHostMachine: host.onHostMachine, connected, inThisApp: here !== undefined, reachability: environment.link?.status ?? (connected ? "reachable" : "unknown"), From cd0cb5f5989b901055642a8fdef3c96afeee5f97 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:12 +0000 Subject: [PATCH 3/3] fix: links change no text agents see t3_environment_links returns what it did on release/native-0.1.10 again: the inAppOnly field and its description are gone from the result and its contract. Settings still reads app-only machines over the client RPC. t3_link_app_pairing is offered only to another environment's link (onlyForLinks); agent sessions have no client caller, so they never list it. The tool-list budget now leaves out link-only tools and is back at base's numbers. Model: claude-opus-5-5 Task: fix Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- apps/server/src/peer/PeerForwarding.ts | 38 +++++-------------- apps/server/src/peer/PeerLinks.ts | 2 +- .../src/provider/AgentContextBudget.test.ts | 20 +++++++--- .../src/provider/agentContextBudget.json | 2 +- packages/contracts/src/orchestratorMcp.ts | 14 ------- 5 files changed, 25 insertions(+), 51 deletions(-) diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index d549ab7b0aa8..5ad397558de1 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -348,37 +348,17 @@ const make = Effect.gen(function* () { function* (scope) { yield* forwardingCaller(scope); yield* requireEnabled; - // The same list Settings shows, so agents and the app never disagree on what exists. - const known = yield* links.environments.pipe(Effect.mapError(linkStorageFailure)); - const inAppOnly = known.flatMap((environment) => - environment.link === null && environment.issue !== null - ? [ - { - environmentId: environment.environmentId, - label: environment.label, - serverVersion: environment.serverVersion, - why: environment.issue.message, - }, - ] - : [], - ); + const listed = yield* links.list.pipe(Effect.mapError(linkStorageFailure)); return { environmentId: scope.environmentId, - links: known.flatMap(({ link }) => - link === null - ? [] - : [ - { - environmentId: link.environmentId, - label: link.label, - status: link.status, - access: link.access, - expiresAt: DateTime.formatIso(link.expiresAt), - lastError: link.lastError, - }, - ], - ), - ...(inAppOnly.length === 0 ? {} : { inAppOnly }), + links: listed.map((link) => ({ + environmentId: link.environmentId, + label: link.label, + status: link.status, + access: link.access, + expiresAt: DateTime.formatIso(link.expiresAt), + lastError: link.lastError, + })), notListed: NOT_LISTED, }; }, diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 7a480922b031..88ee16cf827f 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -118,7 +118,7 @@ export class PeerLinks extends Context.Service< ) => Effect.Effect; /** * Every environment this one knows, links and app connections in one list, - * each saying why it is on one side only. Settings and agents both read it. + * each saying why it is on one side only. Settings reads it over client RPC; agents never see it. */ readonly environments: Effect.Effect, PeerLinkError>; /** diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 2a7d02fc2817..ae5c4bc635a4 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -5,7 +5,8 @@ import { ProviderInstanceId } from "@t3tools/contracts"; import { McpProviderSessions } from "@t3tools/provider-core/server/McpProviderSessions"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { McpServer } from "effect/ai"; +import * as Context from "effect/Context"; +import { McpSchema, McpServer } from "effect/ai"; import { AssetSigner } from "../assets/AssetSigner.ts"; import { ServerSecretStore } from "../auth/ServerSecretStore.ts"; @@ -14,6 +15,7 @@ import { DeviceService } from "../device/DeviceService.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import { onlyForLinks } from "../mcp/McpInvocationContext.ts"; import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; import { CLAUDE_PROVIDER, @@ -140,13 +142,19 @@ it.effect("agent context matches the committed budget", () => claudeSystemAppendBytes: utf8Bytes(claudeSystemAppend()), codexAdditionalContextBytes: utf8Bytes(codexAdditionalContext()), // The model sees these fields. outputSchema and annotations are protocol metadata. + // Tools only another environment's link can list never reach a model. mcpToolListJsonBytes: utf8Bytes( JSON.stringify( - mcp.tools.map(({ tool }) => ({ - name: tool.name, - description: tool.description, - inputSchema: tool.inputSchema, - })), + mcp.tools + .filter( + ({ annotations }) => + Context.getOrUndefined(annotations, McpSchema.EnabledWhen) !== onlyForLinks, + ) + .map(({ tool }) => ({ + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + })), ), ), }; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index b1c8a7898fa9..ab49f2b6c830 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 52881 + "mcpToolListJsonBytes": 52637 } diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index aaad940f90da..afdd5d08455a 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -699,20 +699,6 @@ export type OrchestratorMcpEnvironmentLink = typeof OrchestratorMcpEnvironmentLi export const OrchestratorMcpEnvironmentLinksResult = Schema.Struct({ environmentId: EnvironmentId, links: Schema.Array(OrchestratorMcpEnvironmentLink), - /** Machines the user's app holds that are not linked here, so no tool can act there yet. */ - inAppOnly: Schema.optionalKey( - Schema.Array( - Schema.Struct({ - environmentId: EnvironmentId, - label: Schema.String, - serverVersion: Schema.NullOr(Schema.String), - why: Schema.String.annotate({ - description: - "Why it is not linked and what fixes it. Tell the user; linking still needs their approval.", - }), - }), - ), - ), /** What to do when the machine the user means is not among `links`. */ notListed: Schema.String, });