diff --git a/packages/api/src/agents/route.test.ts b/packages/api/src/agents/route.test.ts index 89ef9c5b..42407413 100644 --- a/packages/api/src/agents/route.test.ts +++ b/packages/api/src/agents/route.test.ts @@ -444,33 +444,29 @@ describe('the built-in agent’s settings', () => { expect(setAgentGrants).toHaveBeenCalledWith({agentId: 'agent-1', connectionId: 'conn-1', actions: {send: false}}); }); - test('are not changed by a member a connection is shared with by name, nor by the organization’s owner on another member’s own', async () => { + test('are changed by anyone who uses the connection: a member it is shared with by name, and every member of one shared with everyone', async () => { getAgent.mockResolvedValue(Ok(builtIn)); const {handleSetAgentGrantsRoute} = await import('./route'); requireViewer.mockResolvedValue(Ok(member)); getConnectionWithCredential.mockResolvedValue(connectionOf('user-1', false)); - const sharedByName = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: false}})); - requireViewer.mockResolvedValue(Ok(owner)); - getConnectionWithCredential.mockResolvedValue(connectionOf('user-2', false)); - const othersOwn = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: false}})); + const sharedByName = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: true}})); + requireViewer.mockResolvedValue(Ok({...member, userId: 'user-3'})); + getConnectionWithCredential.mockResolvedValue(connectionOf('user-2', true)); + const sharedWithEveryone = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: true}})); - expect(sharedByName.unwrapErr().kind).toBe('forbidden'); - expect(othersOwn.unwrapErr().kind).toBe('forbidden'); - expect(setAgentGrants).not.toHaveBeenCalled(); + expect(sharedByName.isOk()).toBe(true); + expect(sharedWithEveryone.isOk()).toBe(true); + expect(setAgentGrants).toHaveBeenCalledTimes(2); }); - test('are changed on a connection shared with everyone by whoever’s it is and the organization’s owner alone', async () => { + test('are not changed on a connection the person doesn’t use, the organization’s owner included', async () => { getAgent.mockResolvedValue(Ok(builtIn)); - getConnectionWithCredential.mockResolvedValue(connectionOf('user-2', true)); + requireViewer.mockResolvedValue(Ok(owner)); + getConnectionWithCredential.mockResolvedValue(Ok(null)); const {handleSetAgentGrantsRoute} = await import('./route'); - const byOrgOwner = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: false}})); - requireViewer.mockResolvedValue(Ok(member)); - const byConnectionOwner = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: false}})); - requireViewer.mockResolvedValue(Ok({...member, userId: 'user-3'})); - const byAnotherMember = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: false}})); + const othersOwn = await handleSetAgentGrantsRoute(makeRequest(params, {actions: {send: true}})); - expect(byOrgOwner.isOk()).toBe(true); - expect(byConnectionOwner.isOk()).toBe(true); - expect(byAnotherMember.unwrapErr().kind).toBe('forbidden'); + expect(othersOwn.unwrapErr().kind).toBe('not_found'); + expect(setAgentGrants).not.toHaveBeenCalled(); }); }); diff --git a/packages/api/src/agents/route.ts b/packages/api/src/agents/route.ts index 49d9422b..57883df2 100644 --- a/packages/api/src/agents/route.ts +++ b/packages/api/src/agents/route.ts @@ -19,7 +19,7 @@ import {listMemberNames} from '@proxy/db/organization'; import type {MemberViewer} from '@proxy/db/viewer'; import {findAgentProvider} from '@proxy/utils/agent-providers'; -import {requireConnection, requireManaged, type StoredConnectionRow} from '../connections/managed'; +import {requireConnection, type StoredConnectionRow} from '../connections/managed'; import {refuseUnavailable, unavailableActions} from '../connections/unavailable'; import type {AuthenticatedRequest} from '../server/middleware/require-auth'; import {parseActionChanges, requireIntegration} from '../utils/connection-actions'; @@ -179,7 +179,9 @@ export function handleShareAgentRoute(request: AuthenticatedRequest): Promise> { return Do(async ($) => { @@ -196,12 +198,12 @@ export function handleSetAgentGrantsRoute(request: AuthenticatedRequest): Promis }); } -// The connection the viewer may give the agent settings on: for the built-in agent, one whose -// defaults they change; for any other, one it reaches, of an agent they change. +// The connection the viewer may give the agent settings on: for the built-in agent, one they use; +// for any other, one it reaches, of an agent they change. function requireGrantable(viewer: OrgViewer, agent: AgentRow, connectionId: string): Promise> { return Do(async ($) => { if (isBuiltIn(agent)) { - return $(await requireManaged(viewer, connectionId)); + return $(await requireConnection(viewer, connectionId)); } if (!managesAgent(viewer, agent)) { return $(Err(ApiErr.forbidden())); diff --git a/packages/web/src/components/access-grid.test.tsx b/packages/web/src/components/access-grid.test.tsx index 6f83e472..416332a5 100644 --- a/packages/web/src/components/access-grid.test.tsx +++ b/packages/web/src/components/access-grid.test.tsx @@ -5,7 +5,7 @@ import type {Action} from '@proxy/integrations'; import {afterEach, describe, expect, mock, test} from 'bun:test'; import {cleanup, fireEvent, render, screen, waitFor, within} from '@testing-library/react'; import {createMemoryRouter, RouterProvider} from 'react-router'; -import {AccessGrid, type GridAgent} from '@/components/access-grid'; +import {AccessGrid, DEFAULT_LOCKED, type GridAgent} from '@/components/access-grid'; afterEach(() => { cleanup(); @@ -40,8 +40,8 @@ function agent(id: string, name: string): AgentLogin { } // Claude, which may send though the default says no, and Scout, which follows every default. -const claude: GridAgent = {agent: agent('agent-1', 'Claude'), own: {send: true}, mayChange: true}; -const scout: GridAgent = {agent: agent('agent-2', 'Scout'), own: {}, mayChange: true}; +const claude: GridAgent = {agent: agent('agent-1', 'Claude'), own: {send: true}, setBy: null}; +const scout: GridAgent = {agent: agent('agent-2', 'Scout'), own: {}, setBy: null}; function renderGrid(props: Partial[0]> = {}) { const onChangeDefaults = mock(async (_actions: Record) => {}); @@ -59,7 +59,7 @@ function renderGrid(props: Partial[0]> = {}) { agents={[claude, scout]} unavailable={[]} signInNeeded={false} - mayChangeDefaults + defaultsSetBy={null} onChangeDefaults={onChangeDefaults} onChangeAgent={onChangeAgent} {...props} @@ -272,12 +272,43 @@ describe('AccessGrid', () => { } }); - test('someone who may change neither the defaults nor an agent sees the grid and changes nothing', () => { - renderGrid({mayChangeDefaults: false, agents: [{...claude, mayChange: false}, scout]}); + test('someone who may change neither the defaults nor an agent sees those boxes as they are, unfaded, and changes nothing', () => { + const {onChangeDefaults, onChangeAgent} = renderGrid({ + defaultsSetBy: 'Dana', + agents: [{...claude, setBy: 'Dana'}, scout], + }); + + expect(box('Read by default').hasAttribute('data-readonly')).toBe(true); + expect(box('Read by default').hasAttribute('data-disabled')).toBe(false); + expect(box('Read for Claude').hasAttribute('data-readonly')).toBe(true); + expect(box('Read for Scout').hasAttribute('data-readonly')).toBe(false); + fireEvent.click(box('Read by default')); + fireEvent.click(box('Read for Claude')); + expect(ticked('Read by default')).toBe('true'); + expect(onChangeDefaults).not.toHaveBeenCalled(); + expect(onChangeAgent).not.toHaveBeenCalled(); + }); + + test('a column the person may not change has a lock by its name, and its boxes say on hover who sets them', async () => { + renderGrid({defaultsSetBy: 'Dana', agents: [{...claude, setBy: 'Dana'}, scout]}); + + expect(screen.getAllByLabelText(DEFAULT_LOCKED)).toHaveLength(1); + expect(screen.getAllByLabelText('Set by Dana')).toHaveLength(1); + fireEvent.focus(box('Read by default')); + expect(await screen.findByText('Set by Dana')).toBeDefined(); + fireEvent.blur(box('Read by default')); - expect(box('Read by default').hasAttribute('data-disabled')).toBe(true); - expect(box('Read for Claude').hasAttribute('data-disabled')).toBe(true); - expect(box('Read for Scout').hasAttribute('data-disabled')).toBe(false); + fireEvent.focus(box('Send for Claude, its own setting')); + expect(await screen.findByText('Overwrites default to on · Set by Dana')).toBeDefined(); + }); + + test('with only their own agents’ columns to change, Enable all turns those on and leaves the defaults', async () => { + const {onChangeDefaults, onChangeAgent} = renderGrid({all: true, defaultsSetBy: 'Dana'}); + + fireEvent.click(screen.getByRole('button', {name: 'Enable all'})); + + await waitFor(() => expect(onChangeAgent).toHaveBeenCalledTimes(2)); + expect(onChangeDefaults).not.toHaveBeenCalled(); }); test('with no agent reaching the connection, there is the default alone, and it says so', () => { diff --git a/packages/web/src/components/access-grid.tsx b/packages/web/src/components/access-grid.tsx index 5efa5ce0..483c4804 100644 --- a/packages/web/src/components/access-grid.tsx +++ b/packages/web/src/components/access-grid.tsx @@ -1,6 +1,7 @@ import type {AgentLogin} from '@proxy/contracts/agents'; import type {Action, OwnSettings} from '@proxy/integrations'; -import {useState} from 'react'; +import {LockIcon} from 'lucide-react'; +import {type ReactNode, useState} from 'react'; import {Link} from 'react-router'; import {AgentLogo} from '@/components/brand-logo'; import {Checkbox} from '@proxy/ui/components/checkbox'; @@ -10,8 +11,11 @@ import {cn} from '@proxy/ui/lib/utils'; import {groupsOf} from '@/lib/access'; import {useOrgSlug} from '@/hooks/use-org'; -/** An agent that reaches the connection, as a column: its own settings there, and whether the person may change them. */ -export type GridAgent = {agent: AgentLogin; own: OwnSettings; mayChange: boolean}; +/** + * An agent that reaches the connection, as a column: its own settings there, and who may change + * them, by name, where the person may not; null where they may. + */ +export type GridAgent = {agent: AgentLogin; own: OwnSettings; setBy: string | null}; type Props = { actions: Action[]; @@ -24,8 +28,8 @@ type Props = { unavailable: string[]; // The connection has no sign-in at all yet, so none of its actions is covered. signInNeeded: boolean; - // The defaults are the person's to set; else they see them. - mayChangeDefaults: boolean; + // Who may change the defaults, by name, where the person may not, who sees them; null where they may. + defaultsSetBy: string | null; // Turns default actions on or off. onChangeDefaults: (actions: Record) => Promise; // Gives an agent settings of its own for actions; null returns one to the default. @@ -67,7 +71,7 @@ export function AccessGrid({ agents, unavailable, signInNeeded, - mayChangeDefaults, + defaultsSetBy, onChangeDefaults, onChangeAgent, unlinked = false, @@ -75,6 +79,7 @@ export function AccessGrid({ all = false, }: Props) { const org = useOrgSlug(); + const mayChangeDefaults = defaultsSetBy === null; // What a box shows while its change is saved and the page's data loaded again, by column and // action. const [pending, setPending] = useState>>({}); @@ -108,7 +113,7 @@ export function AccessGrid({ // Every action the sign-in allows, and the columns the person may change: the defaults where // they are theirs to set, and each agent that is. const available = actions.filter((action) => !isUnavailable(action.id)).map(({id}) => id); - const changeable = agents.filter((column) => column.mayChange); + const changeable = agents.filter((column) => column.setBy === null); const everythingOn = available.length > 0 && available.every( @@ -177,7 +182,8 @@ export function AccessGrid({ void change( available.map((id) => key(DEFAULT, id)), @@ -192,7 +198,8 @@ export function AccessGrid({ isOn(column, id))} - disabled={!column.mayChange || available.length === 0} + setBy={column.setBy} + disabled={available.length === 0} onChange={(next) => void change( available.map((id) => key(column.agent.id, id)), @@ -237,7 +244,8 @@ export function AccessGrid({ void change([key(DEFAULT, action.id)], next, () => onChangeDefaults({[action.id]: next}), @@ -251,7 +259,8 @@ export function AccessGrid({ label={`${action.label} for ${column.agent.name}`} checked={isOn(column, action.id)} own={isOwn(column, action.id)} - disabled={!column.mayChange || isUnavailable(action.id)} + setBy={column.setBy} + disabled={isUnavailable(action.id)} onChange={(next) => void change([key(column.agent.id, action.id)], next, () => onChangeAgent(column.agent.id, {[action.id]: ownSetting(action.id, next)}), @@ -295,12 +304,13 @@ export function AccessGrid({ {group.name ?? 'Action'} - Default + - {agents.map(({agent}) => ( + {agents.map(({agent, setBy}) => ( @@ -324,30 +334,79 @@ export function AccessGrid({ /** * The grid's column names on their own, for a page that heads an ungrouped grid itself (`headed`), * as an agent's page does with the connection's name: Default and each agent by name, as wide as - * the columns under them, at the end of the heading's line, and no taller than it. + * the columns under them, at the end of the heading's line, and no taller than it, each with a lock + * where the person may not change it. */ -export function AccessGridColumns({agents}: {agents: AgentLogin[]}) { +export function AccessGridColumns({ + agents, + defaultsSetBy, +}: { + agents: GridAgent[]; + defaultsSetBy: string | null; +}) { return ( - Default - {agents.map((agent) => ( + + + + {agents.map(({agent, setBy}) => ( - + ))} ); } +// A column's name with a lock before it where the person may not change the column, saying on +// hover why (`says`). +function Locked({says, children}: {says: string | null; children: ReactNode}) { + if (says === null) { + return children; + } + return ( + + + } + > + + {children} + + {says} + + ); +} + +// What the lock by Default says: only whoever shares the connection changes it, Default being what +// every agent on it follows, theirs too. +export const DEFAULT_LOCKED = 'Only the person sharing this connection can update the default'; + +function DefaultHeading({setBy}: {setBy: string | null}) { + return Default; +} + // An agent's column heading: its logo over its name, a link to its page; with `to` null, on the // agent's own page, its name alone, the page being about nothing else. -function AgentHeading({agent, to}: {agent: AgentLogin; to: string | null}) { - if (to === null) { - return ( - +function AgentHeading({ + agent, + setBy, + to, +}: { + agent: AgentLogin; + setBy: string | null; + to: string | null; +}) { + const name = ( + + {agent.name} - ); + + ); + if (to === null) { + return name; } return ( - {agent.name} + {name} ); } // One box of the grid, centered in its column; an agent's own setting sits on a filled square, -// which says on hover what it does to the default. +// which says on hover what it does to the default. A box in a column the person may not change +// (`setBy`) reads as clearly as one they may, its state being what they came to see, and says on +// hover who changes it; one with nothing to set (`disabled`), as an action the sign-in didn't +// cover, is faded. function Box({ label, checked, indeterminate = false, own = false, + setBy, disabled, onChange, }: { @@ -375,19 +438,27 @@ function Box({ checked: boolean; indeterminate?: boolean; own?: boolean; + setBy: string | null; disabled: boolean; onChange: (next: boolean) => void; }) { + const locked = setBy !== null && !disabled; const box = ( onChange(next)} /> ); - if (!own) { + const says = [ + ...(own ? [`Overwrites default to ${checked ? 'on' : 'off'}`] : []), + ...(locked ? [`Set by ${setBy}`] : []), + ]; + if (says.length === 0) { return {box}; } return ( @@ -395,14 +466,17 @@ function Box({ } > {box} - Overwrites default to {checked ? 'on' : 'off'} + {says.join(' · ')} ); } diff --git a/packages/web/src/lib/orgs.ts b/packages/web/src/lib/orgs.ts index abf2cdda..9d56240f 100644 --- a/packages/web/src/lib/orgs.ts +++ b/packages/web/src/lib/orgs.ts @@ -1,7 +1,7 @@ import type {AgentLogin} from '@proxy/contracts/agents'; import type {Connection} from '@proxy/contracts/connections'; import type {Me} from '@proxy/contracts/me'; -import type {Org} from '@proxy/contracts/orgs'; +import type {Member, Org} from '@proxy/contracts/orgs'; import {findIntegration} from '@proxy/integrations'; import {isBuiltInAgent} from '@/lib/access'; @@ -49,30 +49,53 @@ export function manages(human: Human, item: Managed): boolean { } /** - * Whether the person may change an agent's settings on a connection, as the api decides it: the - * built-in agent's where they change the connection's defaults, any other agent's where they change - * the agent. + * Whether the person may change an agent's settings on the connections they see, as the api decides + * it: the built-in agent's on any of them, which hold for everyone's Chat there, since a connection + * shared with them is theirs to use as they see fit; any other agent's where they change the agent. */ -export function managesAgentOn( - human: Human, - agent: AgentLogin, - connection: Pick, -): boolean { - if (isBuiltInAgent(agent)) { - return manages(human, connection); +export function managesAgentSettings(human: Human, agent: AgentLogin): boolean { + return isBuiltInAgent(agent) || manages(human, agent); +} + +// "Sam", "Sam or Alex", "Sam, Alex or Kim": who may do something, in a sentence. +function eitherOf(names: string[]): string { + if (names.length < 2) { + return names[0] ?? ''; } - return manages(human, agent); + return `${names.slice(0, -1).join(', ')} or ${names.at(-1)}`; +} + +// The organization's owners by name, leaving out whoever is named already. +function ownersBeside(members: Member[], named: string | null): string[] { + return members + .filter((member) => member.role === 'owner' && member.userId !== named) + .map((member) => member.name ?? member.email); } /** - * Whose a connection is, at the start of a line: "You", a member by their name or address, or "A - * former member" for one no longer in the organization. + * Who may change a connection's defaults, by name, for a person who may not (`manages`): whoever's + * it is, and for one shared with every member, the organization's owner beside them. */ -export function ownerOf(connection: Connection, human: Human): string { - if (connection.ownerUserId === human.user.id) { - return 'You'; +export function connectionSetBy( + connection: Pick, + members: Member[], +): string { + const owner = connection.owner === null ? [] : [connection.owner]; + if (!connection.sharedWithEveryone) { + return eitherOf(owner.length > 0 ? owner : ['A former member']); } - return connection.owner ?? 'A former member'; + const names = [...owner, ...ownersBeside(members, connection.ownerUserId)]; + return eitherOf(names.length > 0 ? names : ['The organization’s owner']); +} + +/** + * Who may change a shared agent's settings, by name, for a person who may not + * (`managesAgentSettings`): whoever made it and the organization's owner. + */ +export function agentSetBy(agent: AgentLogin, members: Member[]): string { + const maker = agent.createdBy === null ? [] : [agent.createdBy]; + const names = [...maker, ...ownersBeside(members, agent.createdById)]; + return eitherOf(names.length > 0 ? names : ['The organization’s owner']); } /** diff --git a/packages/web/src/pages/agent-page.tsx b/packages/web/src/pages/agent-page.tsx index 2d88abe6..6e9f51ce 100644 --- a/packages/web/src/pages/agent-page.tsx +++ b/packages/web/src/pages/agent-page.tsx @@ -44,7 +44,13 @@ import {cn} from '@proxy/ui/lib/utils'; import {formatDate} from '@/lib/format'; import {chosenTab, type PageTab} from '@/lib/page-tabs'; import {describeApiError, describeFetchError} from '@/lib/loader-utils'; -import {hasOtherPeople, manages, managesAgentOn} from '@/lib/orgs'; +import { + agentSetBy, + connectionSetBy, + hasOtherPeople, + manages, + managesAgentSettings, +} from '@/lib/orgs'; import type {agentLoader} from '@/loaders'; import {useOrgSlug} from '@/hooks/use-org'; @@ -85,6 +91,8 @@ function AgentDetail({id}: {id: string}) { const mayChange = manages(human, agent); // A shared agent reaches the connections shared with everyone alone. const reachable = connections.filter((connection) => reaches(agent, connection)); + // Who changes the agent's settings, where the person doesn't. + const setBy = managesAgentSettings(human, agent) ? null : agentSetBy(agent, members); const provider = findAgentProvider(agent.providerId); const company = provider?.company ?? agent.providerId; // A built-in agent has no login to hand out: it runs in Personal Agent Proxy itself. @@ -156,13 +164,15 @@ function AgentDetail({id}: {id: string}) { {tab === 'permissions' && (

