From 9257bd0341a89303f7680f7658a2ac4131cd858e Mon Sep 17 00:00:00 2001 From: layered-control-agent-host Date: Tue, 17 Nov 2026 07:44:06 +0000 Subject: [PATCH 1/2] feat(settings): workspace leaders card on the Policies page Owners and admins set the agent-name patterns whose direct messages the hosts treat as instructions from a lead, one per line, checked locally against the same limits Control enforces (64 patterns, 1..128 characters, `*` and `?` wildcards, whole name, case-sensitive). The card shows the agents the patterns match right now and surfaces Control's invalid_request and workspace_leaders_unavailable messages as is. Co-Authored-By: Claude Fable 5.1 --- docs/repository-guide.md | 8 ++ src/admin/admin.css | 6 ++ src/admin/api.ts | 14 +++ src/admin/contracts.ts | 13 +++ src/admin/policies.test.tsx | 167 ++++++++++++++++++++++++++++- src/admin/policies.tsx | 207 ++++++++++++++++++++++++++++++++++++ src/admin/settings.tsx | 19 ++-- 7 files changed, 427 insertions(+), 7 deletions(-) diff --git a/docs/repository-guide.md b/docs/repository-guide.md index c167cc32..d5056804 100644 --- a/docs/repository-guide.md +++ b/docs/repository-guide.md @@ -205,6 +205,14 @@ When Control's `SELFHOST_OPERATOR_CONTROLS` is `off`, writes answer reason. Control has no read that reports the switch, so the page learns it from the first refused write. +The same page carries a **Workspace leaders** card for the current workspace: +one agent-name pattern per line (`GET|PUT /cloud/api/v1/workspaces/{id}/leaders`, +body `{ "patterns": [...] }`), checked before sending (at most 64 patterns of +1 to 128 characters, whole-name and case-sensitive, `*` and `?` the only +wildcards, duplicates collapsed), with the agents currently matched listed +below. Control's `400 invalid_request` and `502 workspace_leaders_unavailable` +messages are shown as is; hosts pick up a change within about a minute. + ## Password sign-in (self-hosted) When relaycontrol lists `password` in `SELFHOST_SIGNIN_METHODS`, signed-out diff --git a/src/admin/admin.css b/src/admin/admin.css index 03df47e0..dde32dff 100644 --- a/src/admin/admin.css +++ b/src/admin/admin.css @@ -341,3 +341,9 @@ } } } +.settings .policy-patterns { + width: 100%; + min-height: 7em; + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 12px; +} diff --git a/src/admin/api.ts b/src/admin/api.ts index ea9d3023..24e80c79 100644 --- a/src/admin/api.ts +++ b/src/admin/api.ts @@ -35,6 +35,7 @@ import { usageSchema, usagePeopleSchema, usagePersonSessionsSchema, + workspaceLeadersSchema, type TokenPurpose, type Role, } from "./contracts"; @@ -397,6 +398,19 @@ export const adminApi = { method: "DELETE", headers: { "If-Match": String(revision) }, }), + /** Any member reads; also the agents the patterns match right now. */ + getWorkspaceLeaders: (workspace: string, signal?: AbortSignal) => + call(`${ws(workspace)}/leaders`, workspaceLeadersSchema, { signal }), + /** + * Owner/admin only; replaces the whole pattern list. 400 `invalid_request` + * for a bad list, 502 `workspace_leaders_unavailable` when the Relaycast + * engine cannot be reached. + */ + setWorkspaceLeaders: (workspace: string, patterns: string[]) => + call(`${ws(workspace)}/leaders`, workspaceLeadersSchema, { + method: "PUT", + body: { patterns }, + }), hardDeleteSession: ( organization: string, session: { workspaceId: string; source: string; sessionId: string }, diff --git a/src/admin/contracts.ts b/src/admin/contracts.ts index aeb442c5..3d6cfcc4 100644 --- a/src/admin/contracts.ts +++ b/src/admin/contracts.ts @@ -430,3 +430,16 @@ export const capturePolicySchema = z.object({ settings: captureSettingsSchema, }); export type CapturePolicy = z.infer; + +/** + * relay-control GET|PUT /workspaces/{id}/leaders: the agent-name patterns + * whose DMs hosts treat as instructions from a lead, and the agents they + * match right now. Any member reads; owners and admins write. + */ +export const MAX_LEADER_PATTERNS = 64; +export const MAX_LEADER_PATTERN_LENGTH = 128; +export const workspaceLeadersSchema = z.object({ + leaders: z.array(z.object({ name: z.string(), agent_id: z.string() })), + patterns: z.array(z.string()), +}); +export type WorkspaceLeaders = z.infer; diff --git a/src/admin/policies.test.tsx b/src/admin/policies.test.tsx index ab81c71a..81af15c1 100644 --- a/src/admin/policies.test.tsx +++ b/src/admin/policies.test.tsx @@ -7,17 +7,34 @@ import { within, } from "@testing-library/react"; import { adminApi, ApiError } from "./api"; -import { describeSeconds } from "./policies"; +import { describeSeconds, leaderPatternsFrom } from "./policies"; import { Settings } from "./settings"; type Call = { method: string; path: string; body: unknown; init: RequestInit }; type Reply = { status?: number; body?: unknown }; const POLICY = "/cloud/api/v1/organizations/o1/capture-policy"; +const LEADERS = "/cloud/api/v1/workspaces/w1/leaders"; +const ROSTER = [ + { name: "lead", agent_id: "a1" }, + { name: "review-1", agent_id: "a2" }, + { name: "ops-7", agent_id: "a3" }, +]; let calls: Call[] = []; let role: "owner" | "admin" | "member" = "owner"; let policy: { version: 1; revision: number; settings: Record }; let override: ((call: Call) => Reply | undefined) | null = null; +let leaderPatterns: string[] = []; + +/** Exact names only, plus a trailing `*`; enough for these tests. */ +const matched = (patterns: string[]) => + ROSTER.filter((agent) => + patterns.some((pattern) => + pattern.endsWith("*") + ? agent.name.startsWith(pattern.slice(0, -1)) + : agent.name === pattern, + ), + ); function respond(call: Call): Reply { const custom = override?.(call); @@ -30,6 +47,11 @@ function respond(call: Call): Reply { currentWorkspace: { id: "w1", name: "Primary" }, }, }; + if (call.path.endsWith("/leaders")) { + if (call.method === "PUT") + leaderPatterns = (call.body as { patterns: string[] }).patterns; + return { body: { leaders: matched(leaderPatterns), patterns: leaderPatterns } }; + } if (call.path.endsWith("/capture-policy")) { if (role === "member") return { status: 403, body: { error: "forbidden", message: "Forbidden" } }; @@ -55,6 +77,7 @@ beforeEach(() => { calls = []; role = "owner"; override = null; + leaderPatterns = ["lead", "review-*"]; policy = { version: 1, revision: 4, settings: { sharing_mode: "new" } }; vi.stubGlobal( "fetch", @@ -357,3 +380,145 @@ it("describes Oops windows in plain units", () => { expect(describeSeconds(86_400)).toBe("24 h"); expect(describeSeconds(3_661)).toBe("1 h 1 min 1 s"); }); + +const leaderBox = () => + within(screen.getByRole("form", { name: "Workspace leaders" })).getByRole( + "textbox", + { name: "Leader patterns" }, + ) as HTMLTextAreaElement; + +it("api: reads and replaces the workspace leader patterns", async () => { + expect(await adminApi.getWorkspaceLeaders("w/1")).toEqual({ + leaders: [ROSTER[0], ROSTER[1]], + patterns: ["lead", "review-*"], + }); + expect(calls[0]!.path).toBe("/cloud/api/v1/workspaces/w%2F1/leaders"); + + const saved = await adminApi.setWorkspaceLeaders("w1", ["lead"]); + expect(saved).toEqual({ leaders: [ROSTER[0]], patterns: ["lead"] }); + const put = calls[1]!; + expect(put.method).toBe("PUT"); + expect(put.path).toBe(LEADERS); + expect(put.body).toEqual({ patterns: ["lead"] }); + expect(header(put, "Content-Type")).toBe("application/json"); +}); + +it("shows the leader patterns and the agents they match", async () => { + render(); + expect( + await screen.findByRole("heading", { level: 2, name: "Workspace leaders" }), + ).toBeInTheDocument(); + await waitFor(() => expect(leaderBox().value).toBe("lead\nreview-*")); + const list = screen.getByRole("list", { name: "Currently matched leaders" }); + expect( + within(list) + .getAllByRole("listitem") + .map((item) => item.textContent), + ).toEqual(["lead", "review-1"]); + expect(screen.getByRole("button", { name: "Save leaders" })).toBeDisabled(); +}); + +it("members never read the workspace leaders", async () => { + role = "member"; + render(); + await screen.findByRole("heading", { level: 1, name: "Workspace" }); + expect(calls.some((call) => call.path === LEADERS)).toBe(false); +}); + +it("saves the trimmed, de-duplicated patterns and shows the new matches", async () => { + render(); + await waitFor(() => expect(leaderBox().value).toBe("lead\nreview-*")); + fireEvent.change(leaderBox(), { + target: { value: " lead \n\nops-*\nlead\n release-? \n" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Save leaders" })); + expect(await screen.findByText(/Leaders saved/)).toBeInTheDocument(); + const put = writes()[0]!; + expect(put.method).toBe("PUT"); + expect(put.path).toBe(LEADERS); + expect(put.body).toEqual({ patterns: ["lead", "ops-*", "release-?"] }); + expect(leaderBox().value).toBe("lead\nops-*\nrelease-?"); + const list = screen.getByRole("list", { name: "Currently matched leaders" }); + expect(within(list).getByText("ops-7")).toBeInTheDocument(); + expect(within(list).queryByText("review-1")).not.toBeInTheDocument(); +}); + +it("refuses a 65th pattern before sending anything", async () => { + render(); + await waitFor(() => expect(leaderBox().value).toBe("lead\nreview-*")); + fireEvent.change(leaderBox(), { + target: { + value: Array.from({ length: 65 }, (_, index) => `agent-${index}`).join("\n"), + }, + }); + fireEvent.click(screen.getByRole("button", { name: "Save leaders" })); + expect( + await screen.findByText("There are 65 patterns; a workspace can have at most 64."), + ).toBeInTheDocument(); + expect(writes()).toHaveLength(0); +}); + +it("refuses a pattern longer than 128 characters before sending anything", async () => { + render(); + await waitFor(() => expect(leaderBox().value).toBe("lead\nreview-*")); + fireEvent.change(leaderBox(), { + target: { value: `lead\n${"a".repeat(129)}` }, + }); + fireEvent.click(screen.getByRole("button", { name: "Save leaders" })); + expect( + await screen.findByText( + "Pattern 2 is 129 characters long; each pattern can be at most 128.", + ), + ).toBeInTheDocument(); + expect(writes()).toHaveLength(0); +}); + +it("says nothing was saved when the relay engine is unavailable", async () => { + override = (call) => + call.method === "PUT" && call.path === LEADERS + ? { + status: 502, + body: { + error: "workspace_leaders_unavailable", + message: "Relaycast could not be reached", + }, + } + : undefined; + render(); + await waitFor(() => expect(leaderBox().value).toBe("lead\nreview-*")); + fireEvent.change(leaderBox(), { target: { value: "lead" } }); + fireEvent.click(screen.getByRole("button", { name: "Save leaders" })); + expect( + await screen.findByText( + "The relay engine could not be reached, so nothing was saved: Relaycast could not be reached", + ), + ).toBeInTheDocument(); + expect(leaderBox().value).toBe("lead"); +}); + +it("shows Control's invalid_request message for refused patterns", async () => { + override = (call) => + call.method === "PUT" && call.path === LEADERS + ? { + status: 400, + body: { error: "invalid_request", message: "patterns must be strings" }, + } + : undefined; + render(); + await waitFor(() => expect(leaderBox().value).toBe("lead\nreview-*")); + fireEvent.change(leaderBox(), { target: { value: "lead" } }); + fireEvent.click(screen.getByRole("button", { name: "Save leaders" })); + expect( + await screen.findByText( + "Control refused the patterns, and nothing was saved: patterns must be strings", + ), + ).toBeInTheDocument(); +}); + +it("normalizes leader patterns like Control", () => { + expect(leaderPatternsFrom(" a \r\n\n b\na ")).toEqual(["a", "b"]); + expect(leaderPatternsFrom("")).toEqual([]); + expect(leaderPatternsFrom("x".repeat(128))).toEqual(["x".repeat(128)]); + // Duplicates collapse before the count is checked. + expect(leaderPatternsFrom(Array(65).fill("lead").join("\n"))).toEqual(["lead"]); +}); diff --git a/src/admin/policies.tsx b/src/admin/policies.tsx index c25ea1da..c6163353 100644 --- a/src/admin/policies.tsx +++ b/src/admin/policies.tsx @@ -1,9 +1,12 @@ import { useState, type FormEvent } from "react"; import { adminApi, ApiError } from "./api"; import { + MAX_LEADER_PATTERN_LENGTH, + MAX_LEADER_PATTERNS, MAX_OOPS_WINDOW_SECONDS, type CapturePolicy, type CaptureSettings, + type WorkspaceLeaders, } from "./contracts"; import { message, useLoad } from "./use-load"; @@ -515,3 +518,207 @@ function RadioGroup(props: { ); } + +/** + * One pattern per line: trimmed, blank lines dropped, duplicates collapsed in + * first-seen order (as Control stores them). A string is the reason the list + * is refused before anything is sent. + */ +export function leaderPatternsFrom(text: string): string[] | string { + const patterns = [ + ...new Set( + text + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean), + ), + ]; + const long = patterns.findIndex( + (pattern) => pattern.length > MAX_LEADER_PATTERN_LENGTH, + ); + if (long !== -1) + return `Pattern ${long + 1} is ${patterns[long]!.length} characters long; each pattern can be at most ${MAX_LEADER_PATTERN_LENGTH}.`; + if (patterns.length > MAX_LEADER_PATTERNS) + return `There are ${patterns.length} patterns; a workspace can have at most ${MAX_LEADER_PATTERNS}.`; + return patterns; +} + +export function WorkspaceLeadersSection(props: { workspaceId: string }) { + const { data, error, reload } = useLoad((signal) => + adminApi.getWorkspaceLeaders(props.workspaceId, signal), + ); + // A write's answer is shown until the next explicit reload. + const [written, setWritten] = useState(null); + const [saves, setSaves] = useState(0); + const [notice, setNotice] = useState(null); + const leaders = written ?? data; + + async function save(patterns: string[]) { + setNotice(null); + try { + const next = await adminApi.setWorkspaceLeaders(props.workspaceId, patterns); + setWritten(next); + setSaves((value) => value + 1); + setNotice({ + kind: "status", + text: "Leaders saved. Hosts pick up the change within about a minute.", + }); + } catch (failure) { + if (failure instanceof ApiError && failure.code === "invalid_request") { + setNotice({ + kind: "alert", + text: `Control refused the patterns, and nothing was saved: ${failure.message}`, + }); + return; + } + if ( + failure instanceof ApiError && + failure.code === "workspace_leaders_unavailable" + ) { + setNotice({ + kind: "alert", + text: `The relay engine could not be reached, so nothing was saved: ${failure.message}`, + }); + return; + } + setNotice({ kind: "alert", text: message(failure) }); + } + } + + return ( +
+

