From d783ad58934fb41a8bf36327ded20d3858892aed Mon Sep 17 00:00:00 2001
From: layered-control-agent-host
Date: Tue, 17 Nov 2026 03:15:13 +0000
Subject: [PATCH 1/2] feat(settings): Replicas connection card with environment
setup
Replace the generic remote-connection card for the Replicas provider with
a card that drives the existing Control routes: connection status, the
member responsible for Replicas agents (name and email so same-name
members stay distinguishable), Apply Relay setup (set principal, then
sync), per-environment opt-out, enable and retry, and the replica
binding list with errors and message counts. The one-step flow is kept:
the person pastes a Replicas API key and nobody handles a workspace key.
Co-Authored-By: Claude Fable 5.1
---
src/admin/remote-agent-api.ts | 134 +++++++
src/admin/remote-agents.tsx | 39 +-
src/admin/replicas-settings.test.tsx | 247 +++++++++++++
src/admin/replicas-settings.tsx | 512 +++++++++++++++++++++++++++
src/admin/settings.tsx | 3 +-
5 files changed, 923 insertions(+), 12 deletions(-)
create mode 100644 src/admin/replicas-settings.test.tsx
create mode 100644 src/admin/replicas-settings.tsx
diff --git a/src/admin/remote-agent-api.ts b/src/admin/remote-agent-api.ts
index 9d769251..979974e4 100644
--- a/src/admin/remote-agent-api.ts
+++ b/src/admin/remote-agent-api.ts
@@ -152,3 +152,137 @@ export const remoteAgentApi = {
}
},
};
+
+// Replicas setup. Status strings stay open (z.string()) so a newer Control can
+// add states without breaking this dashboard; unknown fields are stripped.
+const replicasEnvironmentSchema = z.object({
+ environmentId: z.string(),
+ name: z.string().nullable().optional(),
+ enabled: z.boolean(),
+ status: z.string(),
+ discoveryMissingSince: z.string().nullable().optional(),
+ optedOut: z.boolean().optional(),
+ stale: z.boolean().optional(),
+ registeredMcpId: z.string().nullable().optional(),
+ bindings: z.number().optional(),
+ creators: z
+ .array(
+ z.object({
+ creatorId: z.string(),
+ userId: z.string().nullable().optional(),
+ emailHint: z.string().nullable().optional(),
+ }),
+ )
+ .optional(),
+ pendingCreators: z
+ .array(
+ z.object({
+ creatorId: z.string(),
+ emailHint: z.string().nullable().optional(),
+ lastSeenAt: z.string().nullable().optional(),
+ count: z.number().optional(),
+ }),
+ )
+ .optional(),
+});
+export type ReplicasEnvironment = z.infer;
+export const replicasPolicySchema = z.object({
+ mcpUrl: z.string().optional(),
+ organizationId: z.string().nullable().optional(),
+ accessRevoked: z
+ .object({ since: z.string(), error: z.string().nullable().optional() })
+ .nullable()
+ .optional(),
+ allEnvironments: z.boolean().optional(),
+ principal: z
+ .object({ userId: z.string(), member: z.boolean() })
+ .nullable()
+ .optional(),
+ organizationShared: z.boolean().optional(),
+ environments: z.array(replicasEnvironmentSchema),
+});
+export type ReplicasPolicy = z.infer;
+export const replicasWorkspaceSchema = z.object({
+ connection: z
+ .object({
+ keyHint: z.string(),
+ organizationId: z.string().nullable().optional(),
+ validatedAt: z.string().nullable().optional(),
+ })
+ .nullable()
+ .optional(),
+ spawns: z.array(
+ z.object({
+ id: z.string(),
+ agent: z.string().nullable().optional(),
+ replicaId: z.string().nullable().optional(),
+ status: z.string(),
+ error: z.string().nullable().optional(),
+ provisioning_error: z
+ .object({
+ code: z.string().optional(),
+ stage: z.string().optional(),
+ retryable: z.boolean().optional(),
+ })
+ .nullable()
+ .optional(),
+ uncertainMessages: z.number().optional(),
+ rejectedMessages: z.number().optional(),
+ retryingMessages: z.number().optional(),
+ }),
+ ),
+});
+export type ReplicasSpawn = z.infer<
+ typeof replicasWorkspaceSchema
+>["spawns"][number];
+const replicasSyncSchema = z.object({
+ discovery: z
+ .object({ status: z.string() })
+ .nullable()
+ .optional(),
+ allEnvironments: z.boolean().optional(),
+ environments: z
+ .array(
+ z.object({
+ environmentId: z.string(),
+ status: z.string(),
+ retryable: z.boolean().optional(),
+ }),
+ )
+ .optional(),
+});
+
+export const replicasApi = {
+ workspace: (workspace: string, signal?: AbortSignal) =>
+ adminRequest(`${base(workspace)}/replicas`, replicasWorkspaceSchema, {
+ signal,
+ }),
+ policies: (workspace: string, signal?: AbortSignal) =>
+ adminRequest(
+ `${base(workspace)}/replicas/environment-policies`,
+ replicasPolicySchema,
+ { signal },
+ ),
+ sync: (workspace: string) =>
+ adminRequest(
+ `${base(workspace)}/replicas/environments/sync`,
+ replicasSyncSchema,
+ { method: "POST", body: {} },
+ ),
+ updateEnvironment: (
+ workspace: string,
+ environmentId: string,
+ body: { enabled: boolean } | { retry_registration: true },
+ ) =>
+ adminRequest(
+ `${base(workspace)}/replicas/environments/${encodeURIComponent(environmentId)}`,
+ null,
+ { method: "PUT", body },
+ ),
+ setPrincipal: (workspace: string, userId: string | null) =>
+ adminRequest(
+ `${base(workspace)}/replicas/environment-principal`,
+ replicasPolicySchema,
+ { method: "PUT", body: { userId } },
+ ),
+};
diff --git a/src/admin/remote-agents.tsx b/src/admin/remote-agents.tsx
index 858eecd7..29ed9b21 100644
--- a/src/admin/remote-agents.tsx
+++ b/src/admin/remote-agents.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { AmpConnectionCard } from "./amp-connection-card";
import { FactoryConnectionSection } from "./factory-connection";
+import { ReplicasConnectionCard } from "./replicas-settings";
import { remoteAgentApi, type RemoteProvider } from "./remote-agent-api";
import { useLoad, message } from "./use-load";
import { ApiError } from "./api";
@@ -186,9 +187,12 @@ function AmpSettings({ workspaceId }: { workspaceId: string }) {
/** Workspace-keyed by the parent: old requests, drafts and secrets never cross scopes. */
export function RemoteAgentsSection({
workspaceId,
+ organizationId,
canManage,
}: {
workspaceId: string;
+ /** Lists members for the Replicas responsible-member choice. */
+ organizationId?: string;
canManage: boolean;
}) {
const { data: catalog, error: catalogError } = useLoad((signal) =>
@@ -231,17 +235,30 @@ export function RemoteAgentsSection({
{factory?.implemented && factory.enabled && (
)}
- {data?.providers.map((provider) => (
- readsIssued.current}
- />
- ))}
+ {data?.providers.map((provider) =>
+ provider.id === "replicas" ? (
+ readsIssued.current}
+ />
+ ) : (
+ readsIssued.current}
+ />
+ ),
+ )}
{!data && !error && (
Loading remote provider connections…
)}
diff --git a/src/admin/replicas-settings.test.tsx b/src/admin/replicas-settings.test.tsx
new file mode 100644
index 00000000..5ea8cd49
--- /dev/null
+++ b/src/admin/replicas-settings.test.tsx
@@ -0,0 +1,247 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { RemoteAgentsSection } from "./remote-agents";
+
+type Call = {
+ url: string;
+ init: RequestInit;
+ body: Record | null;
+};
+type Environment = {
+ environmentId: string;
+ name: string | null;
+ enabled: boolean;
+ status: string;
+ optedOut: boolean;
+ stale: boolean;
+ bindings: number;
+};
+let calls: Call[] = [];
+let remoteConnected = true;
+let principal: { userId: string; member: boolean } | null = null;
+let environments: Environment[] = [];
+let spawns: Array> = [];
+const secret = "replicas_" + "s".repeat(32);
+const connection = {
+ keyHint: "…ssss",
+ validatedAt: "2026-11-10T00:00:00Z",
+ providerAccount: null,
+};
+const environment = (
+ environmentId: string,
+ status: string,
+ extra: Partial = {},
+): Environment => ({
+ environmentId,
+ name: null,
+ enabled: status !== "disabled",
+ status,
+ optedOut: false,
+ stale: false,
+ bindings: 0,
+ ...extra,
+});
+const policy = () => ({
+ mcpUrl: "/cloud/api/v1/mcp/replicas",
+ organizationId: "rep-org",
+ accessRevoked: null,
+ allEnvironments: true,
+ principal,
+ organizationShared: false,
+ environments: environments.map((row) => ({
+ ...row,
+ discoveryMissingSince: null,
+ registeredMcpId: row.status === "registered" ? "mcp-1" : null,
+ creators: [],
+ pendingCreators: [],
+ futureField: { ignored: true },
+ })),
+});
+function respond(call: Call) {
+ const path = call.url;
+ const method = call.init.method ?? "GET";
+ if (path.endsWith("/providers")) return Response.json({ providers: [] });
+ if (path.endsWith("/remote-agent-connections"))
+ return Response.json({
+ providers: [
+ {
+ id: "replicas",
+ product: "Replicas",
+ docsUrl: "https://replicas.dev",
+ connection: remoteConnected ? connection : null,
+ capabilities: {
+ connectionManagement: true,
+ relayBinding: true,
+ historySync: false,
+ },
+ },
+ ],
+ });
+ if (path.endsWith("/remote-agent-connections/replicas")) {
+ remoteConnected = method !== "DELETE";
+ return Response.json({ connection, environmentSetup: { status: "ok" } });
+ }
+ if (path.endsWith("/organizations/o1/memberships"))
+ return Response.json({
+ memberships: [
+ { userId: "u-ada1", email: "ada@test.example", name: "Ada Lovelace", role: "admin", joinedAt: null },
+ { userId: "u-ada2", email: "ada.l@test.example", name: "Ada Lovelace", role: "member", joinedAt: null },
+ ],
+ });
+ if (path.endsWith("/replicas/environment-policies")) return Response.json(policy());
+ if (path.endsWith("/replicas/environment-principal") && method === "PUT") {
+ const userId = call.body?.userId;
+ principal = typeof userId === "string" ? { userId, member: true } : null;
+ return Response.json(policy());
+ }
+ if (path.endsWith("/replicas/environments/sync") && method === "POST") {
+ environments = environments.map((row) => ({ ...row, status: "registered" }));
+ return Response.json({
+ discovery: { status: "ok", environments: [] },
+ allEnvironments: true,
+ environments: environments.map(({ environmentId, status }) => ({ environmentId, status })),
+ });
+ }
+ const environmentWrite = /\/replicas\/environments\/([^/]+)$/.exec(path);
+ if (environmentWrite && method === "PUT") {
+ const row = environments.find((row) => row.environmentId === environmentWrite[1]);
+ return Response.json({ environment: row });
+ }
+ if (path.endsWith("/workspaces/w1/replicas"))
+ return Response.json({ connection: { keyHint: "…ssss", organizationId: "rep-org", validatedAt: connection.validatedAt }, spawns });
+ return Response.json({ error: "not_found" }, { status: 404 });
+}
+beforeEach(() => {
+ calls = [];
+ remoteConnected = true;
+ principal = null;
+ environments = [environment("env-1", "enabled"), environment("env-2", "registration_unconfirmed")];
+ spawns = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input, init: RequestInit = {}) => {
+ const call = {
+ url: String(input),
+ init,
+ body: init.body ? JSON.parse(String(init.body)) : null,
+ };
+ calls.push(call);
+ return respond(call);
+ }),
+ );
+});
+afterEach(() => vi.unstubAllGlobals());
+
+const replicasCard = async () =>
+ (await screen.findByText("Replicas", { selector: "h3" })).closest(
+ '[data-slot="card"]',
+ )! as HTMLElement;
+const optionTexts = (select: HTMLElement) =>
+ within(select).getAllByRole("option").map((option) => option.textContent);
+const row = (id: string) =>
+ screen.getByText(id, { selector: "small" }).closest("li")! as HTMLElement;
+
+it("asks for a responsible member and lists same-name members by email", async () => {
+ render( );
+ const status = await screen.findByText(/Environment setup does not grant messaging by itself/);
+ expect(status).toHaveTextContent("Choose the member responsible for these agents to enable automatic joining. 0 of 2 environments configured.");
+ const select = screen.getByLabelText("Member responsible for Replicas agents");
+ await waitFor(() => expect(optionTexts(select)).toEqual([
+ "No default principal",
+ "Ada Lovelace (ada@test.example)",
+ "Ada Lovelace (ada.l@test.example)",
+ ]));
+ expect(select).toHaveValue("");
+});
+
+it("applies the chosen principal, then syncs and shows the configured state", async () => {
+ render( );
+ const select = await screen.findByLabelText("Member responsible for Replicas agents");
+ await waitFor(() => expect(optionTexts(select)).toHaveLength(3));
+ fireEvent.change(select, { target: { value: "u-ada2" } });
+ fireEvent.click(screen.getByRole("button", { name: "Apply Relay setup" }));
+ const status = await screen.findByText(/Automatic Relay messaging is configured/);
+ expect(status).toHaveTextContent("2 of 2 environments configured.");
+ const put = calls.findIndex((call) => call.url.endsWith("/replicas/environment-principal") && call.init.method === "PUT");
+ const sync = calls.findIndex((call) => call.url.endsWith("/replicas/environments/sync") && call.init.method === "POST");
+ expect(put).toBeGreaterThanOrEqual(0);
+ expect(calls[put]?.body).toEqual({ userId: "u-ada2" });
+ expect(sync).toBeGreaterThan(put);
+ expect(screen.getByLabelText("Member responsible for Replicas agents")).toHaveValue("u-ada2");
+});
+
+it("opts out, retries and enables individual environments", async () => {
+ principal = { userId: "u-ada1", member: true };
+ environments = [
+ environment("env-1", "registered", { name: "Primary" }),
+ environment("env-2", "registration_unconfirmed"),
+ environment("env-3", "disabled", { optedOut: true }),
+ ];
+ render( );
+ await screen.findByText(/Automatic Relay setup failed for 1 environment\./);
+ expect(within(row("env-1")).getByText("Configured")).toBeInTheDocument();
+ expect(within(row("env-3")).getByText("Opted out")).toBeInTheDocument();
+ const writes = () => calls.filter((call) => call.init.method === "PUT");
+
+ fireEvent.click(within(row("env-1")).getByRole("button", { name: "Opt out" }));
+ await waitFor(() => expect(writes()).toHaveLength(1));
+ expect(writes()[0]?.url).toBe("/cloud/api/v1/workspaces/w1/replicas/environments/env-1");
+ expect(writes()[0]?.body).toEqual({ enabled: false });
+
+ await waitFor(() => expect(within(row("env-2")).getByRole("button", { name: "Retry" })).toBeEnabled());
+ fireEvent.click(within(row("env-2")).getByRole("button", { name: "Retry" }));
+ await waitFor(() => expect(writes()).toHaveLength(2));
+ expect(writes()[1]?.url).toMatch(/\/environments\/env-2$/);
+ expect(writes()[1]?.body).toEqual({ retry_registration: true });
+
+ await waitFor(() => expect(within(row("env-3")).getByRole("button", { name: "Enable" })).toBeEnabled());
+ fireEvent.click(within(row("env-3")).getByRole("button", { name: "Enable" }));
+ await waitFor(() => expect(writes()).toHaveLength(3));
+ expect(writes()[2]?.url).toMatch(/\/environments\/env-3$/);
+ expect(writes()[2]?.body).toEqual({ enabled: true });
+});
+
+it("lists replica bindings with errors and message counts", async () => {
+ spawns = [
+ { id: "s1", agent: "ship-1", replicaId: "r-1", status: "bound", error: null, uncertainMessages: 0, rejectedMessages: 0, retryingMessages: 0 },
+ { id: "s2", agent: null, replicaId: "r-2", status: "rejected", error: "Replicas refused the launch.", uncertainMessages: 1, rejectedMessages: 2, retryingMessages: 3 },
+ ];
+ render( );
+ expect(await screen.findByText((_, element) => element?.tagName === "SPAN" && element.textContent === "@ship-1 · bound")).toBeInTheDocument();
+ expect(screen.getByText((_, element) => element?.tagName === "SPAN" && element.textContent === "r-2 · rejected")).toBeInTheDocument();
+ expect(screen.getByRole("alert")).toHaveTextContent("Replicas refused the launch.");
+ expect(screen.getByText("2 rejected · 1 uncertain · 3 retrying")).toBeInTheDocument();
+});
+
+it("connects with a key, never keeps it in the document, then loads Replicas setup", async () => {
+ remoteConnected = false;
+ render( );
+ const input = await screen.findByLabelText("Replicas API key");
+ expect(calls.some((call) => call.url.includes("/replicas/"))).toBe(false);
+ fireEvent.change(input, { target: { value: secret } });
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ await screen.findByText(/Environment setup does not grant messaging by itself/);
+ const save = calls.find((call) => call.init.method === "POST")!;
+ expect(save.url).toBe("/cloud/api/v1/workspaces/w1/remote-agent-connections/replicas");
+ expect(save.body).toEqual({ key: secret });
+ expect(screen.getByLabelText("Replace Replicas API key")).toHaveValue("");
+ expect(document.body.innerHTML).not.toContain(secret);
+ expect(calls.some((call) => call.url.endsWith("/replicas/environment-policies"))).toBe(true);
+});
+
+it("shows members a safe prompt without management controls", async () => {
+ remoteConnected = false;
+ render( );
+ expect(await screen.findByText("Ask an organization owner or admin to connect Replicas.")).toBeInTheDocument();
+ const card = await replicasCard();
+ expect(within(card).queryByRole("button")).not.toBeInTheDocument();
+ expect(within(card).queryByRole("combobox")).not.toBeInTheDocument();
+ expect(within(card).queryByLabelText("Replicas API key")).not.toBeInTheDocument();
+ expect(calls.some((call) => call.url.includes("/replicas") || call.url.includes("/memberships"))).toBe(false);
+});
diff --git a/src/admin/replicas-settings.tsx b/src/admin/replicas-settings.tsx
new file mode 100644
index 00000000..b31243ee
--- /dev/null
+++ b/src/admin/replicas-settings.tsx
@@ -0,0 +1,512 @@
+import { useEffect, useRef, useState } from "react";
+import { adminApi, ApiError } from "./api";
+import type { Member } from "./contracts";
+import {
+ remoteAgentApi,
+ replicasApi,
+ type RemoteProvider,
+ type ReplicasEnvironment,
+ type ReplicasPolicy,
+ type ReplicasSpawn,
+} from "./remote-agent-api";
+import { formatDate, message, useLoad } from "./use-load";
+import {
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Input,
+} from "../shell/ui";
+
+const selectClass =
+ "rounded-full border border-[var(--border-default)] bg-[var(--surface-soft)] px-3 py-1.5 text-xs text-foreground disabled:opacity-50";
+
+const failingStatuses = new Set([
+ "registration_unconfirmed",
+ "discovery_missing",
+ "access_revoked",
+]);
+
+const needsRetry = (environment: ReplicasEnvironment) =>
+ failingStatuses.has(environment.status) || environment.stale === true;
+
+const plural = (count: number, one: string, many: string) =>
+ count === 1 ? one : many;
+
+function statusLine(policy: ReplicasPolicy) {
+ const environments = policy.environments;
+ const total = environments.length;
+ const registered = environments.filter(
+ (environment) => environment.status === "registered",
+ ).length;
+ const failing = environments.filter(
+ (environment) => environment.enabled && needsRetry(environment),
+ ).length;
+ const principal = policy.principal ?? null;
+ let text: string;
+ if (policy.organizationShared)
+ text =
+ "This Replicas organization is connected in another workspace. Nothing is admitted until one of them disconnects.";
+ else if (policy.accessRevoked)
+ text = `Replicas refused the stored API key (since ${formatDate(policy.accessRevoked.since)}). Replace the key to restore Relay setup.`;
+ else if (!principal)
+ text =
+ "Environment setup does not grant messaging by itself. Choose the member responsible for these agents to enable automatic joining.";
+ else if (!principal.member)
+ text =
+ "The responsible member is no longer in this organization. Choose another member to restore automatic joining.";
+ else if (failing > 0)
+ text = `Automatic Relay setup failed for ${failing} ${plural(failing, "environment", "environments")}. Retry setup or check the provider connection.`;
+ else if (
+ environments.some(
+ (environment) => environment.enabled && environment.status === "enabled",
+ )
+ )
+ text =
+ "Environment Relay setup is pending; Apply Relay setup or the periodic sync will retry it.";
+ else
+ text =
+ "Automatic Relay messaging is configured. Each mothership and ship joins as its own agent when it calls Relay.";
+ return `${text} ${registered} of ${total} ${plural(total, "environment", "environments")} configured.`;
+}
+
+function statusWord(environment: ReplicasEnvironment) {
+ const word =
+ environment.status === "registered"
+ ? "Configured"
+ : environment.status === "enabled"
+ ? "Pending"
+ : environment.status === "registration_unconfirmed"
+ ? "Registration unconfirmed"
+ : environment.status === "discovery_missing"
+ ? "Not listed by Replicas"
+ : environment.status === "access_revoked"
+ ? "Key refused"
+ : environment.status === "disabled"
+ ? environment.optedOut
+ ? "Opted out"
+ : "Disabled"
+ : environment.status;
+ return environment.stale ? `${word} · stale connection` : word;
+}
+
+const memberLabel = (member: Member) =>
+ member.name?.trim() ? `${member.name} (${member.email})` : member.email;
+
+function SpawnRow({ spawn }: { spawn: ReplicasSpawn }) {
+ const rejected = spawn.rejectedMessages ?? 0;
+ const uncertain = spawn.uncertainMessages ?? 0;
+ const retrying = spawn.retryingMessages ?? 0;
+ return (
+
+
+ {spawn.agent ? (
+ @{spawn.agent}
+ ) : spawn.replicaId ? (
+ {spawn.replicaId}
+ ) : (
+ "unassigned"
+ )}
+ {" · "}
+ {spawn.status}
+
+ {spawn.error ? {spawn.error}
: null}
+ {rejected + uncertain + retrying > 0 ? (
+
+ {rejected} rejected · {uncertain} uncertain · {retrying} retrying
+
+ ) : null}
+
+ );
+}
+
+/** Mounted only while connected, keyed by the connection: a new key reloads. */
+function ReplicasSetup({
+ workspaceId,
+ organizationId,
+ canManage,
+}: {
+ workspaceId: string;
+ organizationId?: string;
+ canManage: boolean;
+}) {
+ const setup = useLoad(async (signal) => {
+ const [policy, workspace] = await Promise.all([
+ replicasApi.policies(workspaceId, signal),
+ replicasApi.workspace(workspaceId, signal),
+ ]);
+ return { policy, spawns: workspace.spawns };
+ });
+ const members = useLoad((signal) =>
+ canManage && organizationId
+ ? adminApi.members(organizationId, signal)
+ : Promise.resolve(null),
+ );
+ const principalId = setup.data?.policy.principal?.userId ?? "";
+ const [seed, setSeed] = useState(principalId);
+ const [choice, setChoice] = useState(principalId);
+ if (seed !== principalId) {
+ // A fresh read re-seeds the selection with the stored principal.
+ setSeed(principalId);
+ setChoice(principalId);
+ }
+ const [pending, setPending] = useState(null);
+ const [error, setError] = useState(null);
+ const [rowErrors, setRowErrors] = useState>({});
+ const active = useRef(true);
+ useEffect(() => {
+ active.current = true;
+ return () => {
+ active.current = false;
+ };
+ }, []);
+
+ async function write(
+ action: string,
+ work: () => Promise,
+ environmentId?: string,
+ ) {
+ if (pending || !canManage) return;
+ setPending(action);
+ setError(null);
+ if (environmentId)
+ setRowErrors((errors) => {
+ const next = { ...errors };
+ delete next[environmentId];
+ return next;
+ });
+ try {
+ await work();
+ } catch (failure) {
+ if (active.current) {
+ const text = message(failure);
+ if (environmentId)
+ setRowErrors((errors) => ({ ...errors, [environmentId]: text }));
+ else setError(text);
+ }
+ } finally {
+ // Every write re-reads: a 409 (or a partial apply) leaves newer server
+ // state, and useLoad keeps only the newest response.
+ if (active.current) {
+ setPending(null);
+ setup.reload();
+ }
+ }
+ }
+
+ if (setup.error)
+ return (
+
+ {message(setup.error)}{" "}
+
+ Try again
+
+
+ );
+ if (!setup.data) return Loading Replicas setup…
;
+ const { policy, spawns } = setup.data;
+ const principal = policy.principal ?? null;
+ const memberList = members.data ?? [];
+ // Keep a stored principal who left the organization visible in the select.
+ const formerPrincipalId =
+ principal && members.data &&
+ !members.data.some((member) => member.userId === principal.userId)
+ ? principal.userId
+ : null;
+ const selectId = `replicas-principal-${workspaceId}`;
+ return (
+
+
+ {statusLine(policy)}
+
+ {canManage && (
+
+ )}
+
+
Environments
+ {policy.environments.length === 0 ? (
+
+ No environments discovered yet. Apply Relay setup to discover them.
+
+ ) : (
+
+ {policy.environments.map((environment) => {
+ const id = environment.environmentId;
+ const bindings = environment.bindings ?? 0;
+ const unmapped = environment.pendingCreators?.length ?? 0;
+ const rowError = rowErrors[id];
+ return (
+
+
+
+ {environment.name || id}
+
+ {id}
+
+
+ {statusWord(environment)}
+ {bindings > 0 && (
+
+ {bindings} bound
+
+ )}
+ {unmapped > 0 && (
+
+ {unmapped} unmapped{" "}
+ {plural(unmapped, "creator", "creators")}
+
+ )}
+ {canManage && (
+ <>
+
+ void write(
+ `toggle:${id}`,
+ () =>
+ replicasApi.updateEnvironment(workspaceId, id, {
+ enabled: !environment.enabled,
+ }),
+ id,
+ )
+ }
+ >
+ {pending === `toggle:${id}`
+ ? "Working…"
+ : environment.enabled
+ ? "Opt out"
+ : "Enable"}
+
+ {needsRetry(environment) && (
+
+ void write(
+ `retry:${id}`,
+ () =>
+ replicasApi.updateEnvironment(
+ workspaceId,
+ id,
+ { retry_registration: true },
+ ),
+ id,
+ )
+ }
+ >
+ {pending === `retry:${id}` ? "Working…" : "Retry"}
+
+ )}
+ >
+ )}
+
+ {rowError && {rowError}
}
+
+ );
+ })}
+
+ )}
+
+
+
Replica bindings
+ {spawns.length === 0 ? (
+
+ No replica bindings yet.
+
+ ) : (
+
+ {spawns.map((spawn) => (
+
+ ))}
+
+ )}
+
+
+ );
+}
+
+export function ReplicasConnectionCard({
+ provider,
+ workspaceId,
+ organizationId,
+ canManage,
+ onConflict,
+ readRevision,
+ currentReadRevision,
+}: {
+ provider: RemoteProvider;
+ workspaceId: string;
+ organizationId?: string;
+ canManage: boolean;
+ onConflict(): void;
+ readRevision: number;
+ currentReadRevision(): number;
+}) {
+ const [connection, setConnection] = useState(provider.connection);
+ const [snapshot, setSnapshot] = useState(provider);
+ const [lastWriteRead, setLastWriteRead] = useState(0);
+ if (snapshot !== provider) {
+ setSnapshot(provider);
+ // Reads begun before the latest confirmed mutation cannot replace it.
+ if (readRevision > lastWriteRead) setConnection(provider.connection);
+ }
+ const [key, setKey] = useState("");
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState(null);
+ const active = useRef(true);
+ useEffect(() => {
+ active.current = true;
+ return () => {
+ active.current = false;
+ };
+ }, []);
+ const manageable = canManage && provider.capabilities.connectionManagement;
+ async function change(disconnect = false) {
+ if (pending || !manageable) return;
+ const submitted = key;
+ setPending(true);
+ setError(null);
+ setKey("");
+ try {
+ const result = disconnect
+ ? (await remoteAgentApi.disconnect(workspaceId, "replicas"), null)
+ : (await remoteAgentApi.connect(workspaceId, "replicas", submitted))
+ .connection;
+ if (active.current) {
+ setLastWriteRead(currentReadRevision());
+ setConnection(result);
+ }
+ } catch (error) {
+ if (active.current) {
+ setError(message(error));
+ if (error instanceof ApiError && error.status === 409) onConflict();
+ }
+ } finally {
+ if (active.current) setPending(false);
+ }
+ }
+ const keyId = `replicas-key-${workspaceId}`;
+ return (
+
+
+ Replicas
+
+
+
+ Connect Replicas so agents can launch replicas and exchange Relay
+ messages through this installation. Create a dedicated Replicas API
+ key with access to the environments your agents use. The key is
+ stored encrypted. Relay setup is automatic for those environments; no
+ Relay workspace key is needed.
+
+ {connection && (
+ <>
+
+
+ Connected with {connection.keyHint}, checked{" "}
+ {formatDate(connection.validatedAt)}.
+
+ {manageable && (
+
void change(true)}
+ >
+ Disconnect
+
+ )}
+
+
+ Disconnect revokes every replica's Relay access. Reconnecting
+ requires explicitly restoring each previous VM.
+
+
+ >
+ )}
+ {manageable ? (
+
+ ) : (
+ !connection && (
+ Ask an organization owner or admin to connect Replicas.
+ )
+ )}
+ {error && {error}
}
+
+
+ );
+}
diff --git a/src/admin/settings.tsx b/src/admin/settings.tsx
index a492f55c..d7a7550f 100644
--- a/src/admin/settings.tsx
+++ b/src/admin/settings.tsx
@@ -271,7 +271,8 @@ export function Settings(props: {
)}
/>
+ workspaceId={context.currentWorkspace.id}
+ organizationId={context.currentOrganization.id} canManage={manage} />
)}
{active === "tokens" && manage && (
From b25159203950266bb58e9e22499ec8406dd268a6 Mon Sep 17 00:00:00 2001
From: layered-control-agent-host
Date: Tue, 17 Nov 2026 03:28:41 +0000
Subject: [PATCH 2/2] fix(replicas): gate the setup panel on managers and share
one busy state with the connection form
Control refuses every Replicas route to non-owner/admin members, so the
setup panel now mounts only for managers and members see the owner/admin
prompt whether or not a connection exists. The connection form and the
setup panel share one busy signal: Disconnect/Replace are disabled while a
setup write runs and setup writes are refused while the connection is being
replaced or disconnected.
Co-Authored-By: Claude Fable 5.1
---
src/admin/replicas-settings.test.tsx | 33 +++++++++++++++++++
src/admin/replicas-settings.tsx | 48 +++++++++++++++++++---------
2 files changed, 66 insertions(+), 15 deletions(-)
diff --git a/src/admin/replicas-settings.test.tsx b/src/admin/replicas-settings.test.tsx
index 5ea8cd49..b249cfe0 100644
--- a/src/admin/replicas-settings.test.tsx
+++ b/src/admin/replicas-settings.test.tsx
@@ -245,3 +245,36 @@ it("shows members a safe prompt without management controls", async () => {
expect(within(card).queryByLabelText("Replicas API key")).not.toBeInTheDocument();
expect(calls.some((call) => call.url.includes("/replicas") || call.url.includes("/memberships"))).toBe(false);
});
+
+it("shows a connected non-manager the prompt and never calls the setup routes", async () => {
+ render( );
+ expect(await screen.findByText("Ask an organization owner or admin to connect Replicas.")).toBeInTheDocument();
+ const card = await replicasCard();
+ expect(within(card).getByText(/Connected with/)).toBeInTheDocument();
+ expect(within(card).queryByRole("button")).not.toBeInTheDocument();
+ expect(calls.some((call) => call.url.endsWith("/replicas/environment-policies"))).toBe(false);
+ expect(calls.some((call) => call.url.endsWith("/workspaces/w1/replicas"))).toBe(false);
+});
+
+it("disables Disconnect while a setup write is in flight", async () => {
+ render( );
+ const select = await screen.findByLabelText("Member responsible for Replicas agents");
+ await waitFor(() => expect(optionTexts(select)).toHaveLength(3));
+ const impl = vi.mocked(fetch).getMockImplementation()!;
+ let release: () => void = () => {};
+ const gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ vi.mocked(fetch).mockImplementation(async (input, init) => {
+ if (String(input).endsWith("/replicas/environments/sync")) await gate;
+ return impl(input, init);
+ });
+ const disconnect = screen.getByRole("button", { name: "Disconnect" });
+ expect(disconnect).toBeEnabled();
+ fireEvent.click(screen.getByRole("button", { name: "Apply Relay setup" }));
+ await waitFor(() => expect(disconnect).toBeDisabled());
+ expect(screen.getByRole("button", { name: "Replace" })).toBeDisabled();
+ expect(screen.getByLabelText("Replace Replicas API key")).toBeDisabled();
+ release();
+ await waitFor(() => expect(disconnect).toBeEnabled());
+});
diff --git a/src/admin/replicas-settings.tsx b/src/admin/replicas-settings.tsx
index b31243ee..4f5d509c 100644
--- a/src/admin/replicas-settings.tsx
+++ b/src/admin/replicas-settings.tsx
@@ -126,10 +126,16 @@ function ReplicasSetup({
workspaceId,
organizationId,
canManage,
+ disabled = false,
+ onBusyChange,
}: {
workspaceId: string;
organizationId?: string;
canManage: boolean;
+ /** True while the connection itself is being replaced or disconnected. */
+ disabled?: boolean;
+ /** Reports whether a setup write is in flight. */
+ onBusyChange?(busy: boolean): void;
}) {
const setup = useLoad(async (signal) => {
const [policy, workspace] = await Promise.all([
@@ -155,6 +161,7 @@ function ReplicasSetup({
const [error, setError] = useState(null);
const [rowErrors, setRowErrors] = useState>({});
const active = useRef(true);
+ const inFlight = useRef(false);
useEffect(() => {
active.current = true;
return () => {
@@ -167,7 +174,10 @@ function ReplicasSetup({
work: () => Promise,
environmentId?: string,
) {
- if (pending || !canManage) return;
+ // The ref closes the window before the pending state re-renders.
+ if (inFlight.current || pending || disabled || !canManage) return;
+ inFlight.current = true;
+ onBusyChange?.(true);
setPending(action);
setError(null);
if (environmentId)
@@ -186,6 +196,8 @@ function ReplicasSetup({
else setError(text);
}
} finally {
+ inFlight.current = false;
+ onBusyChange?.(false);
// Every write re-reads: a 409 (or a partial apply) leaves newer server
// state, and useLoad keeps only the newest response.
if (active.current) {
@@ -238,7 +250,7 @@ function ReplicasSetup({
id={selectId}
className={selectClass}
value={choice}
- disabled={pending !== null}
+ disabled={disabled || pending !== null}
onChange={(event) => setChoice(event.target.value)}
>
No default principal
@@ -254,7 +266,7 @@ function ReplicasSetup({
)}
-
+
{pending === "apply" ? "Working…" : "Apply Relay setup"}
@@ -306,7 +318,7 @@ function ReplicasSetup({
void write(
`toggle:${id}`,
@@ -328,7 +340,7 @@ function ReplicasSetup({
void write(
`retry:${id}`,
@@ -400,6 +412,7 @@ export function ReplicasConnectionCard({
}
const [key, setKey] = useState("");
const [pending, setPending] = useState(false);
+ const [setupBusy, setSetupBusy] = useState(false);
const [error, setError] = useState(null);
const active = useRef(true);
useEffect(() => {
@@ -410,7 +423,7 @@ export function ReplicasConnectionCard({
}, []);
const manageable = canManage && provider.capabilities.connectionManagement;
async function change(disconnect = false) {
- if (pending || !manageable) return;
+ if (pending || setupBusy || !manageable) return;
const submitted = key;
setPending(true);
setError(null);
@@ -457,7 +470,7 @@ export function ReplicasConnectionCard({
{manageable && (
void change(true)}
>
Disconnect
@@ -468,12 +481,16 @@ export function ReplicasConnectionCard({
Disconnect revokes every replica's Relay access. Reconnecting
requires explicitly restoring each previous VM.
-
+ {canManage && (
+
+ )}
>
)}
{manageable ? (
@@ -493,15 +510,16 @@ export function ReplicasConnectionCard({
data-1p-ignore="true"
data-lpignore="true"
value={key}
+ disabled={pending || setupBusy}
onChange={(event) => setKey(event.target.value)}
/>
-
+
{pending ? "Working…" : connection ? "Replace" : "Connect"}
) : (
- !connection && (
+ (!canManage || !connection) && (
Ask an organization owner or admin to connect Replicas.
)
)}