- {permissionsIntro(agent, mayChange, builtIn)} + {permissionsIntro(agent, builtIn, setBy)}

managesAgentOn(human, agent, connection)} - setsDefaults={(connection) => manages(human, connection)} + setBy={setBy} + defaultsSetBy={(connection) => + manages(human, connection) ? null : connectionSetBy(connection, members) + } onChange={(connectionId, actions) => apply(setAgentGrants(org, agent.id, connectionId, actions)) } @@ -289,31 +299,30 @@ function McpClients({ } // What the Permissions tab says first: that the agent follows each connection's default unless it -// has a setting of its own, how many it has, and who changes them: for the built-in agent, whoever -// changes each connection's defaults; for another, where the person doesn't, who does. -function permissionsIntro(agent: AgentLogin, mayChange: boolean, builtIn: boolean): string { +// has a setting of its own, how many it has, and who changes them: for the built-in agent, anyone +// who uses a connection, for everyone's Chat on it; for another, where the person doesn't, who does. +function permissionsIntro(agent: AgentLogin, builtIn: boolean, setBy: string | null): string { const own = agent.grants.length; return [ `${agent.name} gets what each connection’s Default says, unless a box of its own says otherwise.`, ...(own > 0 ? [`It has ${own} of its own.`] : []), ...(builtIn - ? ['Whoever changes a connection’s defaults changes them there.'] - : mayChange + ? ['Anyone who uses a connection changes them there, for everyone’s Chat on it.'] + : setBy === null ? [] - : ['Whoever made it and the organization’s owner change them.']), + : [`${setBy} changes them.`]), ].join(' '); } type GridProps = { agent: AgentLogin; connections: Connection[]; - // Whether the person may change the agent's settings on a connection; else they see them: a - // shared agent's by a member who only sees it, the built-in agent's where the connection isn't - // theirs to change. - mayChange: (connection: Connection) => boolean; - // Whether the person may change a connection's defaults, shown beside the agent's own: the - // connection is theirs to change too. - setsDefaults: (connection: Connection) => boolean; + // Who may change the agent's settings, by name, where the person may not, who sees them: a + // shared agent's by a member who only sees it. Null where they may. + setBy: string | null; + // Who may change a connection's defaults, shown beside the agent's own, where the person may + // not; null where the connection is theirs to change too. + defaultsSetBy: (connection: Connection) => string | null; onChange: (connectionId: string, actions: Record) => Promise; onChangeDefaults: (connectionId: string, actions: Record) => Promise; }; @@ -326,8 +335,8 @@ type GridProps = { function ConnectionsAccess({ agent, connections, - mayChange, - setsDefaults, + setBy, + defaultsSetBy, onChange, onChangeDefaults, }: GridProps) { @@ -399,6 +408,7 @@ function ConnectionsAccess({ {groups.map(({connection, integration, label, own, actions}) => { const open = filtering || opened.has(connection.id); const grouped = actions.some((action) => action.group !== undefined); + const columns = [{agent, own, setBy}]; return (
{/* The connection's name is the grid's heading, as tall open as folded: open, the @@ -420,16 +430,18 @@ function ConnectionsAccess({ {label} - {open && !grouped && } + {open && !grouped && ( + + )} {open && ( onChangeDefaults(connection.id, changes)} onChangeAgent={(_agentId, changes) => onChange(connection.id, changes)} unlinked diff --git a/packages/web/src/pages/connection-page.test.tsx b/packages/web/src/pages/connection-page.test.tsx index dc12c631..c486b705 100644 --- a/packages/web/src/pages/connection-page.test.tsx +++ b/packages/web/src/pages/connection-page.test.tsx @@ -212,7 +212,7 @@ describe('ConnectionPage', () => { ).toBe('true'); }); - test('Chat, which the Chat page’s personas act through, has a column on every connection, changed by whoever changes its defaults', async () => { + test('Chat, which the Chat page’s personas act through, has a column on every connection, changed by anyone who uses it, though Default stays its owner’s', async () => { const chat: AgentLogin = { ...claude, id: 'agent-chat', @@ -232,11 +232,11 @@ describe('ConnectionPage', () => { 'Chat', ]); expect( - screen.getByRole('checkbox', {name: 'Send for Chat'}).hasAttribute('data-disabled'), + screen.getByRole('checkbox', {name: 'Send for Chat'}).hasAttribute('data-readonly'), ).toBe(false); cleanup(); - // Dana's mailbox, shared with the person by name: Dana's to change, Chat's settings there too. + // Dana's mailbox, shared with the person by name: Default is Dana's to change, Chat's settings the person's too. const danas: Connection = { ...mailbox, ownerUserId: 'user-2', @@ -247,8 +247,16 @@ describe('ConnectionPage', () => { renderConnectionPage('/acme/connections/conn-1', danas, [chat]); expect( - (await screen.findByRole('checkbox', {name: 'Send for Chat'})).hasAttribute('data-disabled'), + (await screen.findByRole('checkbox', {name: 'Send for Chat'})).hasAttribute('data-readonly'), + ).toBe(false); + expect( + screen.getByRole('checkbox', {name: 'Send by default'}).hasAttribute('data-readonly'), ).toBe(true); + expect( + screen.getByText( + 'Dana sets Default here. You set Chat’s column, for everyone’s Chat on it, beyond Default if you like.', + ), + ).toBeDefined(); }); test('the address opens the page on the tab it names', async () => { diff --git a/packages/web/src/pages/connection-page.tsx b/packages/web/src/pages/connection-page.tsx index 7ee8284e..45960e03 100644 --- a/packages/web/src/pages/connection-page.tsx +++ b/packages/web/src/pages/connection-page.tsx @@ -1,5 +1,5 @@ import type {Connection} from '@proxy/contracts/connections'; -import {ListRestartIcon, UnplugIcon} from 'lucide-react'; +import {ListRestartIcon, LockIcon, UnplugIcon} from 'lucide-react'; import type {FetchError} from '@proxy/utils'; import {useState} from 'react'; import {useNavigate, useSearchParams} from 'react-router'; @@ -28,7 +28,14 @@ import {FileBrowser} from '@/components/file-browser'; import {SandboxList} from '@/components/sandbox-list'; import {SuccessLine} from '@/components/success-line'; import {VaultEntries} from '@/components/vault-entries'; -import {connectionTitle, defaultActions, integrationOf, ownSettings, reaches} from '@/lib/access'; +import { + connectionTitle, + defaultActions, + integrationOf, + isBuiltInAgent, + ownSettings, + reaches, +} from '@/lib/access'; import {useHuman} from '@/hooks/use-human'; import {reachedRepositories} from '@/lib/github'; import {useLoaded} from '@/hooks/use-loaded'; @@ -36,7 +43,14 @@ import {useReload} from '@/hooks/use-reload'; import {signInPath} from '@/lib/integrations'; import {chosenTab, type PageTab} from '@/lib/page-tabs'; import {describeApiError, describeFetchError} from '@/lib/loader-utils'; -import {actsAs, hasOtherPeople, manages, managesAgentOn, ownerOf} from '@/lib/orgs'; +import { + actsAs, + agentSetBy, + connectionSetBy, + hasOtherPeople, + manages, + managesAgentSettings, +} from '@/lib/orgs'; import type {connectionLoader} from '@/loaders'; import {useOrgSlug} from '@/hooks/use-org'; @@ -80,18 +94,20 @@ function ConnectionDetail() { // The agents that reach it, a column each of its permissions: the person's own, the shared ones // where every member has it, theirs to change where the agent is, and Chat, the one the Chat - // page's personas all act through, theirs to change where the connection is. + // page's personas all act through, theirs to change on any connection they use, for everyone's + // Chat there. Where a column isn't theirs, it names who changes it. const columns: GridAgent[] = agents .filter((agent) => agent.revokedAt === null && reaches(agent, connection)) .map((agent) => ({ agent, own: ownSettings(agent, connection.id), - mayChange: managesAgentOn(human, agent, connection), + setBy: managesAgentSettings(human, agent) ? null : agentSetBy(agent, members), })); const activeOrg = human.org; // One's own connection is one's to change and share, and one shared with every member is the // organization's owner's too. Anyone else it is shared with uses it as it is. const mayChange = manages(human, connection); + const defaultsSetBy = mayChange ? null : connectionSetBy(connection, members); // A vault's entries are kept here, so no provider sees anyone. const actingAs = integration.native ? null : actsAs(connection, human); // A vault a member made is deleted, with its entries, where another connection is disconnected. @@ -127,11 +143,8 @@ function ConnectionDetail() { {id: 'activity', label: 'Recent activity'}, ]; const tab = chosenTab(tabs, searchParams); - const about = permissionsIntro(connection, { - custom: integration.custom === true, - mayChange, - owner: ownerOf(connection, human), - }); + const about = permissionsIntro(connection, integration.custom === true); + const locked = lockedNote(defaultsSetBy, columns); const removal = integration.made ? { verb: 'Delete', @@ -261,6 +274,14 @@ function ConnectionDetail() { {tab === 'permissions' && (

{about}

+ {locked && ( +

+ + + + {locked} +

+ )} {integration.disclosure && (

{integration.disclosure}

)} @@ -273,7 +294,7 @@ function ConnectionDetail() { agents={columns} unavailable={connection.unavailable} signInNeeded={connection.signInNeeded} - mayChangeDefaults={mayChange} + defaultsSetBy={defaultsSetBy} all onChangeDefaults={async (actions) => { const result = await setConnectionDefaults(org, connection.id, actions); @@ -359,16 +380,33 @@ function describeRefreshError(error: FetchError): string { return describeFetchError(error); } -// What the Permissions tab says first: what the grid's columns are, whose agents those are, and -// who sets the defaults. -function permissionsIntro( - connection: Connection, - about: {custom: boolean; mayChange: boolean; owner: string}, -): string { +// What the Permissions tab says first: what the grid's columns are, and whose agents those are. +function permissionsIntro(connection: Connection, custom: boolean): string { const whose = connection.shared ? 'The agents of everyone who uses it' : 'Your agents'; return [ `${whose} get what Default says, unless a box of the agent’s own says otherwise.`, - ...(about.custom ? ['These are the server’s tools, as it last listed them.'] : []), - ...(about.mayChange ? [] : [`${about.owner} sets Default.`]), + ...(custom ? ['These are the server’s tools, as it last listed them.'] : []), ].join(' '); } + +// For someone a connection is shared with, who doesn't change it: who sets Default, and what they +// set themselves, beyond Default if they like: Chat's column, which holds for everyone's Chat on +// the connection, and their own agents'. Null where the defaults are theirs to set. +function lockedNote(defaultsSetBy: string | null, columns: GridAgent[]): string | null { + if (defaultsSetBy === null) { + return null; + } + const sets = `${defaultsSetBy} sets Default here.`; + const chat = columns.some(({agent}) => isBuiltInAgent(agent)); + const yours = columns.some(({agent, setBy}) => setBy === null && !isBuiltInAgent(agent)); + if (chat && yours) { + return `${sets} You set Chat’s column, for everyone’s Chat on it, and your own agents’, beyond Default if you like.`; + } + if (chat) { + return `${sets} You set Chat’s column, for everyone’s Chat on it, beyond Default if you like.`; + } + if (yours) { + return `${sets} You set your own agents’ columns, beyond Default if you like.`; + } + return `${sets} Ask them to change what agents may do with it.`; +}