Workspace leaders

+

+ Agents whose direct messages the hosts in this workspace treat as + instructions from a lead. Hosts refresh the list about once a minute. +

+ {error && ( +

+ {leaders + ? `Couldn't load the latest leaders, so the ones shown may be out of date: ${message(error)}` + : message(error)}{" "} + +

+ )} + {!leaders && !error &&

Loading leaders…

} + {leaders && ( + setNotice((value) => (value?.kind === "status" ? null : value))} + /> + )} + {notice &&

{notice.text}

} +
+ ); +} + +function LeadersForm(props: { + leaders: WorkspaceLeaders; + onSave: (patterns: string[]) => Promise; + onEdit: () => void; +}) { + const saved = props.leaders.patterns.join("\n"); + const [draft, setDraft] = useState(saved); + const [busy, setBusy] = useState(false); + const [invalid, setInvalid] = useState(null); + const next = leaderPatternsFrom(draft); + const dirty = + typeof next === "string" || next.join("\n") !== props.leaders.patterns.join("\n"); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (typeof next === "string") { + setInvalid(next); + return; + } + setBusy(true); + try { + await props.onSave(next); + } finally { + setBusy(false); + } + } + + return ( +
void submit(event)} + aria-label="Workspace leaders" + > +
+ Leader patterns +

+ One agent name pattern per line, at most {MAX_LEADER_PATTERNS}{" "} + patterns of up to {MAX_LEADER_PATTERN_LENGTH} characters. A pattern + matches the whole agent name and is case-sensitive; *{" "} + matches any run of characters and ? matches one + character. A line without either is an exact agent name. Duplicate + lines are collapsed. +

+