From 7b23515f196ae6a7cfa6e4deae9a5403fd182134 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:30:25 +0000 Subject: [PATCH 1/2] feat: apps add linked environments automatically A machine a connected server links, but this app lacks, is added without a click once its link is reachable, at no more than the link's access. A failed add waits for the link's status, addresses or session to change, so a down peer never burns single-use codes. Removing a linked machine from the app keeps it out until the user chooses Add to this app. Model: claude-opus-5-5 Task: feature Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/state/peerLinks.ts | 1 + .../settings/ConnectionsSettings.tsx | 3 + .../settings/LinkedEnvironmentsSettings.tsx | 60 +++----- apps/web/src/routes/__root.tsx | 2 + apps/web/src/state/knownEnvironments.ts | 39 ------ apps/web/src/state/knownEnvironments.tsx | 129 ++++++++++++++++++ apps/web/src/state/peerLinks.ts | 87 +++++++++++- docs/user/remote-access.md | 6 +- .../client-runtime/src/linkRequest.test.ts | 120 ++++++++++++++++ packages/client-runtime/src/linkRequest.ts | 64 +++++++++ packages/contracts/src/settings.ts | 6 + 11 files changed, 436 insertions(+), 81 deletions(-) delete mode 100644 apps/web/src/state/knownEnvironments.ts create mode 100644 apps/web/src/state/knownEnvironments.tsx diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts index baed9be90412..f44558c66b12 100644 --- a/apps/mobile/src/state/peerLinks.ts +++ b/apps/mobile/src/state/peerLinks.ts @@ -14,6 +14,7 @@ import { relayEnvironmentDiscovery } from "./relay"; import { useEnvironmentQuery } from "./query"; import { useAtomCommand } from "./use-atom-command"; +// Web adds linked machines on its own (`linkedEnvironmentsToAutoAdd`); mobile does not yet. export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime); /** diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 8abc58bea493..81f3b9ca68b9 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -46,6 +46,7 @@ import { EnvironmentIconMenu } from "./EnvironmentIconPicker"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings"; import { + dismissLinkedEnvironment, forgetLinkOnConnect, hostsLinking, peerLinkEnvironment, @@ -691,6 +692,8 @@ function ConnectionsSettingsContent({ setSavedBackendError(null); // Read before removing: the lists are this app's, and removal changes what it reports. const linkingHosts = hostsLinking(peerLinkHosts, environmentId); + // A host still linking it would add it straight back. Recorded first, so it never does. + if (linkingHosts.length > 0) void dismissLinkedEnvironment(environmentId); const result = await removeEnvironment(environmentId); setRemovingSavedEnvironmentId(null); if (result._tag === "Failure") { diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 209a4a5e1e6e..6de53364eca1 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -1,7 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import { ANOTHER_ADDRESS, - appPairingAddresses, type KnownEnvironmentRow, linkRequestFailureMessage, } from "@t3tools/client-runtime/link-request"; @@ -25,9 +24,15 @@ import { useId, useRef, useState } from "react"; import { requestConfirmDialog } from "~/confirmDialog"; import { mintPairingCodeOn } from "~/state/peerPairingCode"; import { environmentCatalog } from "~/connection/catalog"; -import { connectPairing as connectPairingAtom } from "~/connection/onboarding"; import { useKnownEnvironments } from "~/state/knownEnvironments"; -import { forgetLinkOnConnect, peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks"; +import { + addLinkedEnvironmentToApp, + dismissLinkedEnvironment, + forgetLinkOnConnect, + peerLinkEnvironment, + undismissLinkedEnvironment, + useLinkableMachines, +} from "~/state/peerLinks"; import { useEnvironmentScope, usePreparedConnection } from "~/state/session"; import { useAtomCommand } from "~/state/use-atom-command"; import { accessConfig } from "../auth/ConnectAgentSurface"; @@ -176,9 +181,7 @@ function LinkedEnvironmentRow({ const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute)); const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: "unlink environment" }); const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId)); - const addToApp = useAtomCommand(peerLinkEnvironment.addToApp, { reportFailure: false }); const canAddToApp = useAtomValue(peerLinkEnvironment.addToApp.permissionAtom(environmentId)); - const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false }); const removeFromApp = useAtomCommand(environmentCatalog.remove, { reportFailure: false }); const [busy, setBusy] = useState(false); const forget = async () => { @@ -203,55 +206,34 @@ function LinkedEnvironmentRow({ { variant: "destructive" }, ) ?? Promise.resolve(false)); if (!alsoRemove) return; + // Another host may still link it. Recorded first, so it is never added back on its own. + void dismissLinkedEnvironment(link.environmentId); const removed = await removeFromApp(link.environmentId); 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 () => { 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 connectAt(hosts, issued.value.credential) : issued; + const added = await addLinkedEnvironmentToApp(environmentId, { + environmentId: link.environmentId, + label: link.label, + onHostMachine: row.onHostMachine, + }); 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( - `Could not add ${link.label} to this app`, - String(squashAtomCommandFailure(added)), - ); - } + if (added._tag === "Interrupted") return; + if (added._tag === "Failed") { + failureToast(`Could not add ${link.label} to this app`, added.message); return; } + // Choosing it again is the way back from removing it, so a later removal starts fresh. + void undismissLinkedEnvironment(link.environmentId); toastManager.add({ type: "success", title: `Added ${link.label} to this app`, - ...(issued._tag === "Success" && issued.value.access === "read-only" + ...(added.access === "read-only" ? { description: "Read-only: the link allows no more. Link it with full access to act there.", diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index be65b66483ae..da499d623f6e 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -61,6 +61,7 @@ import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; import { AppConnectionReporter, LinkOnConnectCoordinator } from "../state/peerLinks"; +import { AutoAddLinkedEnvironments } from "../state/knownEnvironments"; export const Route = createRootRoute({ beforeLoad: async ({ location }) => { @@ -197,6 +198,7 @@ function RootRouteBranch() { + {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} diff --git a/apps/web/src/state/knownEnvironments.ts b/apps/web/src/state/knownEnvironments.ts deleted file mode 100644 index a06c493cca11..000000000000 --- a/apps/web/src/state/knownEnvironments.ts +++ /dev/null @@ -1,39 +0,0 @@ -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/knownEnvironments.tsx b/apps/web/src/state/knownEnvironments.tsx new file mode 100644 index 000000000000..703a30c25826 --- /dev/null +++ b/apps/web/src/state/knownEnvironments.tsx @@ -0,0 +1,129 @@ +import { + autoAddLinkState, + knownEnvironmentRows, + type KnownEnvironmentRow, + linkedEnvironmentsToAutoAdd, + reachesOverLoopback, +} from "@t3tools/client-runtime/link-request"; +import { AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts"; +import { useEffect, useEffectEvent } from "react"; + +import { toastManager } from "../components/ui/toast"; +import { useClientSettings, useClientSettingsHydrated } from "../hooks/useSettings"; +import { useEnvironments } from "./environments"; +import { addLinkedEnvironmentToApp, peerLinkEnvironment, usePeerLinkHosts } from "./peerLinks"; +import { useEnvironmentQuery } from "./query"; +import { useEnvironmentsWithScope } from "./session"; + +/** + * 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, + }; +} + +// Shared by every host, so two hosts linking one machine add it once. +const autoAdding = new Set(); +// The link state each (host, machine) add last failed at. Each try spends a single-use code. +const autoAddFailures = new Map(); + +/** + * Adds the machines connected hosts link, but this app lacks, without a click. Runs when a + * host's list changes, which includes its reconnecting, and never on a timer. + */ +export function AutoAddLinkedEnvironments() { + const hosts = usePeerLinkHosts(); + // Adding mints a pairing link on the host's behalf, which needs write access there. + const writable = useEnvironmentsWithScope(hosts, AuthAccessWriteScope); + return hosts + .filter((host) => writable.has(host.environmentId)) + .map((host) => ( + + )); +} + +function AutoAddFromHost({ + hostId, + hostLabel, +}: { + readonly hostId: EnvironmentId; + readonly hostLabel: string; +}) { + const known = useKnownEnvironments(hostId); + const { environments, isReady } = useEnvironments(); + // Until both load, a held or dismissed machine would look addable. + const settingsReady = useClientSettingsHydrated(); + const dismissed = useClientSettings((settings) => settings.dismissedLinkedEnvironmentIds); + const ready = isReady && settingsReady && !known.loading; + const run = useEffectEvent((_snapshot: string) => { + if (!ready) return; + const { add, forget } = linkedEnvironmentsToAutoAdd({ + hostId, + rows: known.rows, + catalog: new Set(environments.map((environment) => environment.environmentId)), + dismissed: new Set(dismissed), + adding: autoAdding, + failed: autoAddFailures, + }); + for (const key of forget) autoAddFailures.delete(key); + for (const { row, key, linkState } of add) { + autoAdding.add(row.environmentId); + void addLinkedEnvironmentToApp(hostId, row).then((outcome) => { + autoAdding.delete(row.environmentId); + if (outcome._tag !== "Added") { + // It stays offered under Linked environments, where the user can add it by hand. + autoAddFailures.set(key, linkState); + return; + } + autoAddFailures.delete(key); + toastManager.add({ + type: "success", + title: `${row.label} added from ${hostLabel}'s links`, + ...(outcome.access === "read-only" + ? { description: "Read-only: the link allows no more." } + : {}), + }); + }); + } + }); + const snapshot = JSON.stringify([ + ready, + dismissed, + environments.map((environment) => environment.environmentId), + known.rows.map((row) => [ + row.environmentId, + row.action, + row.appAddress, + row.link === null ? null : autoAddLinkState(row.link), + ]), + ]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- adds machines this host links, outside React, when its list, the catalog or the dismissals change + useEffect(() => run(snapshot), [snapshot]); + return null; +} diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts index 01d751fd5a7c..99cef6895649 100644 --- a/apps/web/src/state/peerLinks.ts +++ b/apps/web/src/state/peerLinks.ts @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { appConnectionReports, + appPairingAddresses, linkableMachines, linkedEnvironmentNames, linkRequestFailureMessage, @@ -12,12 +13,23 @@ import { AuthAccessWriteScope, type AuthMcpClientAccess, type EnvironmentId, + type PeerLinkAppAccess, } from "@t3tools/contracts"; -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { AsyncResult, Atom } from "effect/reactivity"; import { useEffect, useEffectEvent } from "react"; +import { connectPairing } from "../connection/onboarding"; import { connectionAtomRuntime } from "../connection/runtime"; +import { + ensureClientSettingsHydrated, + getClientSettings, + isClientSettingsHydrated, + persistClientSettingsPatch, +} from "../hooks/useSettings"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { stackedThreadToast, toastManager } from "../components/ui/toast"; import { mintPairingCodeOn } from "./peerPairingCode"; @@ -182,6 +194,79 @@ export async function linkFromThisApp( return linked._tag === "Success" ? null : String(squashAtomCommandFailure(linked)); } +export type AddToAppOutcome = + | { readonly _tag: "Added"; readonly access: PeerLinkAppAccess } + | { readonly _tag: "Failed"; readonly message: string } + | { readonly _tag: "Interrupted" }; + +/** + * Adds a machine `hostId` links to this app: the peer mints a single-use code over the link, + * capped at the link's access, and this client pairs with it at the addresses it reaches. + * "Add to this app" and the automatic add both run this. + */ +export async function addLinkedEnvironmentToApp( + hostId: EnvironmentId, + machine: { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly onHostMachine: boolean; + }, +): Promise { + const issued = await peerLinkEnvironment.addToApp.run(appAtomRegistry, { + environmentId: hostId, + input: { environmentId: machine.environmentId }, + }); + if (issued._tag === "Failure") { + return isAtomCommandInterrupted(issued) + ? { _tag: "Interrupted" } + : { _tag: "Failed", message: String(squashAtomCommandFailure(issued)) }; + } + // Where the peer just answered first, then its other addresses this client reaches. One that + // does not answer as this machine never receives the code, so the next can. + let failure: string | null = null; + for (const host of appPairingAddresses(issued.value.urls, machine.onHostMachine)) { + const result = await connectPairing.run(appAtomRegistry, { + host, + pairingCode: issued.value.credential, + expectedEnvironmentId: machine.environmentId, + }); + if (result._tag === "Success") return { _tag: "Added", access: issued.value.access }; + if (isAtomCommandInterrupted(result)) return { _tag: "Interrupted" }; + failure = String(squashAtomCommandFailure(result)); + } + return { + _tag: "Failed", + message: failure ?? `${machine.label} answers only at addresses this device cannot open.`, + }; +} + +// A patch shows in the settings snapshot at once, before it is stored, so the automatic add +// never sees a removed machine as missing and not dismissed. +const setDismissed = async (environmentId: EnvironmentId, dismissed: boolean) => { + if (!isClientSettingsHydrated()) { + await ensureClientSettingsHydrated().catch(() => undefined); + } + const others = getClientSettings().dismissedLinkedEnvironmentIds.filter( + (id) => id !== environmentId, + ); + return persistClientSettingsPatch({ + dismissedLinkedEnvironmentIds: dismissed ? [...others, environmentId] : others, + }); +}; + +/** + * Keeps a linked machine the user removes from this app out of it: it is no longer added on + * its own. Call it before removing. Unlinking leaves it in place; only adding by hand clears it. + */ +export function dismissLinkedEnvironment(environmentId: EnvironmentId): Promise { + return setDismissed(environmentId, true); +} + +/** Lets a linked machine be added on its own again: the user chose Add to this app. */ +export function undismissLinkedEnvironment(environmentId: EnvironmentId): Promise { + return setDismissed(environmentId, false); +} + /** Links the user chose while adding a connection, kept until that connection connects. */ const pendingLinksAtom = Atom.make< ReadonlyMap< diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 7b50bcea3356..4d02bbafeb7a 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -397,8 +397,10 @@ reasons. When you add an environment in **Settings → Environments**, leave **A 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 +read-only one, and that machine lists it under **Sharing & access**. In the +desktop and web app, linked machines appear in your app on their own, at no more +than the link's access, once their link is reachable. Removing one keeps it out +until you choose **Add to this app**. 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. Neither ends the app's access on the other machine: it still lists this app under **Authorized clients** until you revoke it there. diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts index 3a8cf012d1a1..ce36afa5e5da 100644 --- a/packages/client-runtime/src/linkRequest.test.ts +++ b/packages/client-runtime/src/linkRequest.test.ts @@ -19,9 +19,12 @@ import { appConnectionReports, appPairingAddress, appPairingAddresses, + autoAddKey, + autoAddLinkState, knownEnvironmentRows, linkableMachines, linkedEnvironmentNames, + linkedEnvironmentsToAutoAdd, linkRequestAnswerInput, linkRequestDisplay, linkRequestFailureMessage, @@ -500,6 +503,123 @@ describe("knownEnvironmentRows", () => { }); }); +describe("linkedEnvironmentsToAutoAdd", () => { + const hostId = EnvironmentId.make("host"); + const asus = EnvironmentId.make("asus"); + type Link = NonNullable; + const linkOf = (overrides: Partial = {}): Link => ({ + environmentId: asus, + label: "asus", + urls: ["https://asus.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, + ...overrides, + }); + // Rows as this client sees them, from the host's list and this client's catalog. + const rowsFor = (link: Link, held: ReadonlyArray = []) => + knownEnvironmentRows( + [ + { + environmentId: asus, + label: "asus", + urls: [], + serverVersion: null, + link, + inApp: false, + issue: { action: "add-to-app", message: "asus is linked for agents but not in the app." }, + }, + ], + held.map((environmentId) => ({ + environmentId, + connection: { phase: "connected" } as EnvironmentPresentation["connection"], + })), + { label: "host", onHostMachine: false }, + ); + const select = ( + options: { + readonly link?: Link; + readonly held?: ReadonlyArray; + readonly dismissed?: ReadonlyArray; + readonly adding?: ReadonlyArray; + readonly failed?: ReadonlyMap; + } = {}, + ) => + linkedEnvironmentsToAutoAdd({ + hostId, + rows: rowsFor(options.link ?? linkOf(), options.held), + catalog: new Set(options.held ?? []), + dismissed: new Set(options.dismissed ?? []), + adding: new Set(options.adding ?? []), + failed: options.failed ?? new Map(), + }).add.map((add) => add.row.environmentId); + + it("adds a reachable linked machine this app lacks and the user did not dismiss", () => { + expect(select()).toEqual([asus]); + }); + + it("adds through a read-only link too, which caps what the app gets", () => { + expect(select({ link: linkOf({ access: "read-only" }) })).toEqual([asus]); + }); + + it("leaves a dismissed machine for the user to add", () => { + expect(select({ dismissed: [asus] })).toEqual([]); + }); + + it("skips a machine the catalog already holds", () => { + expect(select({ held: [asus] })).toEqual([]); + }); + + it("waits for a link that is unreachable, cannot pair, or only at an address this device cannot open", () => { + expect(select({ link: linkOf({ status: "unreachable" }) })).toEqual([]); + expect(select({ link: linkOf({ appPairing: false }) })).toEqual([]); + expect(select({ link: linkOf({ urls: ["http://127.0.0.1:3773"] }) })).toEqual([]); + }); + + it("starts no second add while one is in flight", () => { + expect(select({ adding: [asus] })).toEqual([]); + }); + + it("retries a failed add only once the link's status, addresses or session change", () => { + const failedAt = linkOf(); + const failed = new Map([[autoAddKey(hostId, asus), autoAddLinkState(failedAt)]]); + expect(select({ failed })).toEqual([]); + // Only the last answer moved, so a down peer is not asked again. + expect( + select({ + failed, + link: linkOf({ lastReachedAt: DateTime.makeUnsafe("2026-11-02T00:00:00Z") }), + }), + ).toEqual([]); + expect(select({ failed, link: linkOf({ urls: ["https://asus.tail.ts.net"] }) })).toEqual([ + asus, + ]); + expect( + select({ failed, link: linkOf({ linkedAt: DateTime.makeUnsafe("2026-11-05T00:00:00Z") }) }), + ).toEqual([asus]); + }); + + it("tries again after a failed peer goes down and comes back", () => { + const key = autoAddKey(hostId, asus); + const failed = new Map([[key, autoAddLinkState(linkOf())]]); + const whileDown = linkedEnvironmentsToAutoAdd({ + hostId, + rows: rowsFor(linkOf({ status: "unreachable" })), + catalog: new Set(), + dismissed: new Set(), + adding: new Set(), + failed, + }); + expect(whileDown).toEqual({ add: [], forget: [key] }); + failed.delete(key); + expect(select({ failed })).toEqual([asus]); + }); +}); + 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 b0a94495b950..6b45de71b29f 100644 --- a/packages/client-runtime/src/linkRequest.ts +++ b/packages/client-runtime/src/linkRequest.ts @@ -12,6 +12,7 @@ import { type ServerConfig, } from "@t3tools/contracts"; import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification"; +import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import type { EnvironmentPresentation } from "./connection/presentation.ts"; @@ -251,6 +252,69 @@ export function knownEnvironmentRows( }); } +/** Names one automatic add: `environmentId` added from `hostId`'s links. */ +export const autoAddKey = (hostId: EnvironmentId, environmentId: EnvironmentId): string => + JSON.stringify([hostId, environmentId]); + +/** + * What must change before a failed automatic add runs again: the link's status, addresses or + * session. Each try spends a single-use code on the peer, so a down peer is not retried. + */ +export const autoAddLinkState = ( + link: Pick, +): string => JSON.stringify([link.status, link.urls, DateTime.toEpochMillis(link.linkedAt)]); + +/** A linked environment this client adds on its own, with what a failure is remembered by. */ +export interface LinkedEnvironmentAutoAdd { + readonly row: KnownEnvironmentRow; + readonly key: string; + readonly linkState: string; +} + +/** + * What to add to this app now from `hostId`'s rows: each it offers "Add to this app" for, unless + * held, dismissed, in flight from any host, or failed at this same link state. `forget` names + * failures whose link state moved, so a peer back up is retried. The caller checks write access. + */ +export function linkedEnvironmentsToAutoAdd(input: { + readonly hostId: EnvironmentId; + readonly rows: ReadonlyArray; + readonly catalog: ReadonlySet; + readonly dismissed: ReadonlySet; + /** Linked environments being added now, from any host, so two hosts never add one twice. */ + readonly adding: ReadonlySet; + /** The link state each `autoAddKey` last failed at. */ + readonly failed: ReadonlyMap; +}): { + readonly add: ReadonlyArray; + readonly forget: ReadonlyArray; +} { + const add: Array = []; + const forget: Array = []; + for (const row of input.rows) { + const { link } = row; + if (link === null) continue; + const key = autoAddKey(input.hostId, row.environmentId); + const linkState = autoAddLinkState(link); + const failedAt = input.failed.get(key); + if (failedAt !== undefined && failedAt !== linkState) forget.push(key); + if ( + failedAt === linkState || + link.status !== "reachable" || + row.action !== "add-to-app" || + row.appAddress === null || + row.environmentId === input.hostId || + input.catalog.has(row.environmentId) || + input.dismissed.has(row.environmentId) || + input.adding.has(row.environmentId) + ) { + continue; + } + add.push({ row, key, linkState }); + } + return { add, forget }; +} + /** * 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 diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 47dce811574d..294a23e73a1e 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -603,6 +603,11 @@ export const ClientSettingsSchema = Schema.Struct({ // Opt-in TeX typesetting in rendered Markdown. Off keeps math parsing and // KaTeX out of the render path entirely. mathRenderingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + // Linked environments the user removed from this app, so it stops adding them on its own. + // Adding one by hand clears it. + dismissedLinkedEnvironmentIds: Schema.Array(EnvironmentId).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), }); export type ClientSettings = typeof ClientSettingsSchema.Type; @@ -2143,5 +2148,6 @@ export const ClientSettingsPatch = Schema.Struct({ snapShotAnimations: Schema.optionalKey(Schema.Boolean), wordWrap: Schema.optionalKey(Schema.Boolean), mathRenderingEnabled: Schema.optionalKey(Schema.Boolean), + dismissedLinkedEnvironmentIds: Schema.optionalKey(Schema.Array(EnvironmentId)), }); export type ClientSettingsPatch = typeof ClientSettingsPatch.Type; From 6002bdd5567a9f19d45abbdef5cf301f27f57d61 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:48:56 +0000 Subject: [PATCH 2/2] fix: linked machines that come online appear on return; removals stay removed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Repair round 1 for the auto-add review on 7b23515. - Each writable host's linked-environment list is read again on window focus, the document becoming visible, the browser online event and a network path change (useLiveRefresh refreshOnReconnect), with the existing 10 s floor and no timer. The key is shared with the Linked environments panel. - Removing under Connections always records the dismissal, whether or not a host's list is loaded. A remove that fails rolls it back. - addLinkedEnvironmentToApp is single-flight per linked environment across the button and the auto-add; the row shows "Adding…" while one runs. - Adding a machine back by any path (pairing, SSH, T3 Connect, Add to this app) clears its dismissal. - Docs no longer claim a machine appears as soon as its link is reachable. Model: claude-opus-5-5 Task: fix Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- .../cloud/CloudEnvironmentConnectList.tsx | 7 ++- .../settings/AddEnvironmentDialog.tsx | 2 + .../settings/ConnectionsSettings.tsx | 9 ++- .../settings/LinkedEnvironmentsSettings.tsx | 31 ++++++---- apps/web/src/connection/onboarding.ts | 9 ++- apps/web/src/connection/platform.ts | 30 ++-------- .../src/hooks/useLiveRefresh.browser.test.tsx | 32 ++++++++++ apps/web/src/hooks/useLiveRefresh.ts | 16 ++++- apps/web/src/lib/networkPathChanges.ts | 25 ++++++++ apps/web/src/state/knownEnvironments.tsx | 30 +++++++--- .../src/state/linkedEnvironmentDismissals.ts | 43 ++++++++++++++ apps/web/src/state/peerLinks.ts | 59 ++++++++----------- docs/user/remote-access.md | 6 +- .../client-runtime/src/linkRequest.test.ts | 48 +++++++++++++++ packages/client-runtime/src/linkRequest.ts | 20 +++++++ packages/contracts/src/settings.ts | 2 +- 16 files changed, 281 insertions(+), 88 deletions(-) create mode 100644 apps/web/src/lib/networkPathChanges.ts create mode 100644 apps/web/src/state/linkedEnvironmentDismissals.ts diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx index 8c3df5338074..9a56caa3a401 100644 --- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx +++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx @@ -39,6 +39,7 @@ import { Skeleton } from "../ui/skeleton"; import { toastManager } from "../ui/toast"; import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation"; +import { undismissLinkedEnvironment } from "../../state/linkedEnvironmentDismissals"; const EMPTY_DISCOVERY_REFRESH_INTERVAL_MS = 5_000; @@ -111,7 +112,11 @@ export function CloudEnvironmentConnectRows({ label: environment.label, }), }), - ); + ).then((result) => { + // Adding it back is the way back from removing it, so it may be added on its own again. + if (result._tag === "Success") void undismissLinkedEnvironment(environment.environmentId); + return result; + }); const [connectingEnvironmentIds, setConnectingEnvironmentIds] = useState< ReadonlySet >(new Set()); diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index 68f1da1a7c10..5dd78355aaea 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -58,6 +58,7 @@ import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desk import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments"; import { useAtomCommand } from "../../state/use-atom-command"; import { primaryServerKeybindingsAtom } from "~/state/server"; +import { undismissLinkedEnvironment } from "~/state/linkedEnvironmentDismissals"; import { resolveShortcutCommand, shortcutLabelForCommand, @@ -474,6 +475,7 @@ export function AddEnvironmentDialog({ } return; } + void undismissLinkedEnvironment(relayRouteOffer.environmentId); handleOpenChange(false); toastManager.add({ type: "success", diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 81f3b9ca68b9..bb99f1bc1e83 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -46,12 +46,12 @@ import { EnvironmentIconMenu } from "./EnvironmentIconPicker"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings"; import { - dismissLinkedEnvironment, forgetLinkOnConnect, hostsLinking, peerLinkEnvironment, usePeerLinkHosts, } from "~/state/peerLinks"; +import { dismissLinkedEnvironment } from "~/state/linkedEnvironmentDismissals"; import { LoadBalancingSettings } from "./LoadBalancingSettings"; import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings"; import { Input } from "../ui/input"; @@ -692,12 +692,15 @@ function ConnectionsSettingsContent({ setSavedBackendError(null); // Read before removing: the lists are this app's, and removal changes what it reports. const linkingHosts = hostsLinking(peerLinkHosts, environmentId); - // A host still linking it would add it straight back. Recorded first, so it never does. - if (linkingHosts.length > 0) void dismissLinkedEnvironment(environmentId); + // A host linking it, loaded here or not, would add it straight back. Recorded first, so it + // never does. + const undoDismiss = dismissLinkedEnvironment(environmentId); const result = await removeEnvironment(environmentId); setRemovingSavedEnvironmentId(null); if (result._tag === "Failure") { if (isAtomCommandInterrupted(result)) return; + // Still in the app, so nothing should keep it from coming back. + void undoDismiss.then((undo) => undo()); const error = squashAtomCommandFailure(result); const message = error instanceof Error ? error.message : "Failed to remove backend."; setSavedBackendError(message); diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 6de53364eca1..12a90de531fa 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -24,13 +24,13 @@ import { useId, useRef, useState } from "react"; import { requestConfirmDialog } from "~/confirmDialog"; import { mintPairingCodeOn } from "~/state/peerPairingCode"; import { environmentCatalog } from "~/connection/catalog"; -import { useKnownEnvironments } from "~/state/knownEnvironments"; +import { linkedEnvironmentsRefreshKey, useKnownEnvironments } from "~/state/knownEnvironments"; +import { dismissLinkedEnvironment } from "~/state/linkedEnvironmentDismissals"; import { + addingLinkedEnvironmentsAtom, addLinkedEnvironmentToApp, - dismissLinkedEnvironment, forgetLinkOnConnect, peerLinkEnvironment, - undismissLinkedEnvironment, useLinkableMachines, } from "~/state/peerLinks"; import { useEnvironmentScope, usePreparedConnection } from "~/state/session"; @@ -81,7 +81,7 @@ export function LinkedEnvironmentsSettings({ if (!known.isPending) known.refresh(); }, { - key: `linked-environments:${environmentId}`, + key: linkedEnvironmentsRefreshKey(environmentId), intervalMs: null, refreshOnShow: true, }, @@ -184,6 +184,8 @@ function LinkedEnvironmentRow({ const canAddToApp = useAtomValue(peerLinkEnvironment.addToApp.permissionAtom(environmentId)); const removeFromApp = useAtomCommand(environmentCatalog.remove, { reportFailure: false }); const [busy, setBusy] = useState(false); + // An add of this machine runs from any host's row or the automatic add; one at a time. + const adding = useAtomValue(addingLinkedEnvironmentsAtom).has(link.environmentId); 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. An app added through this link stays under Authorized clients there until you revoke it.`, @@ -207,29 +209,28 @@ function LinkedEnvironmentRow({ ) ?? Promise.resolve(false)); if (!alsoRemove) return; // Another host may still link it. Recorded first, so it is never added back on its own. - void dismissLinkedEnvironment(link.environmentId); + const undoDismiss = dismissLinkedEnvironment(link.environmentId); const removed = await removeFromApp(link.environmentId); if (removed._tag === "Success") forgetLinkOnConnect(link.environmentId); else if (!isAtomCommandInterrupted(removed)) { + // Still in the app, so it is not removed, and nothing should keep it from coming back. + void undoDismiss.then((undo) => undo()); failureToast(`Could not remove ${row.label}`, String(squashAtomCommandFailure(removed))); } }; const add = async () => { if (row.appAddress === null) return; - setBusy(true); + // Pairing clears a dismissal on success, so a later removal starts fresh. const added = await addLinkedEnvironmentToApp(environmentId, { environmentId: link.environmentId, label: link.label, onHostMachine: row.onHostMachine, }); - setBusy(false); if (added._tag === "Interrupted") return; if (added._tag === "Failed") { failureToast(`Could not add ${link.label} to this app`, added.message); return; } - // Choosing it again is the way back from removing it, so a later removal starts fresh. - void undismissLinkedEnvironment(link.environmentId); toastManager.add({ type: "success", title: `Added ${link.label} to this app`, @@ -282,15 +283,21 @@ function LinkedEnvironmentRow({ {canUnlink || (canAddToApp && row.action === "add-to-app") ? (
{canAddToApp && row.action === "add-to-app" ? ( - ) : null} {canUnlink ? (