Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 148 additions & 9 deletions client/src/components/SidePanel/Schedules/Consent.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { useState, useId } from 'react';
import { Button, Input, Label, Spinner, OGDialog, OGDialogTemplate } from '@librechat/client';
import type { ScheduleMCPConsentView } from 'librechat-data-provider';
import {
Button,
Input,
Label,
Spinner,
Checkbox,
OGDialog,
OGDialogTemplate,
} from '@librechat/client';
import type { ScheduleMCPConsentView, ScheduledMCPTarget } from 'librechat-data-provider';
import type { MutableRefObject } from 'react';
import {
useScheduleMCPConsent,
Expand All @@ -23,6 +31,44 @@ const messageKeys = {
success: 'com_ui_schedule_consent_confirmed',
} as const;

/** Every tool on offer for a server, whichever agents selected it. */
function offeredTools(target: ScheduledMCPTarget): string[] {
return [...new Set(target.permittedTools.flatMap((selection) => selection.tools))].sort();
}

/** The owner's starting point: what the stored grant already allows and is still on offer. */
function initialChoice(data: ScheduleMCPConsentView): Record<string, string[]> {
return Object.fromEntries(
data.targets.map((target) => {
const offered = offeredTools(target);
const allowed = data.allowed[target.resource.serverName] ?? [];
return [target.resource.serverName, offered.filter((tool) => allowed.includes(tool))];
}),
);
}

/**
* The owner's ticks, kept to what is on offer now. The offer is read again while the dialog
* is open, and a server or tool the agents dropped has no box left to untick.
*/
function currentChoice(
data: ScheduleMCPConsentView,
edited: Record<string, string[]> | null,
): Record<string, string[]> {
const initial = initialChoice(data);
if (!edited) return initial;
return Object.fromEntries(
data.targets.map((target) => {
const { serverName } = target.resource;
const offered = offeredTools(target);
return [
serverName,
(edited[serverName] ?? initial[serverName]).filter((tool) => offered.includes(tool)),
];
}),
);
}

export default function Consent({
canConfirm = true,
id,
Expand All @@ -42,15 +88,30 @@ export default function Consent({
const { confirm, revoke } = useScheduleMCPConsentMutations(id);
const [hours, setHours] = useState(1);
const [message, setMessage] = useState<'success' | 'revoked' | 'error' | null>(null);
/** Null until the owner changes a box, so a refetch cannot overwrite a choice in progress. */
const [edited, setEdited] = useState<Record<string, string[]> | null>(null);
const busy = confirm.isLoading || revoke.isLoading || query.isFetching;
const data: ScheduleMCPConsentView | undefined = query.data;
const choosing = canConfirm && data?.offer != null;
const choice = data ? currentChoice(data, edited) : {};
const chosenCount = Object.values(choice).reduce((count, tools) => count + tools.length, 0);
const setTools = (serverName: string, tools: string[]) =>
setEdited({ ...choice, [serverName]: tools });
const commit = () => {
if (!data?.offer) return;
if (!data?.offer || chosenCount === 0) return;
setMessage(null);
confirm.mutate(
{ offerDigest: data.offer.digest, expectedRevision: data.revision, lifetimeHours: hours },
{
onSuccess: () => setMessage('success'),
offerDigest: data.offer.digest,
expectedRevision: data.revision,
lifetimeHours: hours,
allow: choice,
},
{
onSuccess: () => {
setEdited(null);
setMessage('success');
},
onError: () => setMessage('error'),
},
);
Expand Down Expand Up @@ -122,11 +183,21 @@ export default function Consent({
})}
</p>
)}
{target.permittedTools.map((selection) => (
<p className="text-text-secondary text-xs" key={selection.agentId}>
{selection.agentId}: {selection.tools.join(', ')}
{choosing ? (
<ToolChoice
serverName={target.resource.serverName}
offered={offeredTools(target)}
chosen={choice[target.resource.serverName] ?? []}
disabled={busy}
onChange={(tools) => setTools(target.resource.serverName, tools)}
/>
) : (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_allowed', {
tools: (data.allowed[target.resource.serverName] ?? []).join(', '),
})}
</p>
))}
)}
</li>
))}
</ul>
Expand All @@ -146,13 +217,19 @@ export default function Consent({
onClick={commit}
disabled={
busy ||
chosenCount === 0 ||
!Number.isInteger(hours) ||
hours < 1 ||
hours > data.offer.maxLifetimeHours
}
>
{localize('com_ui_schedule_consent_confirm')}
</Button>
{chosenCount === 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_none_selected')}
</p>
)}
</>
)}
{data.revision && data.state !== 'revoked' && (
Expand All @@ -173,3 +250,65 @@ export default function Consent({
</OGDialog>
);
}

/** One server's tools: a box for the whole server and one per tool. Unchecked means refused. */
function ToolChoice({
serverName,
offered,
chosen,
disabled,
onChange,
}: {
serverName: string;
offered: string[];
chosen: string[];
disabled: boolean;
onChange: (tools: string[]) => void;
}) {
const localize = useLocalize();
const groupId = useId();
/** Checked only when every tool is: the shared box has no partly-selected appearance. */
const all = offered.length > 0 && offered.every((tool) => chosen.includes(tool));
return (
<fieldset className="mt-2 space-y-1" disabled={disabled}>
<div className="flex items-center gap-2">
<Checkbox
id={`${groupId}-all`}
checked={all}
disabled={disabled}
aria-label={localize('com_ui_schedule_consent_allow_server', { server: serverName })}
onCheckedChange={(checked) => onChange(checked === true ? offered : [])}
/>
<Label htmlFor={`${groupId}-all`} className="text-xs">
{localize('com_ui_schedule_consent_allow_server', { server: serverName })}
</Label>
</div>
<ul className="space-y-1 pl-6">
{offered.map((tool) => (
<li key={tool} className="flex items-center gap-2">
<Checkbox
id={`${groupId}-${tool}`}
checked={chosen.includes(tool)}
disabled={disabled}
aria-labelledby={`${groupId}-${tool}-label`}
onCheckedChange={(checked) =>
onChange(
checked === true
? offered.filter((name) => name === tool || chosen.includes(name))
: chosen.filter((name) => name !== tool),
)
}
/>
<Label
id={`${groupId}-${tool}-label`}
htmlFor={`${groupId}-${tool}`}
className="text-xs break-all"
>
{tool}
</Label>
</li>
))}
</ul>
</fieldset>
);
}
105 changes: 95 additions & 10 deletions client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,13 @@ const view: ScheduleMCPConsentView = {
configurationRevision: 'v1',
},
policyRevision: 'p1',
permittedTools: [{ agentId: 'root', tools: ['query'] }],
permittedTools: [
{ agentId: 'root', tools: ['export', 'query'] },
{ agentId: 'child', tools: ['query'] },
],
},
],
allowed: {},
offer: { digest: 'a'.repeat(64), maxLifetimeHours: 24 },
};
function display() {
Expand All @@ -58,7 +62,7 @@ function display() {
beforeEach(() => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(view);
});
it('renders loading, then the exact agent/resource and bounded lifetime', async () => {
it('renders loading, then the resource, each tool on offer unchecked, and a bounded lifetime', async () => {
let resolve!: (value: ScheduleMCPConsentView) => void;
jest.mocked(dataService.getScheduleMCPConsent).mockReturnValue(
new Promise((done) => {
Expand All @@ -69,10 +73,14 @@ it('renders loading, then the exact agent/resource and bounded lifetime', async
expect(screen.queryByText('warehouse')).not.toBeInTheDocument();
resolve(view);
expect(await screen.findByText('warehouse')).toBeVisible();
expect(screen.getByText('root: query')).toBeVisible();
expect(screen.getAllByRole('checkbox')).toHaveLength(3);
expect(screen.getByRole('checkbox', { name: 'query' })).not.toBeChecked();
expect(screen.getByRole('checkbox', { name: 'export' })).not.toBeChecked();
expect(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })).toBeDisabled();
expect(screen.getByText('com_ui_schedule_consent_none_selected')).toBeVisible();
expect(screen.getByRole('spinbutton')).toHaveAttribute('max', '24');
});
it('confirms only an offer reference and lifetime, then rereads persisted state', async () => {
it('confirms the offer reference, lifetime and only the tools the owner ticked, then rereads persisted state', async () => {
const active = {
...view,
state: 'active' as const,
Expand All @@ -84,18 +92,96 @@ it('confirms only an offer reference and lifetime, then rereads persisted state'
return active;
});
display();
await userEvent.click(
await screen.findByRole('button', { name: 'com_ui_schedule_consent_confirm' }),
);
await userEvent.click(await screen.findByRole('checkbox', { name: 'query' }));
await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }));
await waitFor(() =>
expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith('schedule', {
offerDigest: view.offer!.digest,
expectedRevision: null,
lifetimeHours: 1,
allow: { warehouse: ['query'] },
}),
);
expect(await screen.findByText('com_ui_schedule_consent_active')).toBeVisible();
});
it('allows or clears every tool on a server with one box', async () => {
display();
const server = await screen.findByRole('checkbox', {
name: 'com_ui_schedule_consent_allow_server',
});
await userEvent.click(server);
expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked();
expect(screen.getByRole('checkbox', { name: 'export' })).toBeChecked();
expect(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })).toBeEnabled();

await userEvent.click(screen.getByRole('checkbox', { name: 'export' }));
expect(server).not.toBeChecked();
expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked();

await userEvent.click(server);
expect(screen.getByRole('checkbox', { name: 'export' })).toBeChecked();
await userEvent.click(server);
expect(screen.getByRole('checkbox', { name: 'query' })).not.toBeChecked();
expect(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })).toBeDisabled();
});
it('starts from what the stored grant allows and is still on offer', async () => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
state: 'active',
revision: 'grant',
expiresAtMs: Date.now() + 60_000,
allowed: { warehouse: ['query', 'retired'] },
});
display();
expect(await screen.findByRole('checkbox', { name: 'query' })).toBeChecked();
expect(screen.getByRole('checkbox', { name: 'export' })).not.toBeChecked();
expect(screen.queryByRole('checkbox', { name: 'retired' })).not.toBeInTheDocument();
});
it('drops ticks for a server or tool that leaves the offer while the dialog is open', async () => {
const archive = {
...view.targets[0],
resource: { ...view.targets[0].resource, serverName: 'archive' },
permittedTools: [{ agentId: 'root', tools: ['purge'] }],
};
jest
.mocked(dataService.getScheduleMCPConsent)
.mockResolvedValue({ ...view, targets: [archive, ...view.targets] });
jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view);
const client = display();
await userEvent.click(await screen.findByRole('checkbox', { name: 'purge' }));
await userEvent.click(screen.getByRole('checkbox', { name: 'export' }));
await userEvent.click(screen.getByRole('checkbox', { name: 'query' }));
// The agents drop the archive server and the export tool; the offer is read again.
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
targets: [{ ...view.targets[0], permittedTools: [{ agentId: 'root', tools: ['query'] }] }],
offer: { digest: 'b'.repeat(64), maxLifetimeHours: 24 },
});
await client.invalidateQueries();
await waitFor(() =>
expect(screen.queryByRole('checkbox', { name: 'purge' })).not.toBeInTheDocument(),
);
expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked();
await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }));
await waitFor(() =>
expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith(
'schedule',
expect.objectContaining({ offerDigest: 'b'.repeat(64), allow: { warehouse: ['query'] } }),
),
);
});
it('lists the allowed tools without boxes when there is nothing to confirm', async () => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
state: 'revoked',
revision: 'revoked',
allowed: { warehouse: ['query'] },
offer: null,
});
display();
expect(await screen.findByText('com_ui_schedule_consent_allowed')).toBeVisible();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
});
it('reopens with persisted expiry and explicitly revokes without enabling a schedule', async () => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
Expand Down Expand Up @@ -140,9 +226,8 @@ it('shows API errors and retries without silently accepting a grant', async () =
it('reports a stale confirmation and reloads the current offer', async () => {
jest.mocked(dataService.confirmScheduleMCPConsent).mockRejectedValueOnce(new Error('conflict'));
display();
await userEvent.click(
await screen.findByRole('button', { name: 'com_ui_schedule_consent_confirm' }),
);
await userEvent.click(await screen.findByRole('checkbox', { name: 'query' }));
await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }));
expect(await screen.findByText('com_ui_schedule_consent_error')).toBeVisible();
await waitFor(() => expect(dataService.getScheduleMCPConsent).toHaveBeenCalledTimes(2));
});
Expand Down
5 changes: 4 additions & 1 deletion client/src/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -3901,7 +3901,7 @@
"com_nav_mobile_drawer_strip": "Show chat beside the sidebar on mobile",
"com_nav_mobile_drawer_strip_info": "The sidebar stops short of the edge so a strip of the conversation stays visible. Tapping it closes the sidebar.",
"com_ui_schedule_consent_title": "Scheduled MCP authorization",
"com_ui_schedule_consent_boundary": "Authorize only the listed agent and resources until the fixed deadline. This does not reconnect a provider, enable the schedule or permit writes.",
"com_ui_schedule_consent_boundary": "Choose which servers and tools this schedule may use while you are away, until the fixed deadline. Anything left unchecked is refused. This does not reconnect a provider or enable the schedule.",
"com_ui_schedule_consent_missing": "Authorization required",
"com_ui_schedule_consent_active": "Authorized",
"com_ui_schedule_consent_expired": "Authorization expired. Confirm again to renew.",
Expand All @@ -3917,6 +3917,9 @@
"com_ui_schedule_consent_issuer": "Issuer: {{issuer}}",
"com_ui_schedule_consent_audience": "Audience: {{audience}}",
"com_ui_schedule_consent_scopes": "Scopes: {{scopes}}",
"com_ui_schedule_consent_allow_server": "Allow all tools on {{server}}",
"com_ui_schedule_consent_allowed": "Allowed tools: {{tools}}",
"com_ui_schedule_consent_none_selected": "Choose at least one tool to confirm.",
"com_ui_code_checkout_mode": "Checkout mode",
"com_ui_code_checkout_isolated": "Isolated worktree",
"com_ui_code_checkout_isolated_info": "Own Git worktree; uncommitted changes aren't copied",
Expand Down
Loading
Loading