diff --git a/client/src/components/MCP/GrantTools.tsx b/client/src/components/MCP/GrantTools.tsx index 0f39578711..80097baf37 100644 --- a/client/src/components/MCP/GrantTools.tsx +++ b/client/src/components/MCP/GrantTools.tsx @@ -144,6 +144,16 @@ function currentChoice( ); } +/** Tools by server in one spelling, whatever order they were ticked in. */ +function canonical(tools: Record): string { + return JSON.stringify( + Object.entries(tools) + .filter(([, names]) => names.length > 0) + .map(([serverName, names]): [string, string[]] => [serverName, [...names].sort()]) + .sort(([a], [b]) => a.localeCompare(b)), + ); +} + /** The owner's choice from one offer, and the ways to change it. */ export interface GrantChoice { /** The MCP tools ticked, by server. */ @@ -168,6 +178,11 @@ export interface GrantChoice { keepsAsking: boolean; /** Something is allowed, so there is a grant to confirm. */ some: boolean; + /** + * The choice is where the offer starts: nothing ticked, unticked or asked about differently. + * With a grant in force, that is the grant itself, so confirming would store nothing new. + */ + pristine: boolean; /** What a confirmation sends for this choice. */ request: Pick; setEverything: (everything: boolean) => void; @@ -276,6 +291,14 @@ export function useGrantChoice(data: ScheduleMCPConsentView | undefined): GrantC }) .filter(([, tools]) => tools.length > 0), ); + const pristine = + data != null && + everything === (standing && (data.revision == null ? true : data.everything)) && + keepsAsking && + canonical(choice) === canonical(initialChoice(data)) && + canonical(asking) === canonical(data.asking) && + canonical({ other }) === + canonical({ other: data.tools.allowed.filter((tool) => offeredOther.includes(tool)) }); return { choice, ask, @@ -288,6 +311,7 @@ export function useGrantChoice(data: ScheduleMCPConsentView | undefined): GrantC everything, keepsAsking, some: everything || chosenCount > 0, + pristine, // The whole agent names nothing, and says nothing about asking unless the owner stops it: // left out, the server keeps what the stored grant asks about. Otherwise `ask` and `tools` // are always sent, since left out the server would keep the stored grant's choice of both. diff --git a/client/src/components/SidePanel/Schedules/Authorize.tsx b/client/src/components/SidePanel/Schedules/Authorize.tsx index d322ab68f6..30b47914ce 100644 --- a/client/src/components/SidePanel/Schedules/Authorize.tsx +++ b/client/src/components/SidePanel/Schedules/Authorize.tsx @@ -10,6 +10,11 @@ export interface Authorization { value: ScheduleReauthorization | null; /** There is something to allow, so the schedule is not created until something is. */ owed: boolean; + /** + * The choice is not the grant the schedule has in force: saving has something to store even + * where no field of the schedule was edited. + */ + unsaved: boolean; } /** @@ -58,9 +63,15 @@ export default function Authorize({ }) : null; const owed = offer != null; + /** A grant that is not in force is not what the form shows, however little was touched. */ + const unsaved = query.data?.state !== 'active' || !state.pristine || typed != null; useEffect(() => { - onChange({ value: chosen ? (JSON.parse(chosen) as ScheduleReauthorization) : null, owed }); - }, [chosen, owed, onChange]); + onChange({ + value: chosen ? (JSON.parse(chosen) as ScheduleReauthorization) : null, + owed, + unsaved, + }); + }, [chosen, owed, unsaved, onChange]); if (query.isLoading && query.fetchStatus !== 'idle') return ; if (query.isError) diff --git a/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx b/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx index 8a817c2673..e2b8fa69f0 100644 --- a/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx +++ b/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx @@ -51,12 +51,15 @@ import { useCreateScheduleMutation, useUpdateScheduleMutation, } from '~/data-provider'; +import { + useScheduleMCPOfferRefresh, + useScheduleMCPConsentMutations, +} from '~/data-provider/Schedules/consent'; import { scheduleMCPErrorMessage, scheduleMCPErrorOutcomes, scheduleAuthorizationRejected, } from './errors'; -import { useScheduleMCPOfferRefresh } from '~/data-provider/Schedules/consent'; import { useLocalize, useClockFormat, useWeekStart } from '~/hooks'; import { useChatProjectPicker } from './useScheduleProjects'; import { VariableEditor } from '~/components/Variables'; @@ -260,7 +263,11 @@ export default function ScheduleDialog({ * again in the same step that edits it: an edit ends the grant it had. */ const authorizes = schedulesData?.limits.mcpConsent === true; - const [authorization, setAuthorization] = useState({ value: null, owed: false }); + const [authorization, setAuthorization] = useState({ + value: null, + owed: false, + unsaved: false, + }); const { items: loadedProjectItems, namesById: projectNames, @@ -364,29 +371,33 @@ export default function ScheduleDialog({ }, }); - const updateSchedule = useUpdateScheduleMutation({ - onSuccess: () => { - setMCPRecoveryOutcomes([]); - showToast({ message: localize('com_ui_schedule_updated'), status: 'success' }); - onOpenChange(false); - }, - onError: (error) => { - setMCPRecoveryOutcomes(scheduleMCPErrorOutcomes(error)); - const status = (error as { response?: { status?: number } } | undefined)?.response?.status; - // As on create: the offer the choice was made from is not the one the server holds. - const rejected = scheduleAuthorizationRejected(error); - if (rejected) refreshOffer(); - const fallback = status === 409 ? 'com_ui_schedule_conflict' : 'com_ui_error'; - showToast({ - message: - scheduleMCPErrorMessage(error, localize) ?? - localize(rejected ? 'com_ui_schedule_authorize_changed' : fallback), - status: 'error', - }); - }, - }); + const updated = () => { + setMCPRecoveryOutcomes([]); + showToast({ message: localize('com_ui_schedule_updated'), status: 'success' }); + onOpenChange(false); + }; + const refused = (error: Error) => { + setMCPRecoveryOutcomes(scheduleMCPErrorOutcomes(error)); + const status = (error as { response?: { status?: number } } | undefined)?.response?.status; + // As on create: the offer the choice was made from is not the one the server holds. + const rejected = scheduleAuthorizationRejected(error); + if (rejected) refreshOffer(); + const fallback = status === 409 ? 'com_ui_schedule_conflict' : 'com_ui_error'; + showToast({ + message: + scheduleMCPErrorMessage(error, localize) ?? + localize(rejected ? 'com_ui_schedule_authorize_changed' : fallback), + status: 'error', + }); + }; + const updateSchedule = useUpdateScheduleMutation({ onSuccess: updated, onError: refused }); + /** + * The schedule's own authorization step, for a save that changes what the schedule may use + * and nothing else: an edit with no field is refused, and this is not an edit. + */ + const { confirm: authorize } = useScheduleMCPConsentMutations(schedule?.id ?? ''); - const isLoading = createSchedule.isLoading || updateSchedule.isLoading; + const isLoading = createSchedule.isLoading || updateSchedule.isLoading || authorize.isLoading; /** Whether this submit carries a cadence at all: a pure rename does not, and the * API only validates a cadence it actually receives. Only touched cadence @@ -428,10 +439,20 @@ export default function ScheduleDialog({ ...(cadenceTouched ? { cadence } : {}), ...(dirtyFields.timezone === true ? { timezone: values.timezone } : {}), }; - // Nothing touched: a field-less PATCH is refused server-side (it would rotate - // the schedule's fencing for a request that changes nothing), so just close. + // No field touched: a field-less PATCH is refused server-side (it would rotate + // the schedule's fencing for a request that changes nothing). A choice that is not the + // grant in force is stored through the schedule's authorization step instead, which + // leaves the schedule's revision alone. Otherwise there is nothing to save. if (Object.keys(payload).length === 0) { - onOpenChange(false); + if (!(authorizes && authorization.value && authorization.unsaved)) { + onOpenChange(false); + return; + } + const { expectedRevision, ...choice } = authorization.value; + authorize.mutate( + { ...choice, expectedRevision: expectedRevision ?? null }, + { onSuccess: updated, onError: (error) => refused(error as Error) }, + ); return; } updateSchedule.mutate({ diff --git a/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx index da99697402..b3f3a00470 100644 --- a/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx +++ b/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx @@ -90,6 +90,7 @@ jest.mock('librechat-data-provider', () => { ...actual.dataService, getScheduleMCPOffer: jest.fn(), getScheduleMCPConsent: jest.fn(), + confirmScheduleMCPConsent: jest.fn(), }, }; }); @@ -1046,6 +1047,203 @@ describe('ScheduleDialog', () => { await waitFor(() => expect(dataService.getScheduleMCPConsent).toHaveBeenCalledTimes(2)); }); + describe('with no field of the schedule edited', () => { + const confirmed = jest.mocked(dataService.confirmScheduleMCPConsent); + const open = async (view: ScheduleMCPConsentView = stored) => { + mockLimits = { ...mockLimits, mcpConsent: true }; + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(view); + confirmed.mockResolvedValue(view); + const onOpenChange = jest.fn(); + renderDialog(storedSchedule(), onOpenChange); + await screen.findByText('com_ui_schedule_authorize_title'); + return onOpenChange; + }; + + it('stores a tool the owner ticked through the authorization step, not an edit', async () => { + const user = userEvent.setup(); + const onOpenChange = await open(); + await user.click(screen.getByRole('checkbox', { name: 'export' })); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith('sched-1', { + offerDigest: 'c'.repeat(64), + expectedRevision: 'grant-1', + lifetimeHours: 24, + allow: { warehouse: ['export', 'query'] }, + ask: {}, + tools: [], + }), + ); + // An edit with no field is refused by the server, so none is sent. + expect(mockMutate).not.toHaveBeenCalled(); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + }); + + it('stores a narrower choice, so the tool the owner unticked stops being allowed', async () => { + const user = userEvent.setup(); + await open({ ...stored, allowed: { warehouse: ['export', 'query'] } }); + await user.click(screen.getByRole('checkbox', { name: 'export' })); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith( + 'sched-1', + expect.objectContaining({ allow: { warehouse: ['query'] } }), + ), + ); + }); + + it('stores the whole agent when the owner ticks it', async () => { + const user = userEvent.setup(); + await open(); + await user.click( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_everything' }), + ); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith( + 'sched-1', + expect.objectContaining({ allow: {}, everything: true, expectedRevision: 'grant-1' }), + ), + ); + }); + + it('stores a question the owner adds about a tool that stays allowed', async () => { + const user = userEvent.setup(); + await open({ ...stored, approval: true }); + await user.click( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_ask_tool' }), + ); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith( + 'sched-1', + expect.objectContaining({ + allow: { warehouse: ['query'] }, + ask: { warehouse: ['query'] }, + }), + ), + ); + }); + + it('stores one of the other tools the owner ticks or unticks', async () => { + const user = userEvent.setup(); + await open({ + ...stored, + tools: { offered: ['execute_code', 'web_search'], allowed: ['execute_code'] }, + }); + await user.click( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_tool_code' }), + ); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith( + 'sched-1', + expect.objectContaining({ allow: { warehouse: ['query'] }, tools: [] }), + ), + ); + }); + + it('stores the end of a question under a grant for the whole agent', async () => { + const user = userEvent.setup(); + await open({ + ...stored, + approval: true, + everything: true, + allowed: {}, + asking: { warehouse: ['query'] }, + }); + await user.click( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_everything_asking' }), + ); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith( + 'sched-1', + expect.objectContaining({ allow: {}, everything: true, ask: {} }), + ), + ); + }); + + it('stores another lifetime alone', async () => { + const user = userEvent.setup(); + await open(); + const hours = screen.getByLabelText('com_ui_schedule_consent_hours'); + await user.clear(hours); + await user.type(hours, '12'); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith( + 'sched-1', + expect.objectContaining({ lifetimeHours: 12, allow: { warehouse: ['query'] } }), + ), + ); + }); + + it('authorizes a schedule whose grant is not in force, as the form shows it', async () => { + const user = userEvent.setup(); + const missing: ScheduleMCPConsentView = { + ...offerFor(['query']), + offer: { digest: 'd'.repeat(64), maxLifetimeHours: 24, everything: true }, + }; + const onOpenChange = await open(missing); + expect( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_everything' }), + ).toBeChecked(); + await user.click(save()); + await waitFor(() => + expect(confirmed).toHaveBeenCalledWith('sched-1', { + offerDigest: 'd'.repeat(64), + expectedRevision: null, + lifetimeHours: 24, + allow: {}, + everything: true, + }), + ); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + }); + + it('sends nothing and closes when the grant in force is what the form shows', async () => { + const user = userEvent.setup(); + const onOpenChange = await open(); + await user.click(save()); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(confirmed).not.toHaveBeenCalled(); + expect(mockMutate).not.toHaveBeenCalled(); + }); + + it('sends nothing for a choice put back the way it was', async () => { + const user = userEvent.setup(); + const onOpenChange = await open(); + await user.click(screen.getByRole('checkbox', { name: 'export' })); + await user.click(screen.getByRole('checkbox', { name: 'export' })); + await user.click(save()); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(confirmed).not.toHaveBeenCalled(); + }); + + it('stays open and reads the offer again when the choice is turned down', async () => { + const user = userEvent.setup(); + const onOpenChange = await open(); + confirmed.mockRejectedValue( + Object.assign(new Error('rejected'), { + response: { status: 409, data: { code: 'consent_changed' } }, + }), + ); + await user.click(screen.getByRole('checkbox', { name: 'export' })); + await user.click(save()); + await waitFor(() => expect(confirmed).toHaveBeenCalledTimes(1)); + await waitFor(() => + expect( + jest.mocked(dataService.getScheduleMCPConsent).mock.calls.length, + ).toBeGreaterThan(1), + ); + expect(onOpenChange).not.toHaveBeenCalledWith(false); + // The owner's tick is kept, to be sent again against the offer just read. + expect(screen.getByRole('checkbox', { name: 'export' })).toBeChecked(); + await waitFor(() => expect(save()).toBeEnabled()); + }); + }); + it('sends no choice where consent is off', async () => { const user = userEvent.setup(); renderDialog(storedSchedule()); diff --git a/packages/api/src/schedules/README.md b/packages/api/src/schedules/README.md index d9fa0a8978..1e4a808d7e 100644 --- a/packages/api/src/schedules/README.md +++ b/packages/api/src/schedules/README.md @@ -275,7 +275,10 @@ carries, not the one it replaces. A choice that no longer fits is refused and no edited. The write names the stored grant the new one was decided against (`replacesMCPConsent`) and matches only while that is still what is stored, untouched: a revocation or another confirmation since, or a pin or mark a run added, refuses the edit -with `consent_changed`, since consent writes do not move the schedule's edit generation. An edit that carries none behaves as before, and `authorization` alone is not an edit. +with `consent_changed`, since consent writes do not move the schedule's edit generation. An edit that carries none behaves as before, and `authorization` alone is not an edit. The +form therefore sends a save that changes only the choice (tools, questions, the whole agent or +the lifetime), or that finds the grant not in force, to the confirmation endpoint, and sends +nothing when the grant in force is already what it shows. ### A tool that changes after it was allowed