From 47d00ab1fa26de3ed75aca3b0fcb2974b3694fc3 Mon Sep 17 00:00:00 2001 From: sajitha-tj Date: Wed, 18 Nov 2026 10:09:04 +0530 Subject: [PATCH 1/2] Add personal agent self-service to the client SDKs Let a signed-in user list, view, edit, delete and suspend their own personal agents through /users/me/agents in the React and Vue SDKs, and show the personal kind and who applied a suspension in the admin agent views. Refs thunder-id/thunderid#4468 Signed-off-by: sajitha-tj --- .../api/account/__tests__/meAgentsApi.test.ts | 143 ++++++ .../src/api/account/deleteMeAgent.ts | 40 ++ .../javascript/src/api/account/getMeAgent.ts | 43 ++ .../javascript/src/api/account/getMeAgents.ts | 44 ++ .../src/api/account/suspendAllMeAgents.ts | 37 ++ .../src/api/account/suspendMeAgent.ts | 42 ++ .../src/api/account/unsuspendMeAgent.ts | 42 ++ .../src/api/account/updateMeAgent.ts | 52 +++ .../src/constants/AgentQueryKeys.ts | 4 + packages/javascript/src/i18n/models/i18n.ts | 40 ++ .../javascript/src/i18n/translations/en-US.ts | 43 ++ .../javascript/src/i18n/translations/fr-FR.ts | 45 ++ .../javascript/src/i18n/translations/hi-IN.ts | 43 ++ .../javascript/src/i18n/translations/ja-JP.ts | 44 ++ .../javascript/src/i18n/translations/pt-BR.ts | 45 ++ .../javascript/src/i18n/translations/pt-PT.ts | 45 ++ .../javascript/src/i18n/translations/si-LK.ts | 44 ++ .../javascript/src/i18n/translations/ta-IN.ts | 46 ++ .../javascript/src/i18n/translations/te-IN.ts | 44 ++ packages/javascript/src/index.ts | 32 ++ .../javascript/src/models/access-status.ts | 20 +- .../javascript/src/models/agent-resource.ts | 84 +++- packages/javascript/src/models/config.ts | 6 + .../getAccountLifecycleActions.test.ts | 24 + .../getMeAgentSuspensionAction.test.ts | 26 ++ .../utils/__tests__/isPersonalAgent.test.ts | 14 + .../utils/__tests__/personalAgentForm.test.ts | 108 +++++ .../__tests__/resolveResourceEndpoint.test.ts | 1 + .../src/utils/getAccountLifecycleActions.ts | 13 +- .../src/utils/getMeAgentSuspensionAction.ts | 24 + .../javascript/src/utils/isPersonalAgent.ts | 19 + .../javascript/src/utils/personalAgentForm.ts | 81 ++++ .../src/utils/resolveResourceEndpoint.ts | 2 + .../api/account/__tests__/meAgentsApi.test.ts | 93 ++++ .../react/src/api/account/deleteMeAgent.ts | 37 ++ packages/react/src/api/account/getMeAgent.ts | 38 ++ packages/react/src/api/account/getMeAgents.ts | 46 ++ .../src/api/account/suspendAllMeAgents.ts | 42 ++ .../react/src/api/account/suspendMeAgent.ts | 37 ++ .../react/src/api/account/unsuspendMeAgent.ts | 37 ++ .../react/src/api/account/updateMeAgent.ts | 42 ++ .../BasePersonalAgentDetails.tsx | 390 ++++++++++++++++ .../PersonalAgentDetails.tsx | 125 +++++ .../__tests__/PersonalAgentDetails.test.tsx | 321 +++++++++++++ .../BasePersonalAgentList.tsx | 203 +++++++++ .../PersonalAgentList/PersonalAgentList.tsx | 96 ++++ .../__tests__/PersonalAgentList.test.tsx | 189 ++++++++ .../management/AgentDetails/AgentDetails.tsx | 1 + .../AgentDetails/BaseAgentDetails.tsx | 24 +- .../management/AgentList/BaseAgentList.tsx | 14 +- .../__tests__/managementComponents.test.tsx | 72 +++ .../management/shared/AdminParts.styles.ts | 1 + .../hooks/management/useAccountLifecycle.ts | 10 +- packages/react/src/index.ts | 43 ++ .../__tests__/api/account/me-agents.test.ts | 93 ++++ .../account/personal-agents.test.ts | 429 ++++++++++++++++++ .../management/management-components.test.ts | 70 +++ packages/vue/src/api/account/deleteMeAgent.ts | 37 ++ packages/vue/src/api/account/getMeAgent.ts | 38 ++ packages/vue/src/api/account/getMeAgents.ts | 46 ++ .../vue/src/api/account/suspendAllMeAgents.ts | 42 ++ .../vue/src/api/account/suspendMeAgent.ts | 37 ++ .../vue/src/api/account/unsuspendMeAgent.ts | 37 ++ packages/vue/src/api/account/updateMeAgent.ts | 42 ++ .../BasePersonalAgentDetails.ts | 407 +++++++++++++++++ .../PersonalAgentDetails.ts | 120 +++++ .../BasePersonalAgentList.ts | 190 ++++++++ .../personal-agent-list/PersonalAgentList.ts | 120 +++++ .../management/AgentDetails/AgentDetails.ts | 1 + .../AgentDetails/BaseAgentDetails.ts | 18 + .../management/AgentList/BaseAgentList.ts | 12 +- .../management/useAccountLifecycle.ts | 8 +- packages/vue/src/index.ts | 37 ++ playgrounds/react/src/pages/capabilities.ts | 29 ++ .../pages/explorer/CustomRenderWidgets.tsx | 19 +- .../explorer/PersonalAgentStoryWidgets.tsx | 359 +++++++++++++++ .../pages/explorer/personalAgentStories.tsx | 208 +++++++++ .../react/src/pages/explorer/stories.tsx | 3 + .../pages/explorer/personalAgentStories.ts | 357 +++++++++++++++ playgrounds/vue/src/pages/explorer/stories.ts | 2 + 80 files changed, 5943 insertions(+), 19 deletions(-) create mode 100644 packages/javascript/src/api/account/__tests__/meAgentsApi.test.ts create mode 100644 packages/javascript/src/api/account/deleteMeAgent.ts create mode 100644 packages/javascript/src/api/account/getMeAgent.ts create mode 100644 packages/javascript/src/api/account/getMeAgents.ts create mode 100644 packages/javascript/src/api/account/suspendAllMeAgents.ts create mode 100644 packages/javascript/src/api/account/suspendMeAgent.ts create mode 100644 packages/javascript/src/api/account/unsuspendMeAgent.ts create mode 100644 packages/javascript/src/api/account/updateMeAgent.ts create mode 100644 packages/javascript/src/utils/__tests__/getMeAgentSuspensionAction.test.ts create mode 100644 packages/javascript/src/utils/__tests__/isPersonalAgent.test.ts create mode 100644 packages/javascript/src/utils/__tests__/personalAgentForm.test.ts create mode 100644 packages/javascript/src/utils/getMeAgentSuspensionAction.ts create mode 100644 packages/javascript/src/utils/isPersonalAgent.ts create mode 100644 packages/javascript/src/utils/personalAgentForm.ts create mode 100644 packages/react/src/api/account/__tests__/meAgentsApi.test.ts create mode 100644 packages/react/src/api/account/deleteMeAgent.ts create mode 100644 packages/react/src/api/account/getMeAgent.ts create mode 100644 packages/react/src/api/account/getMeAgents.ts create mode 100644 packages/react/src/api/account/suspendAllMeAgents.ts create mode 100644 packages/react/src/api/account/suspendMeAgent.ts create mode 100644 packages/react/src/api/account/unsuspendMeAgent.ts create mode 100644 packages/react/src/api/account/updateMeAgent.ts create mode 100644 packages/react/src/components/account/PersonalAgentDetails/BasePersonalAgentDetails.tsx create mode 100644 packages/react/src/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx create mode 100644 packages/react/src/components/account/PersonalAgentDetails/__tests__/PersonalAgentDetails.test.tsx create mode 100644 packages/react/src/components/account/PersonalAgentList/BasePersonalAgentList.tsx create mode 100644 packages/react/src/components/account/PersonalAgentList/PersonalAgentList.tsx create mode 100644 packages/react/src/components/account/PersonalAgentList/__tests__/PersonalAgentList.test.tsx create mode 100644 packages/vue/src/__tests__/api/account/me-agents.test.ts create mode 100644 packages/vue/src/__tests__/components/account/personal-agents.test.ts create mode 100644 packages/vue/src/api/account/deleteMeAgent.ts create mode 100644 packages/vue/src/api/account/getMeAgent.ts create mode 100644 packages/vue/src/api/account/getMeAgents.ts create mode 100644 packages/vue/src/api/account/suspendAllMeAgents.ts create mode 100644 packages/vue/src/api/account/suspendMeAgent.ts create mode 100644 packages/vue/src/api/account/unsuspendMeAgent.ts create mode 100644 packages/vue/src/api/account/updateMeAgent.ts create mode 100644 packages/vue/src/components/account/personal-agent-details/BasePersonalAgentDetails.ts create mode 100644 packages/vue/src/components/account/personal-agent-details/PersonalAgentDetails.ts create mode 100644 packages/vue/src/components/account/personal-agent-list/BasePersonalAgentList.ts create mode 100644 packages/vue/src/components/account/personal-agent-list/PersonalAgentList.ts create mode 100644 playgrounds/react/src/pages/explorer/PersonalAgentStoryWidgets.tsx create mode 100644 playgrounds/react/src/pages/explorer/personalAgentStories.tsx create mode 100644 playgrounds/vue/src/pages/explorer/personalAgentStories.ts diff --git a/packages/javascript/src/api/account/__tests__/meAgentsApi.test.ts b/packages/javascript/src/api/account/__tests__/meAgentsApi.test.ts new file mode 100644 index 00000000..76ed5334 --- /dev/null +++ b/packages/javascript/src/api/account/__tests__/meAgentsApi.test.ts @@ -0,0 +1,143 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it, vi, type Mock} from 'vitest'; +import ThunderIDAPIError from '../../../errors/ThunderIDAPIError'; +import {ApiFetcher} from '../../../models/api'; +import deleteMeAgent from '../deleteMeAgent'; +import getMeAgent from '../getMeAgent'; +import getMeAgents from '../getMeAgents'; +import suspendAllMeAgents from '../suspendAllMeAgents'; +import suspendMeAgent from '../suspendMeAgent'; +import unsuspendMeAgent from '../unsuspendMeAgent'; +import updateMeAgent from '../updateMeAgent'; + +type FetcherMock = Mock; +type Run = (fetcher: ApiFetcher) => Promise; + +const baseUrl = 'https://localhost:8090'; +const agentId = 'agent-1'; +const payload = { + attributes: {name: 'Spending assistant'}, + grantTypes: ['authorization_code'], + redirectUris: ['https://assistant.example.com/callback'], +}; + +const respond = (status: number, body: unknown = {}): FetcherMock => + vi.fn().mockResolvedValue({ + json: () => Promise.resolve(body), + ok: status >= 200 && status < 300, + status, + statusText: '', + text: () => Promise.resolve(JSON.stringify(body)), + } as Response); + +describe('personal agent self-service API', () => { + it.each<[string, Run, string, string, unknown]>([ + [ + 'getMeAgents', + (fetcher: ApiFetcher) => getMeAgents({baseUrl, fetcher, kind: 'personal-assistant', limit: 5, offset: 10}), + 'GET', + `${baseUrl}/users/me/agents?kind=personal-assistant&limit=5&offset=10`, + undefined, + ], + [ + 'getMeAgent', + (fetcher: ApiFetcher) => getMeAgent({agentId, baseUrl, fetcher}), + 'GET', + `${baseUrl}/users/me/agents/agent-1?include=display`, + undefined, + ], + [ + 'updateMeAgent', + (fetcher: ApiFetcher) => updateMeAgent({agentId, baseUrl, fetcher, payload}), + 'PUT', + `${baseUrl}/users/me/agents/agent-1`, + JSON.stringify(payload), + ], + [ + 'deleteMeAgent', + (fetcher: ApiFetcher) => deleteMeAgent({agentId, baseUrl, fetcher}), + 'DELETE', + `${baseUrl}/users/me/agents/agent-1`, + undefined, + ], + [ + 'suspendMeAgent', + (fetcher: ApiFetcher) => suspendMeAgent({agentId, baseUrl, fetcher}), + 'POST', + `${baseUrl}/users/me/agents/agent-1/suspend`, + undefined, + ], + [ + 'unsuspendMeAgent', + (fetcher: ApiFetcher) => unsuspendMeAgent({agentId, baseUrl, fetcher}), + 'POST', + `${baseUrl}/users/me/agents/agent-1/unsuspend`, + undefined, + ], + [ + 'suspendAllMeAgents', + (fetcher: ApiFetcher) => suspendAllMeAgents({baseUrl, fetcher}), + 'POST', + `${baseUrl}/users/me/agents/suspend`, + undefined, + ], + ])('%s sends %s to the self-service route', async (_name, run, method, url, body) => { + const fetcher: FetcherMock = respond(200); + + await run(fetcher); + + const [sentUrl, init] = fetcher.mock.calls[0]; + expect(sentUrl).toBe(url); + expect(init.method).toBe(method); + expect(init.body).toBe(body); + }); + + it('lists every agent the user owns when no kind is given', async () => { + const fetcher: FetcherMock = respond(200, {agents: [], count: 0, startIndex: 1, totalResults: 0}); + + await getMeAgents({baseUrl, fetcher}); + + expect(fetcher.mock.calls[0][0]).toBe(`${baseUrl}/users/me/agents`); + }); + + it('honors the collection URL override, including for suspending every agent', async () => { + const url = 'https://rs.example.com/users/me/agents/'; + const single: FetcherMock = respond(204); + const all: FetcherMock = respond(200, {suspendedCount: 2}); + + await suspendMeAgent({agentId, fetcher: single, url}); + const result: unknown = await suspendAllMeAgents({fetcher: all, url}); + + expect(single.mock.calls[0][0]).toBe('https://rs.example.com/users/me/agents/agent-1/suspend'); + expect(all.mock.calls[0][0]).toBe('https://rs.example.com/users/me/agents/suspend'); + expect(result).toEqual({suspendedCount: 2}); + }); + + it('resolves with nothing when the server answers 204', async () => { + await expect(unsuspendMeAgent({agentId, baseUrl, fetcher: respond(204)})).resolves.toBeUndefined(); + }); + + it.each<[number, string]>([ + [403, 'getMeAgent-ForbiddenError-001'], + [404, 'getMeAgent-NotFoundError-001'], + [500, 'getMeAgent-ResponseError-001'], + ])('raises a distinct code for HTTP %i', async (status, code) => { + const error: unknown = await getMeAgent({agentId, baseUrl, fetcher: respond(status, {code: 'AGT-1004'})}).catch( + (caught: unknown) => caught, + ); + + expect(error).toBeInstanceOf(ThunderIDAPIError); + expect((error as ThunderIDAPIError).code).toBe(code); + }); + + it('refuses an empty agent ID before any request', async () => { + const fetcher: FetcherMock = respond(200); + + await expect(deleteMeAgent({agentId: ' ', baseUrl, fetcher})).rejects.toMatchObject({ + code: 'deleteMeAgent-ValidationError-002', + }); + expect(fetcher).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/javascript/src/api/account/deleteMeAgent.ts b/packages/javascript/src/api/account/deleteMeAgent.ts new file mode 100644 index 00000000..ede957cc --- /dev/null +++ b/packages/javascript/src/api/account/deleteMeAgent.ts @@ -0,0 +1,40 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the deleteMeAgent request. + */ +export interface DeleteMeAgentConfig extends ManagementRequestConfig { + /** + * Identifier of the personal agent to delete. + */ + agentId: string; +} + +/** + * Deletes one of the signed-in user's personal agents. + * + * @param config - Request configuration object. + * @returns A promise that resolves once the agent is deleted. + * + * @example + * ```typescript + * await deleteMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b', + * }); + * ``` + */ +const deleteMeAgent = async ({agentId, ...config}: DeleteMeAgentConfig): Promise => + requestManagementResource(config, { + collection: 'users/me/agents', + failureMessage: 'Failed to delete your agent', + id: agentId, + method: 'DELETE', + operation: 'deleteMeAgent', + }); + +export default deleteMeAgent; diff --git a/packages/javascript/src/api/account/getMeAgent.ts b/packages/javascript/src/api/account/getMeAgent.ts new file mode 100644 index 00000000..357bb1c6 --- /dev/null +++ b/packages/javascript/src/api/account/getMeAgent.ts @@ -0,0 +1,43 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {Agent} from '../../models/agent-resource'; +import {ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the getMeAgent request. + */ +export interface GetMeAgentConfig extends ManagementRequestConfig { + /** + * Identifier of the agent to retrieve. + */ + agentId: string; +} + +/** + * Retrieves one of the agents the signed-in user owns. Another user's agent, or one outside the + * organization unit the access token names, is not found. + * + * @param config - Request configuration object. + * @returns A promise that resolves with the agent. + * + * @example + * ```typescript + * const agent = await getMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b', + * }); + * ``` + */ +const getMeAgent = async ({agentId, ...config}: GetMeAgentConfig): Promise => + requestManagementResource(config, { + collection: 'users/me/agents', + failureMessage: 'Failed to fetch your agent', + id: agentId, + method: 'GET', + operation: 'getMeAgent', + query: {include: 'display'}, + }); + +export default getMeAgent; diff --git a/packages/javascript/src/api/account/getMeAgents.ts b/packages/javascript/src/api/account/getMeAgents.ts new file mode 100644 index 00000000..4a787d5a --- /dev/null +++ b/packages/javascript/src/api/account/getMeAgents.ts @@ -0,0 +1,44 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {AgentKind, AgentListResponse} from '../../models/agent-resource'; +import {ApiFilteringParams, ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the getMeAgents request. + */ +export type GetMeAgentsConfig = ManagementRequestConfig & + Pick & { + /** + * Lists only the agents of this kind. Without it, every agent the signed-in user owns is listed. + */ + kind?: AgentKind; + }; + +/** + * Retrieves a page of the agents the signed-in user owns, in the organization unit the access token names. + * The token must be the user's own: a delegated token, such as an agent's token for its owner, is refused. + * + * @param config - Request configuration object. + * @returns A promise that resolves with the page of agents. + * + * @example + * ```typescript + * const {agents, totalResults} = await getMeAgents({ + * baseUrl: 'https://localhost:8090', + * kind: PERSONAL_AGENT_KIND, + * limit: 10, + * }); + * ``` + */ +const getMeAgents = async ({kind, limit, offset, ...config}: GetMeAgentsConfig): Promise => + requestManagementResource(config, { + collection: 'users/me/agents', + failureMessage: 'Failed to fetch your agents', + method: 'GET', + operation: 'getMeAgents', + query: {kind, limit, offset}, + }); + +export default getMeAgents; diff --git a/packages/javascript/src/api/account/suspendAllMeAgents.ts b/packages/javascript/src/api/account/suspendAllMeAgents.ts new file mode 100644 index 00000000..58742c77 --- /dev/null +++ b/packages/javascript/src/api/account/suspendAllMeAgents.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {SuspendAllMeAgentsResponse} from '../../models/agent-resource'; +import {ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the suspendAllMeAgents request. + */ +export type SuspendAllMeAgentsConfig = ManagementRequestConfig; + +/** + * Suspends every personal agent of the signed-in user that the user has not already suspended, in the + * organization unit the access token names, after the server revokes the tokens issued to each. + * + * @param config - Request configuration object. A `url` is the collection of the user's agents, as for + * {@link getMeAgents}. + * @returns A promise that resolves with how many agents the request suspended. + * + * @example + * ```typescript + * const {suspendedCount} = await suspendAllMeAgents({baseUrl: 'https://localhost:8090'}); + * ``` + */ +const suspendAllMeAgents = async ({url, ...config}: SuspendAllMeAgentsConfig): Promise => + requestManagementResource( + {...config, url: url ? `${url.replace(/\/+$/, '')}/suspend` : undefined}, + { + collection: 'users/me/agents/suspend', + failureMessage: 'Failed to suspend your agents', + method: 'POST', + operation: 'suspendAllMeAgents', + }, + ); + +export default suspendAllMeAgents; diff --git a/packages/javascript/src/api/account/suspendMeAgent.ts b/packages/javascript/src/api/account/suspendMeAgent.ts new file mode 100644 index 00000000..0cc7c47c --- /dev/null +++ b/packages/javascript/src/api/account/suspendMeAgent.ts @@ -0,0 +1,42 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the suspendMeAgent request. + */ +export interface SuspendMeAgentConfig extends ManagementRequestConfig { + /** + * Identifier of the personal agent to suspend. + */ + agentId: string; +} + +/** + * Suspends one of the signed-in user's personal agents, after the server revokes the tokens issued to it. + * The owner's suspension is independent of the organization's, and suspending again changes nothing. + * + * @param config - Request configuration object. + * @returns A promise that resolves once the agent is suspended. + * + * @example + * ```typescript + * await suspendMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b', + * }); + * ``` + */ +const suspendMeAgent = async ({agentId, ...config}: SuspendMeAgentConfig): Promise => + requestManagementResource(config, { + collection: 'users/me/agents', + failureMessage: 'Failed to suspend your agent', + id: agentId, + method: 'POST', + operation: 'suspendMeAgent', + subPath: 'suspend', + }); + +export default suspendMeAgent; diff --git a/packages/javascript/src/api/account/unsuspendMeAgent.ts b/packages/javascript/src/api/account/unsuspendMeAgent.ts new file mode 100644 index 00000000..89d7904f --- /dev/null +++ b/packages/javascript/src/api/account/unsuspendMeAgent.ts @@ -0,0 +1,42 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the unsuspendMeAgent request. + */ +export interface UnsuspendMeAgentConfig extends ManagementRequestConfig { + /** + * Identifier of the personal agent whose owner's suspension to lift. + */ + agentId: string; +} + +/** + * Lifts the suspension the signed-in user placed on one of their personal agents. A suspension by the + * organization stays in force, so the agent stays suspended until an administrator lifts it. + * + * @param config - Request configuration object. + * @returns A promise that resolves once the owner's suspension is lifted. + * + * @example + * ```typescript + * await unsuspendMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b', + * }); + * ``` + */ +const unsuspendMeAgent = async ({agentId, ...config}: UnsuspendMeAgentConfig): Promise => + requestManagementResource(config, { + collection: 'users/me/agents', + failureMessage: 'Failed to unsuspend your agent', + id: agentId, + method: 'POST', + operation: 'unsuspendMeAgent', + subPath: 'unsuspend', + }); + +export default unsuspendMeAgent; diff --git a/packages/javascript/src/api/account/updateMeAgent.ts b/packages/javascript/src/api/account/updateMeAgent.ts new file mode 100644 index 00000000..1d684c91 --- /dev/null +++ b/packages/javascript/src/api/account/updateMeAgent.ts @@ -0,0 +1,52 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {Agent, UpdateMeAgentRequest} from '../../models/agent-resource'; +import {ManagementRequestConfig} from '../../models/api'; +import requestManagementResource from '../../utils/requestManagementResource'; + +/** + * Configuration for the updateMeAgent request. + */ +export interface UpdateMeAgentConfig extends ManagementRequestConfig { + /** + * Identifier of the personal agent to update. + */ + agentId: string; + /** + * The whole editable part of the agent. Read the agent first and send these fields back with the changes. + */ + payload: UpdateMeAgentRequest; +} + +/** + * Replaces the part of one of the signed-in user's personal agents its owner may change: the description, + * the attributes (including the name), the grant types and the redirect URIs. + * + * @param config - Request configuration object. + * @returns A promise that resolves with the updated agent. + * + * @example + * ```typescript + * const agent = await updateMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: '6f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b', + * payload: { + * attributes: {name: 'Spending assistant'}, + * grantTypes: ['authorization_code', 'refresh_token'], + * redirectUris: ['https://assistant.example.com/callback'], + * }, + * }); + * ``` + */ +const updateMeAgent = async ({agentId, payload, ...config}: UpdateMeAgentConfig): Promise => + requestManagementResource(config, { + body: payload, + collection: 'users/me/agents', + failureMessage: 'Failed to update your agent', + id: agentId, + method: 'PUT', + operation: 'updateMeAgent', + }); + +export default updateMeAgent; diff --git a/packages/javascript/src/constants/AgentQueryKeys.ts b/packages/javascript/src/constants/AgentQueryKeys.ts index 992d9bd0..2c25c1f2 100644 --- a/packages/javascript/src/constants/AgentQueryKeys.ts +++ b/packages/javascript/src/constants/AgentQueryKeys.ts @@ -9,10 +9,14 @@ const AgentQueryKeys: { AGENT: 'agent'; AGENTS: 'agents'; AGENT_TYPES: 'agent-types'; + ME_AGENT: 'me-agent'; + ME_AGENTS: 'me-agents'; } = { AGENT: 'agent', AGENTS: 'agents', AGENT_TYPES: 'agent-types', + ME_AGENT: 'me-agent', + ME_AGENTS: 'me-agents', }; export default AgentQueryKeys; diff --git a/packages/javascript/src/i18n/models/i18n.ts b/packages/javascript/src/i18n/models/i18n.ts index 696fe8e2..09929ad7 100644 --- a/packages/javascript/src/i18n/models/i18n.ts +++ b/packages/javascript/src/i18n/models/i18n.ts @@ -159,6 +159,40 @@ export interface I18nTranslations { 'user.change_password.generic.error': string; 'user.change_password.unavailable.heading': string; 'user.change_password.unavailable.description': string; + 'user.agents.title': string; + 'user.agents.description': string; + 'user.agents.list.columns.name': string; + 'user.agents.list.columns.status': string; + 'user.agents.list.empty': string; + 'user.agents.list.error': string; + 'user.agents.suspend_all.action': string; + 'user.agents.suspend_all.confirm': string; + 'user.agents.suspend_all.done': string; + 'user.agents.details.overview': string; + 'user.agents.details.attributes': string; + 'user.agents.details.client_id': string; + 'user.agents.details.grant_types': string; + 'user.agents.details.redirect_uris': string; + 'user.agents.details.none': string; + 'user.agents.details.error': string; + 'user.agents.suspension.owner': string; + 'user.agents.suspension.organization': string; + 'user.agents.suspension.cascade': string; + 'user.agents.suspend.action': string; + 'user.agents.suspend.confirm': string; + 'user.agents.unsuspend.action': string; + 'user.agents.action.error': string; + 'user.agents.edit.action': string; + 'user.agents.edit.title': string; + 'user.agents.edit.save': string; + 'user.agents.fields.name': string; + 'user.agents.fields.description': string; + 'user.agents.fields.redirect_uris_hint': string; + 'user.agents.grant_types.authorization_code': string; + 'user.agents.grant_types.ciba': string; + 'user.agents.grant_types.refresh_token': string; + 'user.agents.delete.action': string; + 'user.agents.delete.confirm': string; 'validation.password.pattern': string; /* |---------------------------------------------------------------| */ @@ -457,6 +491,12 @@ export interface I18nTranslations { 'admin.agents.details.delete.action': string; 'admin.agents.details.delete.confirm': string; 'admin.agents.details.delete.error': string; + 'admin.agents.kind.personal': string; + 'admin.agents.details.kind': string; + 'admin.agents.details.suspension.title': string; + 'admin.agents.details.suspension.organization': string; + 'admin.agents.details.suspension.owner': string; + 'admin.agents.details.suspension.cascade': string; 'admin.applications.list.title': string; 'admin.applications.list.columns.name': string; 'admin.applications.list.columns.client_id': string; diff --git a/packages/javascript/src/i18n/translations/en-US.ts b/packages/javascript/src/i18n/translations/en-US.ts index 43e8e5f6..6e4184f3 100644 --- a/packages/javascript/src/i18n/translations/en-US.ts +++ b/packages/javascript/src/i18n/translations/en-US.ts @@ -159,6 +159,43 @@ const translations: I18nTranslations = { 'user.change_password.generic.error': 'An error occurred while updating your {credentialLower}. Please try again.', 'user.change_password.unavailable.heading': '{credential} changes unavailable', 'user.change_password.unavailable.description': 'Please contact your administrator.', + + /* Personal agents */ + 'user.agents.title': 'Personal agents', + 'user.agents.description': 'Agents that act only on your behalf.', + 'user.agents.list.columns.name': 'Name', + 'user.agents.list.columns.status': 'Status', + 'user.agents.list.empty': "You don't have any personal agents.", + 'user.agents.list.error': 'Could not load your agents. Please try again.', + 'user.agents.suspend_all.action': 'Suspend all', + 'user.agents.suspend_all.confirm': 'Suspend all your personal agents? They lose access until you unsuspend them.', + 'user.agents.suspend_all.done': 'Agents suspended: {count}', + 'user.agents.details.overview': 'Overview', + 'user.agents.details.attributes': 'Attributes', + 'user.agents.details.client_id': 'Client ID', + 'user.agents.details.grant_types': 'Grant types', + 'user.agents.details.redirect_uris': 'Redirect URIs', + 'user.agents.details.none': 'None', + 'user.agents.details.error': 'Could not load this agent. Please try again.', + 'user.agents.suspension.owner': 'You suspended this agent.', + 'user.agents.suspension.organization': + 'Your organization suspended this agent. Only an administrator can lift that suspension.', + 'user.agents.suspension.cascade': 'This agent stays suspended while your account is suspended.', + 'user.agents.suspend.action': 'Suspend', + 'user.agents.suspend.confirm': 'Suspend {name}? It loses access until you unsuspend it.', + 'user.agents.unsuspend.action': 'Unsuspend', + 'user.agents.action.error': 'The action could not be completed. Please try again.', + 'user.agents.edit.action': 'Edit', + 'user.agents.edit.title': 'Edit agent', + 'user.agents.edit.save': 'Save changes', + 'user.agents.fields.name': 'Name', + 'user.agents.fields.description': 'Description', + 'user.agents.fields.redirect_uris_hint': 'Needed for the authorization code grant. Separate URIs with commas.', + 'user.agents.grant_types.authorization_code': 'Authorization code', + 'user.agents.grant_types.ciba': 'Backchannel authentication (CIBA)', + 'user.agents.grant_types.refresh_token': 'Refresh token', + 'user.agents.delete.action': 'Delete agent', + 'user.agents.delete.confirm': 'Delete {name}? This cannot be undone.', 'validation.password.pattern': 'Matches the required format', /* |---------------------------------------------------------------| */ @@ -454,6 +491,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'Delete agent', 'admin.agents.details.delete.confirm': 'Delete {name}?', 'admin.agents.details.delete.error': 'Could not delete the agent. Please try again.', + 'admin.agents.kind.personal': 'Personal', + 'admin.agents.details.kind': 'Kind', + 'admin.agents.details.suspension.title': 'Suspended by', + 'admin.agents.details.suspension.organization': 'Organization', + 'admin.agents.details.suspension.owner': 'Owner', + 'admin.agents.details.suspension.cascade': "Owner's account suspension", 'admin.applications.list.title': 'Applications', 'admin.applications.list.columns.name': 'Name', 'admin.applications.list.columns.client_id': 'Client ID', diff --git a/packages/javascript/src/i18n/translations/fr-FR.ts b/packages/javascript/src/i18n/translations/fr-FR.ts index bf9adc59..cd863be3 100644 --- a/packages/javascript/src/i18n/translations/fr-FR.ts +++ b/packages/javascript/src/i18n/translations/fr-FR.ts @@ -162,6 +162,45 @@ const translations: I18nTranslations = { 'Une erreur est survenue lors de la mise à jour de votre {credentialLower}. Veuillez réessayer.', 'user.change_password.unavailable.heading': 'Modification du {credentialLower} indisponible', 'user.change_password.unavailable.description': 'Veuillez contacter votre administrateur.', + + /* Personal agents */ + 'user.agents.title': 'Agents personnels', + 'user.agents.description': 'Agents qui agissent uniquement en votre nom.', + 'user.agents.list.columns.name': 'Nom', + 'user.agents.list.columns.status': 'Statut', + 'user.agents.list.empty': "Vous n'avez aucun agent personnel.", + 'user.agents.list.error': 'Impossible de charger vos agents. Veuillez réessayer.', + 'user.agents.suspend_all.action': 'Tout suspendre', + 'user.agents.suspend_all.confirm': + "Suspendre tous vos agents personnels ? Ils perdent l'accès jusqu'à ce que vous leviez la suspension.", + 'user.agents.suspend_all.done': 'Agents suspendus : {count}', + 'user.agents.details.overview': 'Aperçu', + 'user.agents.details.attributes': 'Attributs', + 'user.agents.details.client_id': 'ID client', + 'user.agents.details.grant_types': "Types d'octroi", + 'user.agents.details.redirect_uris': 'URI de redirection', + 'user.agents.details.none': 'Aucun', + 'user.agents.details.error': 'Impossible de charger cet agent. Veuillez réessayer.', + 'user.agents.suspension.owner': 'Vous avez suspendu cet agent.', + 'user.agents.suspension.organization': + 'Votre organisation a suspendu cet agent. Seul un administrateur peut lever cette suspension.', + 'user.agents.suspension.cascade': 'Cet agent reste suspendu tant que votre compte est suspendu.', + 'user.agents.suspend.action': 'Suspendre', + 'user.agents.suspend.confirm': "Suspendre {name} ? Il perd l'accès jusqu'à ce que vous leviez la suspension.", + 'user.agents.unsuspend.action': 'Lever la suspension', + 'user.agents.action.error': "L'action n'a pas pu être effectuée. Veuillez réessayer.", + 'user.agents.edit.action': 'Modifier', + 'user.agents.edit.title': "Modifier l'agent", + 'user.agents.edit.save': 'Enregistrer les modifications', + 'user.agents.fields.name': 'Nom', + 'user.agents.fields.description': 'Description', + 'user.agents.fields.redirect_uris_hint': + "Nécessaire pour l'octroi par code d'autorisation. Séparez les URI par des virgules.", + 'user.agents.grant_types.authorization_code': "Code d'autorisation", + 'user.agents.grant_types.ciba': 'Authentification par canal de retour (CIBA)', + 'user.agents.grant_types.refresh_token': 'Jeton de rafraîchissement', + 'user.agents.delete.action': "Supprimer l'agent", + 'user.agents.delete.confirm': 'Supprimer {name} ? Cette action est irréversible.', 'validation.password.pattern': 'Correspond au format requis', /* |---------------------------------------------------------------| */ @@ -464,6 +503,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': "Supprimer l'agent", 'admin.agents.details.delete.confirm': 'Supprimer {name} ?', 'admin.agents.details.delete.error': "Impossible de supprimer l'agent. Veuillez réessayer.", + 'admin.agents.kind.personal': 'Personnel', + 'admin.agents.details.kind': 'Nature', + 'admin.agents.details.suspension.title': 'Suspendu par', + 'admin.agents.details.suspension.organization': 'Organisation', + 'admin.agents.details.suspension.owner': 'Propriétaire', + 'admin.agents.details.suspension.cascade': 'Suspension du compte du propriétaire', 'admin.applications.list.title': 'Applications', 'admin.applications.list.columns.name': 'Nom', 'admin.applications.list.columns.client_id': 'ID client', diff --git a/packages/javascript/src/i18n/translations/hi-IN.ts b/packages/javascript/src/i18n/translations/hi-IN.ts index 42373dbb..2cfe84f2 100644 --- a/packages/javascript/src/i18n/translations/hi-IN.ts +++ b/packages/javascript/src/i18n/translations/hi-IN.ts @@ -158,6 +158,43 @@ const translations: I18nTranslations = { 'user.change_password.generic.error': 'आपका {credentialLower} अपडेट करते समय त्रुटि हुई। कृपया पुनः प्रयास करें।', 'user.change_password.unavailable.heading': '{credential} परिवर्तन उपलब्ध नहीं है', 'user.change_password.unavailable.description': 'कृपया अपने व्यवस्थापक से संपर्क करें।', + + /* Personal agents */ + 'user.agents.title': 'व्यक्तिगत एजेंट', + 'user.agents.description': 'एजेंट जो केवल आपकी ओर से कार्य करते हैं।', + 'user.agents.list.columns.name': 'नाम', + 'user.agents.list.columns.status': 'स्थिति', + 'user.agents.list.empty': 'आपके पास कोई व्यक्तिगत एजेंट नहीं है।', + 'user.agents.list.error': 'आपके एजेंट लोड नहीं हो सके। कृपया पुनः प्रयास करें।', + 'user.agents.suspend_all.action': 'सभी को निलंबित करें', + 'user.agents.suspend_all.confirm': 'अपने सभी व्यक्तिगत एजेंट निलंबित करें? निलंबन हटाने तक उनकी पहुंच बंद रहेगी।', + 'user.agents.suspend_all.done': 'निलंबित एजेंट: {count}', + 'user.agents.details.overview': 'अवलोकन', + 'user.agents.details.attributes': 'विशेषताएँ', + 'user.agents.details.client_id': 'क्लाइंट ID', + 'user.agents.details.grant_types': 'ग्रांट प्रकार', + 'user.agents.details.redirect_uris': 'रीडायरेक्ट URI', + 'user.agents.details.none': 'कोई नहीं', + 'user.agents.details.error': 'यह एजेंट लोड नहीं हो सका। कृपया पुनः प्रयास करें।', + 'user.agents.suspension.owner': 'आपने इस एजेंट को निलंबित किया है।', + 'user.agents.suspension.organization': + 'आपके संगठन ने इस एजेंट को निलंबित किया है। केवल व्यवस्थापक ही वह निलंबन हटा सकता है।', + 'user.agents.suspension.cascade': 'जब तक आपका खाता निलंबित है, यह एजेंट निलंबित रहेगा।', + 'user.agents.suspend.action': 'निलंबित करें', + 'user.agents.suspend.confirm': '{name} को निलंबित करें? निलंबन हटाने तक इसकी पहुंच बंद रहेगी।', + 'user.agents.unsuspend.action': 'निलंबन हटाएं', + 'user.agents.action.error': 'कार्रवाई पूरी नहीं हो सकी। कृपया पुनः प्रयास करें।', + 'user.agents.edit.action': 'संपादित करें', + 'user.agents.edit.title': 'एजेंट संपादित करें', + 'user.agents.edit.save': 'परिवर्तन सहेजें', + 'user.agents.fields.name': 'नाम', + 'user.agents.fields.description': 'विवरण', + 'user.agents.fields.redirect_uris_hint': 'ऑथराइज़ेशन कोड ग्रांट के लिए आवश्यक। URI को अल्पविराम से अलग करें।', + 'user.agents.grant_types.authorization_code': 'ऑथराइज़ेशन कोड', + 'user.agents.grant_types.ciba': 'बैकचैनल प्रमाणीकरण (CIBA)', + 'user.agents.grant_types.refresh_token': 'रिफ्रेश टोकन', + 'user.agents.delete.action': 'एजेंट हटाएं', + 'user.agents.delete.confirm': '{name} को हटाएं? इसे पूर्ववत नहीं किया जा सकता।', 'validation.password.pattern': 'आवश्यक प्रारूप से मेल खाता है', /* |---------------------------------------------------------------| */ @@ -451,6 +488,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'एजेंट हटाएं', 'admin.agents.details.delete.confirm': '{name} को हटाएं?', 'admin.agents.details.delete.error': 'एजेंट को हटाया नहीं जा सका। कृपया फिर से प्रयास करें।', + 'admin.agents.kind.personal': 'व्यक्तिगत', + 'admin.agents.details.kind': 'श्रेणी', + 'admin.agents.details.suspension.title': 'द्वारा निलंबित', + 'admin.agents.details.suspension.organization': 'संगठन', + 'admin.agents.details.suspension.owner': 'स्वामी', + 'admin.agents.details.suspension.cascade': 'स्वामी के खाते का निलंबन', 'admin.applications.list.title': 'एप्लिकेशन', 'admin.applications.list.columns.name': 'नाम', 'admin.applications.list.columns.client_id': 'क्लाइंट आईडी', diff --git a/packages/javascript/src/i18n/translations/ja-JP.ts b/packages/javascript/src/i18n/translations/ja-JP.ts index 776b0ef4..c2e60b1f 100644 --- a/packages/javascript/src/i18n/translations/ja-JP.ts +++ b/packages/javascript/src/i18n/translations/ja-JP.ts @@ -159,6 +159,44 @@ const translations: I18nTranslations = { 'user.change_password.generic.error': '{credentialLower}の更新中にエラーが発生しました。もう一度お試しください。', 'user.change_password.unavailable.heading': '{credential}の変更はできません', 'user.change_password.unavailable.description': '管理者にお問い合わせください。', + + /* Personal agents */ + 'user.agents.title': '個人用エージェント', + 'user.agents.description': 'あなたの代わりにのみ動作するエージェントです。', + 'user.agents.list.columns.name': '名前', + 'user.agents.list.columns.status': 'ステータス', + 'user.agents.list.empty': '個人用エージェントはありません。', + 'user.agents.list.error': 'エージェントを読み込めませんでした。もう一度お試しください。', + 'user.agents.suspend_all.action': 'すべて停止', + 'user.agents.suspend_all.confirm': + 'すべての個人用エージェントを停止しますか?停止を解除するまでアクセスできなくなります。', + 'user.agents.suspend_all.done': '停止したエージェント: {count}', + 'user.agents.details.overview': '概要', + 'user.agents.details.attributes': '属性', + 'user.agents.details.client_id': 'クライアントID', + 'user.agents.details.grant_types': 'グラントタイプ', + 'user.agents.details.redirect_uris': 'リダイレクトURI', + 'user.agents.details.none': 'なし', + 'user.agents.details.error': 'このエージェントを読み込めませんでした。もう一度お試しください。', + 'user.agents.suspension.owner': 'あなたがこのエージェントを停止しました。', + 'user.agents.suspension.organization': + '組織がこのエージェントを停止しました。この停止を解除できるのは管理者のみです。', + 'user.agents.suspension.cascade': 'アカウントが停止されている間、このエージェントは停止されたままです。', + 'user.agents.suspend.action': '停止', + 'user.agents.suspend.confirm': '{name} を停止しますか?停止を解除するまでアクセスできなくなります。', + 'user.agents.unsuspend.action': '停止を解除', + 'user.agents.action.error': '操作を完了できませんでした。もう一度お試しください。', + 'user.agents.edit.action': '編集', + 'user.agents.edit.title': 'エージェントを編集', + 'user.agents.edit.save': '変更を保存', + 'user.agents.fields.name': '名前', + 'user.agents.fields.description': '説明', + 'user.agents.fields.redirect_uris_hint': '認可コードグラントに必要です。複数のURIはカンマで区切ってください。', + 'user.agents.grant_types.authorization_code': '認可コード', + 'user.agents.grant_types.ciba': 'バックチャネル認証 (CIBA)', + 'user.agents.grant_types.refresh_token': 'リフレッシュトークン', + 'user.agents.delete.action': 'エージェントを削除', + 'user.agents.delete.confirm': '{name} を削除しますか?この操作は元に戻せません。', 'validation.password.pattern': '必要な形式に一致しています', /* |---------------------------------------------------------------| */ @@ -453,6 +491,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'エージェントを削除', 'admin.agents.details.delete.confirm': '{name} を削除しますか?', 'admin.agents.details.delete.error': 'エージェントを削除できませんでした。もう一度お試しください。', + 'admin.agents.kind.personal': '個人用', + 'admin.agents.details.kind': '種類', + 'admin.agents.details.suspension.title': '停止元', + 'admin.agents.details.suspension.organization': '組織', + 'admin.agents.details.suspension.owner': '所有者', + 'admin.agents.details.suspension.cascade': '所有者のアカウント停止', 'admin.applications.list.title': 'アプリケーション', 'admin.applications.list.columns.name': '名前', 'admin.applications.list.columns.client_id': 'クライアントID', diff --git a/packages/javascript/src/i18n/translations/pt-BR.ts b/packages/javascript/src/i18n/translations/pt-BR.ts index a79296dc..394d57b8 100644 --- a/packages/javascript/src/i18n/translations/pt-BR.ts +++ b/packages/javascript/src/i18n/translations/pt-BR.ts @@ -159,6 +159,45 @@ const translations: I18nTranslations = { 'user.change_password.generic.error': 'Ocorreu um erro ao atualizar seu {credentialLower}. Tente novamente.', 'user.change_password.unavailable.heading': 'Alteração de {credentialLower} indisponível', 'user.change_password.unavailable.description': 'Entre em contato com o administrador.', + + /* Personal agents */ + 'user.agents.title': 'Agentes pessoais', + 'user.agents.description': 'Agentes que agem somente em seu nome.', + 'user.agents.list.columns.name': 'Nome', + 'user.agents.list.columns.status': 'Status', + 'user.agents.list.empty': 'Você não tem agentes pessoais.', + 'user.agents.list.error': 'Não foi possível carregar seus agentes. Tente novamente.', + 'user.agents.suspend_all.action': 'Suspender todos', + 'user.agents.suspend_all.confirm': + 'Suspender todos os seus agentes pessoais? Eles perdem o acesso até você remover a suspensão.', + 'user.agents.suspend_all.done': 'Agentes suspensos: {count}', + 'user.agents.details.overview': 'Visão geral', + 'user.agents.details.attributes': 'Atributos', + 'user.agents.details.client_id': 'ID do cliente', + 'user.agents.details.grant_types': 'Tipos de concessão', + 'user.agents.details.redirect_uris': 'URIs de redirecionamento', + 'user.agents.details.none': 'Nenhum', + 'user.agents.details.error': 'Não foi possível carregar este agente. Tente novamente.', + 'user.agents.suspension.owner': 'Você suspendeu este agente.', + 'user.agents.suspension.organization': + 'Sua organização suspendeu este agente. Somente um administrador pode remover essa suspensão.', + 'user.agents.suspension.cascade': 'Este agente fica suspenso enquanto sua conta estiver suspensa.', + 'user.agents.suspend.action': 'Suspender', + 'user.agents.suspend.confirm': 'Suspender {name}? Ele perde o acesso até você remover a suspensão.', + 'user.agents.unsuspend.action': 'Remover suspensão', + 'user.agents.action.error': 'Não foi possível concluir a ação. Tente novamente.', + 'user.agents.edit.action': 'Editar', + 'user.agents.edit.title': 'Editar agente', + 'user.agents.edit.save': 'Salvar alterações', + 'user.agents.fields.name': 'Nome', + 'user.agents.fields.description': 'Descrição', + 'user.agents.fields.redirect_uris_hint': + 'Necessário para a concessão de código de autorização. Separe as URIs com vírgulas.', + 'user.agents.grant_types.authorization_code': 'Código de autorização', + 'user.agents.grant_types.ciba': 'Autenticação por canal secundário (CIBA)', + 'user.agents.grant_types.refresh_token': 'Token de atualização', + 'user.agents.delete.action': 'Excluir agente', + 'user.agents.delete.confirm': 'Excluir {name}? Esta ação não pode ser desfeita.', 'validation.password.pattern': 'Corresponde ao formato exigido', /* |---------------------------------------------------------------| */ @@ -458,6 +497,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'Excluir agente', 'admin.agents.details.delete.confirm': 'Excluir {name}?', 'admin.agents.details.delete.error': 'Não foi possível excluir o agente. Tente novamente.', + 'admin.agents.kind.personal': 'Pessoal', + 'admin.agents.details.kind': 'Categoria', + 'admin.agents.details.suspension.title': 'Suspenso por', + 'admin.agents.details.suspension.organization': 'Organização', + 'admin.agents.details.suspension.owner': 'Responsável', + 'admin.agents.details.suspension.cascade': 'Suspensão da conta do responsável', 'admin.applications.list.title': 'Aplicações', 'admin.applications.list.columns.name': 'Nome', 'admin.applications.list.columns.client_id': 'ID do cliente', diff --git a/packages/javascript/src/i18n/translations/pt-PT.ts b/packages/javascript/src/i18n/translations/pt-PT.ts index eced27bc..41265c43 100644 --- a/packages/javascript/src/i18n/translations/pt-PT.ts +++ b/packages/javascript/src/i18n/translations/pt-PT.ts @@ -159,6 +159,45 @@ const translations: I18nTranslations = { 'user.change_password.generic.error': 'Ocorreu um erro ao actualizar o seu {credentialLower}. Tente novamente.', 'user.change_password.unavailable.heading': 'Alteração de {credentialLower} indisponível', 'user.change_password.unavailable.description': 'Contacte o seu administrador.', + + /* Personal agents */ + 'user.agents.title': 'Agentes pessoais', + 'user.agents.description': 'Agentes que agem apenas em seu nome.', + 'user.agents.list.columns.name': 'Nome', + 'user.agents.list.columns.status': 'Estado', + 'user.agents.list.empty': 'Não tem agentes pessoais.', + 'user.agents.list.error': 'Não foi possível carregar os seus agentes. Tente novamente.', + 'user.agents.suspend_all.action': 'Suspender todos', + 'user.agents.suspend_all.confirm': + 'Suspender todos os seus agentes pessoais? Perdem o acesso até levantar a suspensão.', + 'user.agents.suspend_all.done': 'Agentes suspensos: {count}', + 'user.agents.details.overview': 'Vista geral', + 'user.agents.details.attributes': 'Atributos', + 'user.agents.details.client_id': 'ID de cliente', + 'user.agents.details.grant_types': 'Tipos de concessão', + 'user.agents.details.redirect_uris': 'URIs de redirecionamento', + 'user.agents.details.none': 'Nenhum', + 'user.agents.details.error': 'Não foi possível carregar este agente. Tente novamente.', + 'user.agents.suspension.owner': 'Suspendeu este agente.', + 'user.agents.suspension.organization': + 'A sua organização suspendeu este agente. Só um administrador pode levantar essa suspensão.', + 'user.agents.suspension.cascade': 'Este agente fica suspenso enquanto a sua conta estiver suspensa.', + 'user.agents.suspend.action': 'Suspender', + 'user.agents.suspend.confirm': 'Suspender {name}? Perde o acesso até levantar a suspensão.', + 'user.agents.unsuspend.action': 'Levantar suspensão', + 'user.agents.action.error': 'Não foi possível concluir a ação. Tente novamente.', + 'user.agents.edit.action': 'Editar', + 'user.agents.edit.title': 'Editar agente', + 'user.agents.edit.save': 'Guardar alterações', + 'user.agents.fields.name': 'Nome', + 'user.agents.fields.description': 'Descrição', + 'user.agents.fields.redirect_uris_hint': + 'Necessário para a concessão de código de autorização. Separe os URIs com vírgulas.', + 'user.agents.grant_types.authorization_code': 'Código de autorização', + 'user.agents.grant_types.ciba': 'Autenticação por canal secundário (CIBA)', + 'user.agents.grant_types.refresh_token': 'Token de atualização', + 'user.agents.delete.action': 'Eliminar agente', + 'user.agents.delete.confirm': 'Eliminar {name}? Esta ação não pode ser anulada.', 'validation.password.pattern': 'Corresponde ao formato exigido', /* |---------------------------------------------------------------| */ @@ -458,6 +497,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'Eliminar agente', 'admin.agents.details.delete.confirm': 'Eliminar {name}?', 'admin.agents.details.delete.error': 'Não foi possível eliminar o agente. Tente novamente.', + 'admin.agents.kind.personal': 'Pessoal', + 'admin.agents.details.kind': 'Categoria', + 'admin.agents.details.suspension.title': 'Suspenso por', + 'admin.agents.details.suspension.organization': 'Organização', + 'admin.agents.details.suspension.owner': 'Responsável', + 'admin.agents.details.suspension.cascade': 'Suspensão da conta do responsável', 'admin.applications.list.title': 'Aplicações', 'admin.applications.list.columns.name': 'Nome', 'admin.applications.list.columns.client_id': 'ID de cliente', diff --git a/packages/javascript/src/i18n/translations/si-LK.ts b/packages/javascript/src/i18n/translations/si-LK.ts index e157c5a1..b0ceea0c 100644 --- a/packages/javascript/src/i18n/translations/si-LK.ts +++ b/packages/javascript/src/i18n/translations/si-LK.ts @@ -160,6 +160,44 @@ const translations: I18nTranslations = { 'ඔබේ {credentialLower} යාවත්කාලීන කිරීමේදී දෝෂයක් ඇතිවිය. කරුණාකර නැවත උත්සාහ කරන්න.', 'user.change_password.unavailable.heading': '{credential} වෙනස් කිරීම් ලබා ගත නොහැක', 'user.change_password.unavailable.description': 'කරුණාකර ඔබේ පරිපාලක සම්බන්ධ කර ගන්න.', + + /* Personal agents */ + 'user.agents.title': 'පුද්ගලික නියෝජිතයින්', + 'user.agents.description': 'ඔබ වෙනුවෙන් පමණක් ක්‍රියා කරන නියෝජිතයින්.', + 'user.agents.list.columns.name': 'නම', + 'user.agents.list.columns.status': 'තත්ත්වය', + 'user.agents.list.empty': 'ඔබට පුද්ගලික නියෝජිතයින් නැත.', + 'user.agents.list.error': 'ඔබේ නියෝජිතයින් පූරණය කළ නොහැකි විය. නැවත උත්සාහ කරන්න.', + 'user.agents.suspend_all.action': 'සියල්ල අත්හිටුවන්න', + 'user.agents.suspend_all.confirm': + 'ඔබේ සියලුම පුද්ගලික නියෝජිතයින් අත්හිටුවන්නද? අත්හිටුවීම ඉවත් කරන තුරු ඒවාට ප්‍රවේශය අහිමි වේ.', + 'user.agents.suspend_all.done': 'අත්හිටුවූ නියෝජිතයින්: {count}', + 'user.agents.details.overview': 'දළ විශ්ලේෂණය', + 'user.agents.details.attributes': 'ගුණාංග', + 'user.agents.details.client_id': 'සේවාලාභී ID', + 'user.agents.details.grant_types': 'ප්‍රදාන වර්ග', + 'user.agents.details.redirect_uris': 'යළි-යොමු URI', + 'user.agents.details.none': 'කිසිවක් නැත', + 'user.agents.details.error': 'මෙම නියෝජිතයා පූරණය කළ නොහැකි විය. නැවත උත්සාහ කරන්න.', + 'user.agents.suspension.owner': 'ඔබ මෙම නියෝජිතයා අත්හිටුවා ඇත.', + 'user.agents.suspension.organization': + 'ඔබේ සංවිධානය මෙම නියෝජිතයා අත්හිටුවා ඇත. එම අත්හිටුවීම ඉවත් කළ හැක්කේ පරිපාලකයෙකුට පමණි.', + 'user.agents.suspension.cascade': 'ඔබේ ගිණුම අත්හිටුවා ඇති තාක් මෙම නියෝජිතයා අත්හිටුවා තිබේ.', + 'user.agents.suspend.action': 'අත්හිටුවන්න', + 'user.agents.suspend.confirm': '{name} අත්හිටුවන්නද? අත්හිටුවීම ඉවත් කරන තුරු එයට ප්‍රවේශය අහිමි වේ.', + 'user.agents.unsuspend.action': 'අත්හිටුවීම ඉවත් කරන්න', + 'user.agents.action.error': 'ක්‍රියාව සම්පූර්ණ කළ නොහැකි විය. නැවත උත්සාහ කරන්න.', + 'user.agents.edit.action': 'සංස්කරණය කරන්න', + 'user.agents.edit.title': 'නියෝජිතයා සංස්කරණය කරන්න', + 'user.agents.edit.save': 'වෙනස්කම් සුරකින්න', + 'user.agents.fields.name': 'නම', + 'user.agents.fields.description': 'විස්තරය', + 'user.agents.fields.redirect_uris_hint': 'අවසර කේත ප්‍රදානය සඳහා අවශ්‍යයි. URI කොමා මගින් වෙන් කරන්න.', + 'user.agents.grant_types.authorization_code': 'අවසර කේතය', + 'user.agents.grant_types.ciba': 'පසු නාලිකා සත්‍යාපනය (CIBA)', + 'user.agents.grant_types.refresh_token': 'නැවුම් කිරීමේ ටෝකනය', + 'user.agents.delete.action': 'නියෝජිතයා මකන්න', + 'user.agents.delete.confirm': '{name} මකන්නද? මෙය අහෝසි කළ නොහැක.', 'validation.password.pattern': 'අවශ්‍ය ආකෘතියට ගැලපේ', /* |---------------------------------------------------------------| */ @@ -453,6 +491,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'නියෝජිතයා මකන්න', 'admin.agents.details.delete.confirm': '{name} මකන්නද?', 'admin.agents.details.delete.error': 'නියෝජිතයා මැකිය නොහැකි විය. නැවත උත්සාහ කරන්න.', + 'admin.agents.kind.personal': 'පුද්ගලික', + 'admin.agents.details.kind': 'වර්ගය', + 'admin.agents.details.suspension.title': 'අත්හිටුවූයේ', + 'admin.agents.details.suspension.organization': 'සංවිධානය', + 'admin.agents.details.suspension.owner': 'හිමිකරු', + 'admin.agents.details.suspension.cascade': 'හිමිකරුගේ ගිණුම අත්හිටුවීම', 'admin.applications.list.title': 'යෙදුම්', 'admin.applications.list.columns.name': 'නම', 'admin.applications.list.columns.client_id': 'සේවාලාභී හැඳුනුම්පත', diff --git a/packages/javascript/src/i18n/translations/ta-IN.ts b/packages/javascript/src/i18n/translations/ta-IN.ts index c10e5ba4..787b7590 100644 --- a/packages/javascript/src/i18n/translations/ta-IN.ts +++ b/packages/javascript/src/i18n/translations/ta-IN.ts @@ -161,6 +161,46 @@ const translations: I18nTranslations = { 'உங்கள் {credentialLower}-ஐ புதுப்பிக்கும் போது பிழை ஏற்பட்டது. மீண்டும் முயற்சிக்கவும்.', 'user.change_password.unavailable.heading': '{credential} மாற்றங்கள் கிடைக்கவில்லை', 'user.change_password.unavailable.description': 'உங்கள் நிர்வாகியை தொடர்பு கொள்ளவும்.', + + /* Personal agents */ + 'user.agents.title': 'தனிப்பட்ட முகவர்கள்', + 'user.agents.description': 'உங்கள் சார்பாக மட்டுமே செயல்படும் முகவர்கள்.', + 'user.agents.list.columns.name': 'பெயர்', + 'user.agents.list.columns.status': 'நிலை', + 'user.agents.list.empty': 'உங்களிடம் தனிப்பட்ட முகவர்கள் இல்லை.', + 'user.agents.list.error': 'உங்கள் முகவர்களை ஏற்ற முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', + 'user.agents.suspend_all.action': 'அனைத்தையும் இடைநிறுத்து', + 'user.agents.suspend_all.confirm': + 'உங்கள் தனிப்பட்ட முகவர்கள் அனைத்தையும் இடைநிறுத்தவா? இடைநிறுத்தத்தை நீக்கும் வரை அவற்றுக்கு அணுகல் இருக்காது.', + 'user.agents.suspend_all.done': 'இடைநிறுத்தப்பட்ட முகவர்கள்: {count}', + 'user.agents.details.overview': 'மேலோட்டம்', + 'user.agents.details.attributes': 'பண்புகள்', + 'user.agents.details.client_id': 'கிளையன்ட் ID', + 'user.agents.details.grant_types': 'வழங்கல் வகைகள்', + 'user.agents.details.redirect_uris': 'திசைதிருப்பு URIகள்', + 'user.agents.details.none': 'எதுவும் இல்லை', + 'user.agents.details.error': 'இந்த முகவரை ஏற்ற முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', + 'user.agents.suspension.owner': 'நீங்கள் இந்த முகவரை இடைநிறுத்தியுள்ளீர்கள்.', + 'user.agents.suspension.organization': + 'உங்கள் நிறுவனம் இந்த முகவரை இடைநிறுத்தியுள்ளது. அந்த இடைநிறுத்தத்தை நிர்வாகி மட்டுமே நீக்க முடியும்.', + 'user.agents.suspension.cascade': + 'உங்கள் கணக்கு இடைநிறுத்தப்பட்டிருக்கும் வரை இந்த முகவர் இடைநிறுத்தப்பட்டிருக்கும்.', + 'user.agents.suspend.action': 'இடைநிறுத்து', + 'user.agents.suspend.confirm': '{name} ஐ இடைநிறுத்தவா? இடைநிறுத்தத்தை நீக்கும் வரை அதற்கு அணுகல் இருக்காது.', + 'user.agents.unsuspend.action': 'இடைநிறுத்தத்தை நீக்கு', + 'user.agents.action.error': 'செயலை முடிக்க முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', + 'user.agents.edit.action': 'திருத்து', + 'user.agents.edit.title': 'முகவரைத் திருத்து', + 'user.agents.edit.save': 'மாற்றங்களைச் சேமி', + 'user.agents.fields.name': 'பெயர்', + 'user.agents.fields.description': 'விளக்கம்', + 'user.agents.fields.redirect_uris_hint': + 'அங்கீகாரக் குறியீடு வழங்கலுக்குத் தேவை. URIகளைக் காற்புள்ளிகளால் பிரிக்கவும்.', + 'user.agents.grant_types.authorization_code': 'அங்கீகாரக் குறியீடு', + 'user.agents.grant_types.ciba': 'பின்தள அங்கீகாரம் (CIBA)', + 'user.agents.grant_types.refresh_token': 'புதுப்பிப்பு டோக்கன்', + 'user.agents.delete.action': 'முகவரை நீக்கு', + 'user.agents.delete.confirm': '{name} ஐ நீக்கவா? இதைத் திரும்பப் பெற முடியாது.', 'validation.password.pattern': 'தேவையான வடிவமைப்பிற்கு பொருந்துகிறது', /* |---------------------------------------------------------------| */ @@ -458,6 +498,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'முகவரை நீக்கு', 'admin.agents.details.delete.confirm': '{name} ஐ நீக்கவா?', 'admin.agents.details.delete.error': 'முகவரை நீக்க முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', + 'admin.agents.kind.personal': 'தனிப்பட்ட', + 'admin.agents.details.kind': 'பிரிவு', + 'admin.agents.details.suspension.title': 'இடைநிறுத்தியவர்', + 'admin.agents.details.suspension.organization': 'நிறுவனம்', + 'admin.agents.details.suspension.owner': 'உரிமையாளர்', + 'admin.agents.details.suspension.cascade': 'உரிமையாளரின் கணக்கு இடைநிறுத்தம்', 'admin.applications.list.title': 'பயன்பாடுகள்', 'admin.applications.list.columns.name': 'பெயர்', 'admin.applications.list.columns.client_id': 'கிளையன்ட் ஐடி', diff --git a/packages/javascript/src/i18n/translations/te-IN.ts b/packages/javascript/src/i18n/translations/te-IN.ts index d29da93c..8f2977b3 100644 --- a/packages/javascript/src/i18n/translations/te-IN.ts +++ b/packages/javascript/src/i18n/translations/te-IN.ts @@ -161,6 +161,44 @@ const translations: I18nTranslations = { 'మీ {credentialLower} నవీకరించేటప్పుడు లోపం వచ్చింది. దయచేసి మళ్లీ ప్రయత్నించండి.', 'user.change_password.unavailable.heading': '{credential} మార్పులు అందుబాటులో లేవు', 'user.change_password.unavailable.description': 'దయచేసి మీ నిర్వాహకుడిని సంప్రదించండి.', + + /* Personal agents */ + 'user.agents.title': 'వ్యక్తిగత ఏజెంట్లు', + 'user.agents.description': 'మీ తరపున మాత్రమే పనిచేసే ఏజెంట్లు.', + 'user.agents.list.columns.name': 'పేరు', + 'user.agents.list.columns.status': 'స్థితి', + 'user.agents.list.empty': 'మీకు వ్యక్తిగత ఏజెంట్లు ఏవీ లేవు.', + 'user.agents.list.error': 'మీ ఏజెంట్లను లోడ్ చేయడం సాధ్యం కాలేదు. దయచేసి మళ్లీ ప్రయత్నించండి.', + 'user.agents.suspend_all.action': 'అన్నింటినీ నిలిపివేయి', + 'user.agents.suspend_all.confirm': + 'మీ వ్యక్తిగత ఏజెంట్లన్నింటినీ నిలిపివేయాలా? మీరు నిలిపివేతను తొలగించే వరకు వాటికి యాక్సెస్ ఉండదు.', + 'user.agents.suspend_all.done': 'నిలిపివేసిన ఏజెంట్లు: {count}', + 'user.agents.details.overview': 'అవలోకనం', + 'user.agents.details.attributes': 'లక్షణాలు', + 'user.agents.details.client_id': 'క్లయింట్ ID', + 'user.agents.details.grant_types': 'గ్రాంట్ రకాలు', + 'user.agents.details.redirect_uris': 'రీడైరెక్ట్ URIలు', + 'user.agents.details.none': 'ఏదీ లేదు', + 'user.agents.details.error': 'ఈ ఏజెంట్‌ను లోడ్ చేయడం సాధ్యం కాలేదు. దయచేసి మళ్లీ ప్రయత్నించండి.', + 'user.agents.suspension.owner': 'మీరు ఈ ఏజెంట్‌ను నిలిపివేశారు.', + 'user.agents.suspension.organization': + 'మీ సంస్థ ఈ ఏజెంట్‌ను నిలిపివేసింది. ఆ నిలిపివేతను నిర్వాహకుడు మాత్రమే తొలగించగలరు.', + 'user.agents.suspension.cascade': 'మీ ఖాతా నిలిపివేయబడి ఉన్నంత వరకు ఈ ఏజెంట్ నిలిపివేయబడి ఉంటుంది.', + 'user.agents.suspend.action': 'నిలిపివేయి', + 'user.agents.suspend.confirm': '{name} ను నిలిపివేయాలా? మీరు నిలిపివేతను తొలగించే వరకు దానికి యాక్సెస్ ఉండదు.', + 'user.agents.unsuspend.action': 'నిలిపివేతను తొలగించు', + 'user.agents.action.error': 'చర్యను పూర్తి చేయడం సాధ్యం కాలేదు. దయచేసి మళ్లీ ప్రయత్నించండి.', + 'user.agents.edit.action': 'సవరించు', + 'user.agents.edit.title': 'ఏజెంట్‌ను సవరించు', + 'user.agents.edit.save': 'మార్పులను సేవ్ చేయి', + 'user.agents.fields.name': 'పేరు', + 'user.agents.fields.description': 'వివరణ', + 'user.agents.fields.redirect_uris_hint': 'ఆథరైజేషన్ కోడ్ గ్రాంట్‌కు అవసరం. URIలను కామాలతో వేరు చేయండి.', + 'user.agents.grant_types.authorization_code': 'ఆథరైజేషన్ కోడ్', + 'user.agents.grant_types.ciba': 'బ్యాక్‌చానెల్ ప్రామాణీకరణ (CIBA)', + 'user.agents.grant_types.refresh_token': 'రిఫ్రెష్ టోకెన్', + 'user.agents.delete.action': 'ఏజెంట్‌ను తొలగించు', + 'user.agents.delete.confirm': '{name} ను తొలగించాలా? దీన్ని రద్దు చేయడం సాధ్యం కాదు.', 'validation.password.pattern': 'అవసరమైన ఫార్మాట్‌కు సరిపోతుంది', /* |---------------------------------------------------------------| */ @@ -458,6 +496,12 @@ const translations: I18nTranslations = { 'admin.agents.details.delete.action': 'ఏజెంట్‌ను తొలగించు', 'admin.agents.details.delete.confirm': '{name} ను తొలగించాలా?', 'admin.agents.details.delete.error': 'ఏజెంట్‌ను తొలగించలేకపోయాము. దయచేసి మళ్లీ ప్రయత్నించండి.', + 'admin.agents.kind.personal': 'వ్యక్తిగత', + 'admin.agents.details.kind': 'వర్గం', + 'admin.agents.details.suspension.title': 'నిలిపివేసినవారు', + 'admin.agents.details.suspension.organization': 'సంస్థ', + 'admin.agents.details.suspension.owner': 'యజమాని', + 'admin.agents.details.suspension.cascade': 'యజమాని ఖాతా నిలిపివేత', 'admin.applications.list.title': 'అప్లికేషన్‌లు', 'admin.applications.list.columns.name': 'పేరు', 'admin.applications.list.columns.client_id': 'క్లయింట్ ID', diff --git a/packages/javascript/src/index.ts b/packages/javascript/src/index.ts index 2bc74636..e80d52ac 100644 --- a/packages/javascript/src/index.ts +++ b/packages/javascript/src/index.ts @@ -32,6 +32,20 @@ export {default as updateMeCredentials} from './api/account/updateMeCredentials' export type {UpdateMeCredentialsConfig} from './api/account/updateMeCredentials'; export {default as updateMeProfile} from './api/account/updateMeProfile'; export type {UpdateMeProfileConfig} from './api/account/updateMeProfile'; +export {default as getMeAgents} from './api/account/getMeAgents'; +export type {GetMeAgentsConfig} from './api/account/getMeAgents'; +export {default as getMeAgent} from './api/account/getMeAgent'; +export type {GetMeAgentConfig} from './api/account/getMeAgent'; +export {default as updateMeAgent} from './api/account/updateMeAgent'; +export type {UpdateMeAgentConfig} from './api/account/updateMeAgent'; +export {default as deleteMeAgent} from './api/account/deleteMeAgent'; +export type {DeleteMeAgentConfig} from './api/account/deleteMeAgent'; +export {default as suspendMeAgent} from './api/account/suspendMeAgent'; +export type {SuspendMeAgentConfig} from './api/account/suspendMeAgent'; +export {default as unsuspendMeAgent} from './api/account/unsuspendMeAgent'; +export type {UnsuspendMeAgentConfig} from './api/account/unsuspendMeAgent'; +export {default as suspendAllMeAgents} from './api/account/suspendAllMeAgents'; +export type {SuspendAllMeAgentsConfig} from './api/account/suspendAllMeAgents'; export {default as getApplications} from './api/management/applications/getApplications'; export type {GetApplicationsConfig} from './api/management/applications/getApplications'; @@ -751,6 +765,7 @@ export type { AccessStatus, AccessStatusDetails, AccessStatusValue, + SuspensionAppliedBy, } from './models/access-status'; export type { CreateManagedUserRequest, @@ -975,6 +990,7 @@ export type {ManagedUserType, ManagedUserTypeListResponse} from './models/manage export type { Agent, AgentInboundAuthConfig, + AgentKind, AgentListResponse, AgentLoginConsentConfig, AgentOwner, @@ -984,7 +1000,14 @@ export type { AgentTypeListResponse, BasicAgent, CreateAgentRequest, + SuspendAllMeAgentsResponse, UpdateAgentRequest, + UpdateMeAgentRequest, +} from './models/agent-resource'; +export { + PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS, + PERSONAL_AGENT_GRANT_TYPES, + PERSONAL_AGENT_KIND, } from './models/agent-resource'; export type { CreateRoleRequest, @@ -1074,7 +1097,16 @@ export { export type {SharingPolicyFormValues, SharingPolicyOperations, SharingResourceType} from './utils/sharingPolicies'; export {default as resolveManagedIdentityName} from './utils/resolveManagedIdentityName'; export {default as getAgentName} from './utils/getAgentName'; +export {default as isPersonalAgent} from './utils/isPersonalAgent'; export {default as getAccountLifecycleActions} from './utils/getAccountLifecycleActions'; +export {default as getMeAgentSuspensionAction} from './utils/getMeAgentSuspensionAction'; +export { + getPersonalAgentOAuthConfig, + isPersonalAgentFormValid, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, +} from './utils/personalAgentForm'; +export type {PersonalAgentFormValues} from './utils/personalAgentForm'; export {default as hasPermission} from './utils/hasPermission'; export type {PermissionMatching} from './utils/hasPermission'; export {default as arrayBufferToBase64url} from './utils/arrayBufferToBase64url'; diff --git a/packages/javascript/src/models/access-status.ts b/packages/javascript/src/models/access-status.ts index f7e1d808..c4311da6 100644 --- a/packages/javascript/src/models/access-status.ts +++ b/packages/javascript/src/models/access-status.ts @@ -10,7 +10,19 @@ export type AccessStatusValue = 'ACTIVE' | 'LOCKED' | 'SUSPENDED'; /** * What put an identity into the status it reports. */ -export type AccessHoldReason = 'ADMINISTRATIVE_SUSPENSION' | 'FAILED_ATTEMPTS' | 'SUSPENSION_RELEASE_LOCK'; +export type AccessHoldReason = + | 'ADMINISTRATIVE_SUSPENSION' + | 'CASCADED_SUSPENSION' + | 'FAILED_ATTEMPTS' + | 'OWNER_SUSPENSION' + | 'SUSPENSION_RELEASE_LOCK'; + +/** + * Who placed a suspension: the organization, the identity's owner (such as the owner of an agent), + * or `cascade` for one carried from the identity it depends on, such as a personal agent's owner, while + * that identity is suspended. Each suspension is independent and is lifted only by whoever placed it. + */ +export type SuspensionAppliedBy = 'cascade' | 'organization' | 'owner'; /** * One live automatic lock: the authentication method it holds, and when it lifts. @@ -30,6 +42,12 @@ export interface AccessLockedMethod { * What a management read says about a status beyond its value. */ export interface AccessStatusDetails { + /** + * Who placed each suspension in force. Present only when the status is `SUSPENDED`, and only for an + * identity that can be suspended by more than the organization, such as a personal agent. Absent means + * the organization's. + */ + appliedBy?: SuspensionAppliedBy[]; /** * Every live automatic lock. Absent for a status that is not a lock. */ diff --git a/packages/javascript/src/models/agent-resource.ts b/packages/javascript/src/models/agent-resource.ts index 911d29e4..6da16259 100644 --- a/packages/javascript/src/models/agent-resource.ts +++ b/packages/javascript/src/models/agent-resource.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {AccessStatus} from './access-status'; -import {AssertionConfig, OAuth2Config} from './application'; +import {AssertionConfig, OAuth2Config, OAuth2GrantTypes} from './application'; /** * Inbound authentication configuration of an agent. @@ -16,9 +16,44 @@ export interface AgentInboundAuthConfig { * Login consent configuration of an agent. */ export interface AgentLoginConsentConfig { + /** + * Asks for consent on every authorization, even when an earlier consent covers it. The server defaults it + * to `true` for a personal agent and to `false` otherwise. + */ + alwaysPrompt?: boolean; validityPeriod?: number; } +/** + * The kind of a personal agent: one that acts only for its owner, a user. + */ +export const PERSONAL_AGENT_KIND = 'personal-assistant'; + +/** + * The kind of an agent: a category set when the agent is created and never changed, which can add rules of + * its own to the agent. Absent for an ordinary agent. Each kind is a constant, such as {@link PERSONAL_AGENT_KIND}. + */ +export type AgentKind = typeof PERSONAL_AGENT_KIND; + +/** + * The only grant types a personal agent can use. Each is labelled by the translation key in + * {@link PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS}. + */ +export const PERSONAL_AGENT_GRANT_TYPES: readonly string[] = [ + OAuth2GrantTypes.AUTHORIZATION_CODE, + OAuth2GrantTypes.CIBA, + OAuth2GrantTypes.REFRESH_TOKEN, +]; + +/** + * The translation key that labels each of the {@link PERSONAL_AGENT_GRANT_TYPES}. + */ +export const PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS: Readonly> = { + [OAuth2GrantTypes.AUTHORIZATION_CODE]: 'user.agents.grant_types.authorization_code', + [OAuth2GrantTypes.CIBA]: 'user.agents.grant_types.ciba', + [OAuth2GrantTypes.REFRESH_TOKEN]: 'user.agents.grant_types.refresh_token', +}; + /** * What an agent owner's `id` holds. */ @@ -66,6 +101,10 @@ export interface Agent { inboundAuthConfig?: AgentInboundAuthConfig[]; isReadOnly?: boolean; isRegistrationFlowEnabled?: boolean; + /** + * The agent's kind, set when the agent is created and never changed. Absent for an ordinary agent. + */ + kind?: AgentKind; loginConsent?: AgentLoginConsentConfig; logoUrl?: string; ouHandle?: string; @@ -96,9 +135,17 @@ export interface BasicAgent { display?: string; id: string; isReadOnly?: boolean; + /** + * The agent's kind, set when the agent is created and never changed. Absent for an ordinary agent. + */ + kind?: AgentKind; logoUrl?: string; ouHandle?: string; ouId: string; + /** + * The effective access status, set by the server on a read. + */ + status?: AccessStatus; type: string; } @@ -122,6 +169,11 @@ export interface CreateAgentRequest { attributes?: Record; description?: string; inboundAuthConfig?: AgentInboundAuthConfig[]; + /** + * The agent's kind, fixed once the agent is created. Omit it for an ordinary agent. A kind can add + * requirements of its own: `personal-assistant` requires `owner` to name a local user. + */ + kind?: AgentKind; logoUrl?: string; /** * The organization unit the agent is created in. Required unless `projectId` is given. @@ -192,3 +244,33 @@ export interface AgentTypeListResponse { totalResults: number; types: AgentType[]; } + +/** + * The part of a personal agent its owner may change, sent whole: `attributes`, `grantTypes` and + * `redirectUris` are required, and a `description` left out is cleared. + */ +export interface UpdateMeAgentRequest { + /** + * The agent's attributes, as its agent type defines them, including `name`. + */ + attributes: Record; + description?: string; + /** + * A subset of {@link PERSONAL_AGENT_GRANT_TYPES}. An empty list removes every grant. + */ + grantTypes: string[]; + /** + * At least one when `grantTypes` holds `authorization_code`. + */ + redirectUris: string[]; +} + +/** + * The result of suspending every personal agent of the signed-in user. + */ +export interface SuspendAllMeAgentsResponse { + /** + * How many agents the request suspended. Agents the owner had already suspended are not counted. + */ + suspendedCount: number; +} diff --git a/packages/javascript/src/models/config.ts b/packages/javascript/src/models/config.ts index 187b1125..62eb56f5 100644 --- a/packages/javascript/src/models/config.ts +++ b/packages/javascript/src/models/config.ts @@ -513,6 +513,12 @@ export interface BaseConfig extends WithPreferences, WithExtensions * If not provided, defaults to `{baseUrl}/users/me`. */ usersMe?: string; + /** + * The collection URL of the agents the signed-in user owns, used by the personal agent self-service + * operations. A single agent is addressed as `{usersMeAgents}/{id}`. + * If not provided, defaults to `{baseUrl}/users/me/agents`. + */ + usersMeAgents?: string; /** * The self-service credential update endpoint URL used to change one of the signed-in * user's own credentials (for example `password` or `pin`). diff --git a/packages/javascript/src/utils/__tests__/getAccountLifecycleActions.test.ts b/packages/javascript/src/utils/__tests__/getAccountLifecycleActions.test.ts index dcccc54e..2908b09d 100644 --- a/packages/javascript/src/utils/__tests__/getAccountLifecycleActions.test.ts +++ b/packages/javascript/src/utils/__tests__/getAccountLifecycleActions.test.ts @@ -46,4 +46,28 @@ describe('getAccountLifecycleActions', () => { it('offers nothing for a status it does not know', () => { expect(getAccountLifecycleActions('user', 'ARCHIVED' as never, allUserFlows)).toEqual([]); }); + + describe('a suspension other parties hold', () => { + const agentFlows: Record = {agentSuspendFlow: 'a', agentUnsuspendFlow: 'b'}; + + it('offers the unsuspend while the organization holds a suspension', () => { + expect(getAccountLifecycleActions('agent', 'SUSPENDED', agentFlows, ['organization', 'owner'])).toEqual([ + 'unsuspend', + ]); + }); + + it("offers the organization's own suspension when only the owner or the cascade holds one", () => { + expect(getAccountLifecycleActions('agent', 'SUSPENDED', agentFlows, ['owner'])).toEqual(['suspend']); + expect(getAccountLifecycleActions('agent', 'SUSPENDED', agentFlows, ['owner', 'cascade'])).toEqual(['suspend']); + }); + + it("reads a suspension that names no party as the organization's", () => { + expect(getAccountLifecycleActions('agent', 'SUSPENDED', agentFlows, [])).toEqual(['unsuspend']); + expect(getAccountLifecycleActions('agent', 'SUSPENDED', agentFlows)).toEqual(['unsuspend']); + }); + + it('ignores the parties for a status that is not a suspension', () => { + expect(getAccountLifecycleActions('agent', 'ACTIVE', agentFlows, ['owner'])).toEqual(['suspend']); + }); + }); }); diff --git a/packages/javascript/src/utils/__tests__/getMeAgentSuspensionAction.test.ts b/packages/javascript/src/utils/__tests__/getMeAgentSuspensionAction.test.ts new file mode 100644 index 00000000..99af3f5c --- /dev/null +++ b/packages/javascript/src/utils/__tests__/getMeAgentSuspensionAction.test.ts @@ -0,0 +1,26 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it} from 'vitest'; +import getMeAgentSuspensionAction from '../getMeAgentSuspensionAction'; + +describe('getMeAgentSuspensionAction', () => { + it('offers the unsuspend while the owner holds the agent suspended', () => { + expect(getMeAgentSuspensionAction({details: {appliedBy: ['owner']}, value: 'SUSPENDED'})).toBe('unsuspend'); + expect(getMeAgentSuspensionAction({details: {appliedBy: ['organization', 'owner']}, value: 'SUSPENDED'})).toBe( + 'unsuspend', + ); + }); + + it("offers the owner's own suspension when only others hold one", () => { + expect(getMeAgentSuspensionAction({details: {appliedBy: ['organization']}, value: 'SUSPENDED'})).toBe('suspend'); + expect(getMeAgentSuspensionAction({details: {appliedBy: ['cascade']}, value: 'SUSPENDED'})).toBe('suspend'); + expect(getMeAgentSuspensionAction({value: 'SUSPENDED'})).toBe('suspend'); + }); + + it('offers the suspension for an agent that is not suspended', () => { + expect(getMeAgentSuspensionAction({value: 'ACTIVE'})).toBe('suspend'); + expect(getMeAgentSuspensionAction({value: 'LOCKED'})).toBe('suspend'); + expect(getMeAgentSuspensionAction(undefined)).toBe('suspend'); + }); +}); diff --git a/packages/javascript/src/utils/__tests__/isPersonalAgent.test.ts b/packages/javascript/src/utils/__tests__/isPersonalAgent.test.ts new file mode 100644 index 00000000..1df0f2f1 --- /dev/null +++ b/packages/javascript/src/utils/__tests__/isPersonalAgent.test.ts @@ -0,0 +1,14 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import isPersonalAgent from '../isPersonalAgent'; + +describe('isPersonalAgent', () => { + it('should be true for an agent of the personal kind', () => { + expect(isPersonalAgent({kind: 'personal-assistant'})).toBe(true); + }); + + it('should be false for an agent with no kind', () => { + expect(isPersonalAgent({})).toBe(false); + }); +}); diff --git a/packages/javascript/src/utils/__tests__/personalAgentForm.test.ts b/packages/javascript/src/utils/__tests__/personalAgentForm.test.ts new file mode 100644 index 00000000..66266a24 --- /dev/null +++ b/packages/javascript/src/utils/__tests__/personalAgentForm.test.ts @@ -0,0 +1,108 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {Agent} from '../../models/agent-resource'; +import { + PersonalAgentFormValues, + getPersonalAgentOAuthConfig, + isPersonalAgentFormValid, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, +} from '../personalAgentForm'; + +const agent: Agent = { + attributes: {name: 'Spending assistant', software: 'assistant-x', tags: ['finance']}, + description: 'Answers questions about my spending', + id: 'a-1', + inboundAuthConfig: [ + { + config: { + grantTypes: ['authorization_code', 'refresh_token'], + redirectUris: ['https://a.example.com/cb', 'https://b.example.com/cb'], + responseTypes: ['code'], + }, + type: 'oauth2', + }, + ], + kind: 'personal-assistant', + ouId: 'ou-1', + type: 'default', +}; + +const values: PersonalAgentFormValues = { + attributes: {software: 'assistant-x'}, + description: 'Answers questions about my spending', + grantTypes: ['authorization_code'], + name: 'Spending assistant', + redirectUris: 'https://a.example.com/cb', +}; + +describe('getPersonalAgentOAuthConfig', () => { + it('should return the OAuth settings of an agent with an OAuth client', () => { + expect(getPersonalAgentOAuthConfig(agent)?.grantTypes).toEqual(['authorization_code', 'refresh_token']); + }); + + it('should return undefined for an agent with no OAuth client', () => { + expect(getPersonalAgentOAuthConfig({...agent, inboundAuthConfig: undefined})).toBeUndefined(); + }); +}); + +describe('toPersonalAgentFormValues', () => { + it('should start from what the server holds, editing only text attributes other than the name', () => { + expect(toPersonalAgentFormValues(agent)).toEqual({ + attributes: {software: 'assistant-x'}, + description: 'Answers questions about my spending', + grantTypes: ['authorization_code', 'refresh_token'], + name: 'Spending assistant', + redirectUris: 'https://a.example.com/cb, https://b.example.com/cb', + }); + }); + + it('should start empty for an agent with no attributes, description or OAuth client', () => { + expect( + toPersonalAgentFormValues({ + ...agent, + attributes: undefined, + description: undefined, + inboundAuthConfig: undefined, + }), + ).toEqual({attributes: {}, description: '', grantTypes: [], name: '', redirectUris: ''}); + }); +}); + +describe('toUpdateMeAgentRequest', () => { + it('should send back the attributes the form does not edit, and trim the text', () => { + expect( + toUpdateMeAgentRequest(agent, { + ...values, + attributes: {software: 'assistant-y'}, + description: ' Budgets ', + name: ' Budget assistant ', + redirectUris: 'https://a.example.com/cb, https://c.example.com/cb', + }), + ).toEqual({ + attributes: {name: 'Budget assistant', software: 'assistant-y', tags: ['finance']}, + description: 'Budgets', + grantTypes: ['authorization_code'], + redirectUris: ['https://a.example.com/cb', 'https://c.example.com/cb'], + }); + }); +}); + +describe('isPersonalAgentFormValid', () => { + it('should accept a name with the authorization code grant and a redirect URI', () => { + expect(isPersonalAgentFormValid(values)).toBe(true); + }); + + it('should refuse a blank name', () => { + expect(isPersonalAgentFormValid({...values, name: ' '})).toBe(false); + }); + + it('should refuse the authorization code grant without a redirect URI', () => { + expect(isPersonalAgentFormValid({...values, redirectUris: ''})).toBe(false); + }); + + it('should accept no redirect URI without the authorization code grant', () => { + expect(isPersonalAgentFormValid({...values, grantTypes: ['ciba'], redirectUris: ''})).toBe(true); + }); +}); diff --git a/packages/javascript/src/utils/__tests__/resolveResourceEndpoint.test.ts b/packages/javascript/src/utils/__tests__/resolveResourceEndpoint.test.ts index 5e00ed57..66b4eb10 100644 --- a/packages/javascript/src/utils/__tests__/resolveResourceEndpoint.test.ts +++ b/packages/javascript/src/utils/__tests__/resolveResourceEndpoint.test.ts @@ -83,6 +83,7 @@ describe('resolveResourceEndpoint', (): void => { 'userTypes', 'users', 'usersMe', + 'usersMeAgents', 'usersMeCredentials', 'usersMeMeta', 'usersMeOrganizationUnits', diff --git a/packages/javascript/src/utils/getAccountLifecycleActions.ts b/packages/javascript/src/utils/getAccountLifecycleActions.ts index 87f4d301..4a0ed1c6 100644 --- a/packages/javascript/src/utils/getAccountLifecycleActions.ts +++ b/packages/javascript/src/utils/getAccountLifecycleActions.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import {AccountLifecycleFlowConfigKey} from '../constants/AdministrationConstants'; -import {AccessStatusValue} from '../models/access-status'; +import {AccessStatusValue, SuspensionAppliedBy} from '../models/access-status'; import {AccountLifecycleAction, AccountLifecycleSubjectKind} from '../models/administration'; /** @@ -24,6 +24,9 @@ const ACTIONS_BY_STATUS: Record = { * @param status - Its effective access status. An identity with none reads as `ACTIVE`. * @param configuredFlows - The flows the server configures, keyed by `flow` server-config key, as * `resolveAdministrationFlows` returns them. + * @param appliedBy - Who holds a suspension, from `status.details.appliedBy`. The organization lifts only its + * own suspension: a suspension held only by others, such as an agent's owner, offers the organization's + * own suspension instead of an unsuspend. Absent or empty reads as the organization's. * @returns The actions to offer, most expected first. * * @example @@ -36,10 +39,16 @@ const getAccountLifecycleActions = ( kind: AccountLifecycleSubjectKind, status: AccessStatusValue | undefined, configuredFlows: Record, + appliedBy?: SuspensionAppliedBy[], ): AccountLifecycleAction[] => { const configKeys: Partial> = AccountLifecycleFlowConfigKey[kind]; + const heldByOthersOnly: boolean = + status === 'SUSPENDED' && Boolean(appliedBy?.length) && !appliedBy?.includes('organization'); + const candidates: AccountLifecycleAction[] = heldByOthersOnly + ? ['suspend'] + : (ACTIONS_BY_STATUS[status ?? 'ACTIVE'] ?? []); - return (ACTIONS_BY_STATUS[status ?? 'ACTIVE'] ?? []).filter((action: AccountLifecycleAction) => { + return candidates.filter((action: AccountLifecycleAction) => { const configKey: string | undefined = configKeys[action]; return configKey !== undefined && Boolean(configuredFlows[configKey]); diff --git a/packages/javascript/src/utils/getMeAgentSuspensionAction.ts b/packages/javascript/src/utils/getMeAgentSuspensionAction.ts new file mode 100644 index 00000000..9774d671 --- /dev/null +++ b/packages/javascript/src/utils/getMeAgentSuspensionAction.ts @@ -0,0 +1,24 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {AccessStatus} from '../models/access-status'; + +/** + * The suspension action an agent's owner can take on it: `unsuspend` while the owner holds it suspended, + * otherwise `suspend`. The owner's suspension is independent of any other party's, so an agent the + * organization suspended, or one suspended while its owner's account is, can still take the owner's own + * suspension, and lifting the owner's leaves the others in force. + * + * @param status - The agent's effective access status, from a read of the owner's agent. + * @returns The action to offer. + * + * @example + * ```typescript + * const action = getMeAgentSuspensionAction(agent.status); + * await (action === 'suspend' ? suspendMeAgent : unsuspendMeAgent)({agentId: agent.id, baseUrl}); + * ``` + */ +const getMeAgentSuspensionAction = (status: AccessStatus | undefined): 'suspend' | 'unsuspend' => + status?.value === 'SUSPENDED' && status.details?.appliedBy?.includes('owner') ? 'unsuspend' : 'suspend'; + +export default getMeAgentSuspensionAction; diff --git a/packages/javascript/src/utils/isPersonalAgent.ts b/packages/javascript/src/utils/isPersonalAgent.ts new file mode 100644 index 00000000..de55ad74 --- /dev/null +++ b/packages/javascript/src/utils/isPersonalAgent.ts @@ -0,0 +1,19 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {AgentKind, PERSONAL_AGENT_KIND} from '../models/agent-resource'; + +/** + * Whether an agent is a personal agent: one that acts only for its owner, a user. + * + * @param agent - An agent, or the summary of one from a list response. + * @returns `true` when the agent's kind is {@link PERSONAL_AGENT_KIND}. + * + * @example + * ```typescript + * isPersonalAgent({id: 'a1', kind: 'personal-assistant'}); // true + * ``` + */ +const isPersonalAgent = (agent: {kind?: AgentKind}): boolean => agent.kind === PERSONAL_AGENT_KIND; + +export default isPersonalAgent; diff --git a/packages/javascript/src/utils/personalAgentForm.ts b/packages/javascript/src/utils/personalAgentForm.ts new file mode 100644 index 00000000..254ab2f9 --- /dev/null +++ b/packages/javascript/src/utils/personalAgentForm.ts @@ -0,0 +1,81 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import parseRedirectUris from './parseRedirectUris'; +import {Agent, UpdateMeAgentRequest} from '../models/agent-resource'; +import {OAuth2Config, OAuth2GrantTypes} from '../models/application'; + +/** + * The values of the personal agent edit form. `redirectUris` is the text of the field, URIs separated by + * commas. + */ +export interface PersonalAgentFormValues { + /** + * The agent's text attributes other than `name`, keyed by attribute name. Attributes that hold another kind + * of value are not edited, and are sent back unchanged. + */ + attributes: Record; + description: string; + grantTypes: string[]; + name: string; + redirectUris: string; +} + +/** + * The OAuth settings of an agent, if it has an OAuth client. + * + * @param agent - The agent. + * @returns Its OAuth settings. + */ +export const getPersonalAgentOAuthConfig = (agent: Agent): OAuth2Config | undefined => + agent.inboundAuthConfig?.find((config: {type: string}) => config.type === 'oauth2')?.config; + +/** + * The form values that edit an agent, starting from what the server holds. + * + * @param agent - The agent to edit. + * @returns The initial form values. + */ +export const toPersonalAgentFormValues = (agent: Agent): PersonalAgentFormValues => { + const oauth: OAuth2Config | undefined = getPersonalAgentOAuthConfig(agent); + const name: unknown = agent.attributes?.['name']; + + return { + attributes: Object.fromEntries( + Object.entries(agent.attributes ?? {}).filter( + (entry: [string, unknown]): entry is [string, string] => entry[0] !== 'name' && typeof entry[1] === 'string', + ), + ), + description: agent.description ?? '', + grantTypes: oauth?.grantTypes ?? [], + name: typeof name === 'string' ? name : '', + redirectUris: (oauth?.redirectUris ?? []).join(', '), + }; +}; + +/** + * The update request for an agent's edit form. Attributes the form does not edit are sent back unchanged, + * since an update replaces them all. + * + * @param agent - The agent being edited. + * @param values - The edited form values. + * @returns The request for `updateMeAgent`. + */ +export const toUpdateMeAgentRequest = (agent: Agent, values: PersonalAgentFormValues): UpdateMeAgentRequest => ({ + attributes: {...agent.attributes, ...values.attributes, name: values.name.trim()}, + description: values.description.trim(), + grantTypes: values.grantTypes, + redirectUris: parseRedirectUris(values.redirectUris), +}); + +/** + * Whether the edit form can be saved: a name is required, and the authorization code grant needs a + * redirect URI. + * + * @param values - The edited form values. + * @returns Whether the values are valid. + */ +export const isPersonalAgentFormValid = (values: PersonalAgentFormValues): boolean => + values.name.trim().length > 0 && + (!values.grantTypes.includes(OAuth2GrantTypes.AUTHORIZATION_CODE) || + parseRedirectUris(values.redirectUris).length > 0); diff --git a/packages/javascript/src/utils/resolveResourceEndpoint.ts b/packages/javascript/src/utils/resolveResourceEndpoint.ts index 7d33a92d..85f025e2 100644 --- a/packages/javascript/src/utils/resolveResourceEndpoint.ts +++ b/packages/javascript/src/utils/resolveResourceEndpoint.ts @@ -40,6 +40,7 @@ export type ResourceEndpointKey = | 'serverConfig' | 'users' | 'usersMe' + | 'usersMeAgents' | 'usersMeCredentials' | 'usersMeMeta' | 'usersMeOrganizationUnits' @@ -78,6 +79,7 @@ export const RESOURCE_ENDPOINT_KEYS: readonly ResourceEndpointKey[] = [ 'serverConfig', 'users', 'usersMe', + 'usersMeAgents', 'usersMeCredentials', 'usersMeMeta', 'usersMeOrganizationUnits', diff --git a/packages/react/src/api/account/__tests__/meAgentsApi.test.ts b/packages/react/src/api/account/__tests__/meAgentsApi.test.ts new file mode 100644 index 00000000..6f22cb6b --- /dev/null +++ b/packages/react/src/api/account/__tests__/meAgentsApi.test.ts @@ -0,0 +1,93 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {Mock, beforeEach, describe, expect, it, vi} from 'vitest'; +import deleteMeAgent from '../deleteMeAgent'; +import getMeAgent from '../getMeAgent'; +import getMeAgents from '../getMeAgents'; +import suspendAllMeAgents from '../suspendAllMeAgents'; +import suspendMeAgent from '../suspendMeAgent'; +import unsuspendMeAgent from '../unsuspendMeAgent'; +import updateMeAgent from '../updateMeAgent'; + +const {mockBase, mockCreateFetcher} = vi.hoisted(() => ({ + mockBase: { + deleteMeAgent: vi.fn(), + getMeAgent: vi.fn(), + getMeAgents: vi.fn(), + suspendAllMeAgents: vi.fn(), + suspendMeAgent: vi.fn(), + unsuspendMeAgent: vi.fn(), + updateMeAgent: vi.fn(), + } as Record, + mockCreateFetcher: vi.fn() as Mock, +})); + +vi.mock('@thunderid/browser', () => ({ + createHttpClientFetcher: (...args: unknown[]): unknown => mockCreateFetcher(...args) as unknown, + deleteMeAgent: (...args: unknown[]): unknown => mockBase['deleteMeAgent'](...args) as unknown, + getMeAgent: (...args: unknown[]): unknown => mockBase['getMeAgent'](...args) as unknown, + getMeAgents: (...args: unknown[]): unknown => mockBase['getMeAgents'](...args) as unknown, + suspendAllMeAgents: (...args: unknown[]): unknown => mockBase['suspendAllMeAgents'](...args) as unknown, + suspendMeAgent: (...args: unknown[]): unknown => mockBase['suspendMeAgent'](...args) as unknown, + unsuspendMeAgent: (...args: unknown[]): unknown => mockBase['unsuspendMeAgent'](...args) as unknown, + updateMeAgent: (...args: unknown[]): unknown => mockBase['updateMeAgent'](...args) as unknown, +})); + +const baseUrl = 'https://localhost:8090'; +const payload = {attributes: {name: 'Spending assistant'}, grantTypes: ['ciba'], redirectUris: []}; + +const calls: [string, (fetcher?: Mock) => Promise, Record][] = [ + ['getMeAgents', (fetcher) => getMeAgents({baseUrl, fetcher, instanceId: 2, limit: 5}), {baseUrl, limit: 5}], + ['getMeAgent', (fetcher) => getMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), {agentId: 'a-1', baseUrl}], + [ + 'updateMeAgent', + (fetcher) => updateMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2, payload}), + {agentId: 'a-1', baseUrl, payload}, + ], + [ + 'deleteMeAgent', + (fetcher) => deleteMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), + {agentId: 'a-1', baseUrl}, + ], + [ + 'suspendMeAgent', + (fetcher) => suspendMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), + {agentId: 'a-1', baseUrl}, + ], + [ + 'unsuspendMeAgent', + (fetcher) => unsuspendMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), + {agentId: 'a-1', baseUrl}, + ], + ['suspendAllMeAgents', (fetcher) => suspendAllMeAgents({baseUrl, fetcher, instanceId: 2}), {baseUrl}], +]; + +describe('personal agent self-service functions (React)', () => { + beforeEach(() => { + vi.clearAllMocks(); + Object.values(mockBase).forEach((mock: Mock) => mock.mockResolvedValue(undefined)); + }); + + it.each(calls)( + "%s uses the SDK's HTTP client, which attaches the access token, for the instance", + async (name, call, expected) => { + const fetcher: Mock = vi.fn(); + mockCreateFetcher.mockReturnValue(fetcher); + + await call(); + + expect(mockCreateFetcher).toHaveBeenCalledWith(2); + expect(mockBase[name]).toHaveBeenCalledWith({...expected, fetcher}); + }, + ); + + it.each(calls)('%s keeps a fetcher the caller supplies', async (name, call) => { + const fetcher: Mock = vi.fn(); + + await call(fetcher); + + expect(mockCreateFetcher).not.toHaveBeenCalled(); + expect(mockBase[name].mock.calls[0][0]).toMatchObject({fetcher}); + }); +}); diff --git a/packages/react/src/api/account/deleteMeAgent.ts b/packages/react/src/api/account/deleteMeAgent.ts new file mode 100644 index 00000000..ea6cb61d --- /dev/null +++ b/packages/react/src/api/account/deleteMeAgent.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + deleteMeAgent as baseDeleteMeAgent, + DeleteMeAgentConfig as BaseDeleteMeAgentConfig, +} from '@thunderid/browser'; + +export interface DeleteMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Deletes one of the signed-in user's personal agents, with the signed-in user's access token attached by the + * SDK's HTTP client. + * + * @example + * ```typescript + * await deleteMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const deleteMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: DeleteMeAgentConfig): Promise => + baseDeleteMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default deleteMeAgent; diff --git a/packages/react/src/api/account/getMeAgent.ts b/packages/react/src/api/account/getMeAgent.ts new file mode 100644 index 00000000..cebe7e3d --- /dev/null +++ b/packages/react/src/api/account/getMeAgent.ts @@ -0,0 +1,38 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + Agent, + createHttpClientFetcher, + getMeAgent as baseGetMeAgent, + GetMeAgentConfig as BaseGetMeAgentConfig, +} from '@thunderid/browser'; + +export interface GetMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Retrieves one of the agents the signed-in user owns, with the signed-in user's access token attached by the + * SDK's HTTP client. + * + * @example + * ```typescript + * const agent = await getMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const getMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: GetMeAgentConfig): Promise => + baseGetMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default getMeAgent; diff --git a/packages/react/src/api/account/getMeAgents.ts b/packages/react/src/api/account/getMeAgents.ts new file mode 100644 index 00000000..b00d2169 --- /dev/null +++ b/packages/react/src/api/account/getMeAgents.ts @@ -0,0 +1,46 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + AgentListResponse, + createHttpClientFetcher, + getMeAgents as baseGetMeAgents, + GetMeAgentsConfig as BaseGetMeAgentsConfig, +} from '@thunderid/browser'; + +export interface GetMeAgentsConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Retrieves a page of the agents the signed-in user owns, from `/users/me/agents`, with the signed-in user's + * access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * const {agents, totalResults} = await getMeAgents({ + * baseUrl: 'https://localhost:8090', + * kind: PERSONAL_AGENT_KIND, + * limit: 10, + * }); + * ``` + */ +const getMeAgents = async ({ + fetcher, + instanceId = 0, + ...requestConfig +}: GetMeAgentsConfig): Promise => + baseGetMeAgents({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default getMeAgents; diff --git a/packages/react/src/api/account/suspendAllMeAgents.ts b/packages/react/src/api/account/suspendAllMeAgents.ts new file mode 100644 index 00000000..87634f93 --- /dev/null +++ b/packages/react/src/api/account/suspendAllMeAgents.ts @@ -0,0 +1,42 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + SuspendAllMeAgentsResponse, + suspendAllMeAgents as baseSuspendAllMeAgents, + SuspendAllMeAgentsConfig as BaseSuspendAllMeAgentsConfig, +} from '@thunderid/browser'; + +export interface SuspendAllMeAgentsConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Suspends every personal agent of the signed-in user that the user has not already suspended, with the + * signed-in user's access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * const {suspendedCount} = await suspendAllMeAgents({baseUrl: 'https://localhost:8090'}); + * ``` + */ +const suspendAllMeAgents = async ({ + fetcher, + instanceId = 0, + ...requestConfig +}: SuspendAllMeAgentsConfig): Promise => + baseSuspendAllMeAgents({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default suspendAllMeAgents; diff --git a/packages/react/src/api/account/suspendMeAgent.ts b/packages/react/src/api/account/suspendMeAgent.ts new file mode 100644 index 00000000..3a940cae --- /dev/null +++ b/packages/react/src/api/account/suspendMeAgent.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + suspendMeAgent as baseSuspendMeAgent, + SuspendMeAgentConfig as BaseSuspendMeAgentConfig, +} from '@thunderid/browser'; + +export interface SuspendMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Places the owner's suspension on one of the signed-in user's personal agents, with the signed-in user's + * access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * await suspendMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const suspendMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: SuspendMeAgentConfig): Promise => + baseSuspendMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default suspendMeAgent; diff --git a/packages/react/src/api/account/unsuspendMeAgent.ts b/packages/react/src/api/account/unsuspendMeAgent.ts new file mode 100644 index 00000000..67d851df --- /dev/null +++ b/packages/react/src/api/account/unsuspendMeAgent.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + unsuspendMeAgent as baseUnsuspendMeAgent, + UnsuspendMeAgentConfig as BaseUnsuspendMeAgentConfig, +} from '@thunderid/browser'; + +export interface UnsuspendMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Lifts the owner's suspension from one of the signed-in user's personal agents, with the signed-in user's + * access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * await unsuspendMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const unsuspendMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: UnsuspendMeAgentConfig): Promise => + baseUnsuspendMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default unsuspendMeAgent; diff --git a/packages/react/src/api/account/updateMeAgent.ts b/packages/react/src/api/account/updateMeAgent.ts new file mode 100644 index 00000000..dca4df93 --- /dev/null +++ b/packages/react/src/api/account/updateMeAgent.ts @@ -0,0 +1,42 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + Agent, + createHttpClientFetcher, + updateMeAgent as baseUpdateMeAgent, + UpdateMeAgentConfig as BaseUpdateMeAgentConfig, +} from '@thunderid/browser'; + +export interface UpdateMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Replaces the part of one of the signed-in user's personal agents its owner may change, with the signed-in + * user's access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * const agent = await updateMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: 'a-1', + * payload: {attributes: {name: 'Spending assistant'}, grantTypes: ['ciba'], redirectUris: []}, + * }); + * ``` + */ +const updateMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: UpdateMeAgentConfig): Promise => + baseUpdateMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default updateMeAgent; diff --git a/packages/react/src/components/account/PersonalAgentDetails/BasePersonalAgentDetails.tsx b/packages/react/src/components/account/PersonalAgentDetails/BasePersonalAgentDetails.tsx new file mode 100644 index 00000000..e8aeb347 --- /dev/null +++ b/packages/react/src/components/account/PersonalAgentDetails/BasePersonalAgentDetails.tsx @@ -0,0 +1,390 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + Agent, + OAuth2Config, + PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS, + PERSONAL_AGENT_GRANT_TYPES, + Preferences, + SuspensionAppliedBy, + UpdateMeAgentRequest, + PersonalAgentFormValues, + getAgentName, + getMeAgentSuspensionAction, + getPersonalAgentOAuthConfig, + isPersonalAgentFormValid, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, +} from '@thunderid/browser'; +import {ChangeEvent, FC, FormEvent, ReactElement, ReactNode, useState} from 'react'; +import useTranslation from '../../../hooks/useTranslation'; +import {AccessStatusBadge} from '../../management/shared/AccountLifecycleParts'; +import {ConfirmButton, DetailList, DetailListItem, Panel} from '../../management/shared/AdminParts'; +import AdminSection from '../../management/shared/AdminSection'; +import useAdminPartStyles from '../../management/shared/useAdminPartStyles'; +import Alert from '../../primitives/Alert/Alert'; +import Button from '../../primitives/Button/Button'; +import Checkbox from '../../primitives/Checkbox/Checkbox'; +import CopyableText from '../../primitives/CopyableText/CopyableText'; +import Spinner from '../../primitives/Spinner/Spinner'; +import TextField from '../../primitives/TextField/TextField'; + +/** + * What {@link BasePersonalAgentDetails} hands its `children` render function, so the agent can be shown with + * any UI. An action is undefined when the app has not turned it on, or when it does not apply to the agent. + */ +export interface BasePersonalAgentDetailsRenderProps { + agent?: Agent; + error: string | null; + isChangingSuspension: boolean; + isDeleting: boolean; + isLoading: boolean; + isUpdating: boolean; + /** + * The agent's OAuth configuration. Undefined when it has no OAuth client. + */ + oauth?: OAuth2Config; + /** + * Deletes the agent. The built-in UI asks for confirmation first, and a custom render must too. + */ + onDelete?: () => void; + /** + * Places the owner's suspension on the agent. Offered unless the owner already holds it suspended. + */ + onSuspend?: () => void; + /** + * Lifts the owner's suspension of the agent. Offered only while the owner holds it suspended. + */ + onUnsuspend?: () => void; + /** + * Replaces the editable part of the agent. + */ + onUpdate?: (changes: UpdateMeAgentRequest) => void; +} + +export interface BasePersonalAgentDetailsProps { + /** + * Controls rendered next to the agent's name. + */ + actions?: ReactNode; + agent?: Agent; + /** + * Renders custom UI in place of the default view. Receives the agent, its OAuth configuration, the loading + * and error state, and the actions the app has turned on that apply to the agent. + */ + children?: (props: BasePersonalAgentDetailsRenderProps) => ReactNode; + className?: string; + error?: string | null; + isChangingSuspension?: boolean; + isDeleting?: boolean; + isLoading?: boolean; + isUpdating?: boolean; + /** + * Deletes the agent. The delete action is hidden when omitted, and for a declarative agent. + */ + onDelete?: () => void; + /** + * Places the owner's suspension on the agent. The suspend action is hidden when omitted. + */ + onSuspend?: () => void; + /** + * Lifts the owner's suspension of the agent. Shown only while the owner holds the agent suspended. + */ + onUnsuspend?: () => void; + /** + * Replaces the editable part of the agent. The edit action is hidden when omitted, and for a declarative + * agent. + */ + onUpdate?: (changes: UpdateMeAgentRequest) => void; + preferences?: Preferences; +} + +const stringify = (value: unknown): string => { + if (value === null || value === undefined) { + return ''; + } + + return typeof value === 'object' ? JSON.stringify(value) : String(value as string | number | boolean); +}; + +/** + * Shows one of the signed-in user's personal agents with the actions its owner can take. Holds no data of its + * own: pass the agent and handle editing, deletion and the owner's suspension, each offered only when its + * handler is set. + */ +const BasePersonalAgentDetails: FC = ({ + actions, + agent, + children, + className, + error = null, + isChangingSuspension = false, + isDeleting = false, + isLoading = false, + isUpdating = false, + onDelete, + onSuspend, + onUnsuspend, + onUpdate, + preferences, +}: BasePersonalAgentDetailsProps): ReactElement => { + const {t} = useTranslation(preferences?.i18n); + const styles: Record = useAdminPartStyles(); + // The draft remembers which agent it was opened for, so switching the agent closes the form instead of + // saving one agent's values onto another. + const [editing, setEditing] = useState<{agentId: string; values: PersonalAgentFormValues} | null>(null); + const draft: PersonalAgentFormValues | null = editing && editing.agentId === agent?.id ? editing.values : null; + const setDraft = (update: (previous: PersonalAgentFormValues) => PersonalAgentFormValues): void => + setEditing( + (previous: {agentId: string; values: PersonalAgentFormValues} | null) => + previous && {...previous, values: update(previous.values)}, + ); + + const isWritable: boolean = Boolean(agent) && !agent?.isReadOnly; + const suspensionAction: 'suspend' | 'unsuspend' = getMeAgentSuspensionAction(agent?.status); + const canSuspend: boolean = Boolean(agent) && suspensionAction === 'suspend'; + const canUnsuspend: boolean = Boolean(agent) && suspensionAction === 'unsuspend'; + + if (children) { + return ( +
+ {children({ + agent, + error, + isChangingSuspension, + isDeleting, + isLoading, + isUpdating, + oauth: agent ? getPersonalAgentOAuthConfig(agent) : undefined, + onDelete: isWritable ? onDelete : undefined, + onSuspend: canSuspend ? onSuspend : undefined, + onUnsuspend: canUnsuspend ? onUnsuspend : undefined, + onUpdate: isWritable ? onUpdate : undefined, + })} +
+ ); + } + + if (isLoading && !agent) { + return ( + + + {t('admin.common.loading')} + + + ); + } + + if (!agent) { + return ( + + + {error ?? t('admin.common.errors.not_found')} + + + ); + } + + const name: string = getAgentName(agent); + const oauth: OAuth2Config | undefined = getPersonalAgentOAuthConfig(agent); + const grantTypeLabel = (grantType: string): string => + PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS[grantType] ? t(PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS[grantType]) : grantType; + const appliedBy: SuspensionAppliedBy[] = + agent.status?.value === 'SUSPENDED' ? (agent.status.details?.appliedBy ?? []) : []; + + const none: ReactNode = {t('user.agents.details.none')}; + const overview: DetailListItem[] = [ + { + label: t('user.agents.list.columns.status'), + value: , + }, + { + label: t('user.agents.details.client_id'), + value: agent.clientId ? : none, + }, + { + label: t('user.agents.details.grant_types'), + value: oauth?.grantTypes?.length ? oauth.grantTypes.map(grantTypeLabel).join(', ') : none, + }, + { + label: t('user.agents.details.redirect_uris'), + value: oauth?.redirectUris?.length ? oauth.redirectUris.map((uri: string) =>
{uri}
) : none, + }, + ]; + const attributes: [string, unknown][] = Object.entries(agent.attributes ?? {}); + + const handleSave = (event: FormEvent): void => { + event.preventDefault(); + + if (!draft || !isPersonalAgentFormValid(draft)) { + return; + } + + onUpdate?.(toUpdateMeAgentRequest(agent, draft)); + setEditing(null); + }; + + const setField = (field: keyof Omit, value: string): void => + setDraft((previous: PersonalAgentFormValues) => ({...previous, [field]: value})); + + return ( + + {actions} + {onUnsuspend && canUnsuspend && ( + + )} + {onSuspend && canSuspend && ( + + {t('user.agents.suspend.action')} + + )} + {onDelete && isWritable && ( + + {t('user.agents.delete.action')} + + )} + + } + > + {error && ( + + {error} + + )} + {appliedBy.map((party: SuspensionAppliedBy) => ( + + {t(`user.agents.suspension.${party}`)} + + ))} + {draft ? ( + +
+ ): void => setField('name', event.target.value)} + /> + {Object.keys(draft.attributes).map((attribute: string) => ( + ): void => + setDraft((previous: PersonalAgentFormValues) => ({ + ...previous, + attributes: {...previous.attributes, [attribute]: event.target.value}, + })) + } + /> + ))} + ): void => setField('description', event.target.value)} + /> + ): void => setField('redirectUris', event.target.value)} + /> +
+ {t('user.agents.details.grant_types')} + {PERSONAL_AGENT_GRANT_TYPES.map((grantType: string) => ( + ): void => + setDraft((previous: PersonalAgentFormValues) => ({ + ...previous, + grantTypes: event.target.checked + ? [...previous.grantTypes, grantType] + : previous.grantTypes.filter((value: string) => value !== grantType), + })) + } + /> + ))} +
+
+ + +
+ +
+ ) : ( + <> + setEditing({agentId: agent.id, values: toPersonalAgentFormValues(agent)})} + > + {t('user.agents.edit.action')} + + ) : undefined + } + > + + + + {attributes.length > 0 ? ( + ({label: name, value: stringify(value)}))} + /> + ) : ( + none + )} + + + )} +
+ ); +}; + +export default BasePersonalAgentDetails; diff --git a/packages/react/src/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx b/packages/react/src/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx new file mode 100644 index 00000000..cd6fc733 --- /dev/null +++ b/packages/react/src/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx @@ -0,0 +1,125 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + Agent, + AgentQueryKeys, + ResourceQueryKey, + UpdateMeAgentRequest, + resolveResourceEndpoint, + toManagementErrorMessage, +} from '@thunderid/browser'; +import {FC, ReactElement} from 'react'; +import BasePersonalAgentDetails, {BasePersonalAgentDetailsProps} from './BasePersonalAgentDetails'; +import deleteMeAgent from '../../../api/account/deleteMeAgent'; +import getMeAgent from '../../../api/account/getMeAgent'; +import suspendMeAgent from '../../../api/account/suspendMeAgent'; +import unsuspendMeAgent from '../../../api/account/unsuspendMeAgent'; +import updateMeAgent from '../../../api/account/updateMeAgent'; +import useThunderID from '../../../contexts/ThunderID/useThunderID'; +import useResourceMutation, {ResourceMutationResult} from '../../../hooks/management/useResourceMutation'; +import useResourceQuery, {ResourceQueryResult} from '../../../hooks/management/useResourceQuery'; +import useTranslation from '../../../hooks/useTranslation'; + +export type PersonalAgentDetailsProps = Omit< + BasePersonalAgentDetailsProps, + | 'agent' + | 'error' + | 'isChangingSuspension' + | 'isDeleting' + | 'isLoading' + | 'isUpdating' + | 'onDelete' + | 'onSuspend' + | 'onUnsuspend' + | 'onUpdate' +> & { + agentId: string; + /** + * Whether the agent can be deleted from this view. + * @default false + */ + deletable?: boolean; + /** + * Whether the agent can be edited from this view. + * @default false + */ + editable?: boolean; + /** + * Called after the agent has been deleted. + */ + onDeleted?: () => void; + /** + * Whether the user can suspend the agent, and lift their own suspension, from this view. + * @default false + */ + suspendable?: boolean; +}; + +/** + * Shows one of the signed-in user's personal agents, and, when the app allows it, lets the user edit, delete + * and suspend it. + * + * @example + * ```tsx + * setAgentId(null)} /> + * ``` + */ +const PersonalAgentDetails: FC = ({ + agentId, + deletable = false, + editable = false, + onDeleted, + preferences, + suspendable = false, + ...rest +}: PersonalAgentDetailsProps): ReactElement => { + const {t} = useTranslation(preferences?.i18n); + const {baseUrl, endpoints, instanceId} = useThunderID(); + const url: string | undefined = resolveResourceEndpoint('usersMeAgents', {endpoints}); + const changed: ResourceQueryKey[] = [[AgentQueryKeys.ME_AGENT, agentId], [AgentQueryKeys.ME_AGENTS]]; + + // These are the user's own requests, so they go through the SDK's transport for this instance, like the other + // `users/me` operations, and never the management `http.fetcher` the hooks would otherwise hand them. + const agent: ResourceQueryResult = useResourceQuery( + [AgentQueryKeys.ME_AGENT, agentId], + () => getMeAgent({agentId, baseUrl, instanceId, url}), + {enabled: Boolean(agentId)}, + ); + const update: ResourceMutationResult = useResourceMutation( + (payload: UpdateMeAgentRequest) => updateMeAgent({agentId, baseUrl, instanceId, payload, url}), + () => changed, + ); + const deletion: ResourceMutationResult = useResourceMutation( + () => deleteMeAgent({agentId, baseUrl, instanceId, url}), + () => [[AgentQueryKeys.ME_AGENTS]], + {onSuccess: onDeleted}, + ); + const suspension: ResourceMutationResult = useResourceMutation( + (action: 'suspend' | 'unsuspend') => + (action === 'suspend' ? suspendMeAgent : unsuspendMeAgent)({agentId, baseUrl, instanceId, url}), + () => changed, + ); + + return ( + void update.mutate(changes) : undefined} + onDelete={deletable ? (): void => void deletion.mutate(undefined) : undefined} + onSuspend={suspendable ? (): void => void suspension.mutate('suspend') : undefined} + onUnsuspend={suspendable ? (): void => void suspension.mutate('unsuspend') : undefined} + preferences={preferences} + {...rest} + /> + ); +}; + +export default PersonalAgentDetails; diff --git a/packages/react/src/components/account/PersonalAgentDetails/__tests__/PersonalAgentDetails.test.tsx b/packages/react/src/components/account/PersonalAgentDetails/__tests__/PersonalAgentDetails.test.tsx new file mode 100644 index 00000000..da6f1903 --- /dev/null +++ b/packages/react/src/components/account/PersonalAgentDetails/__tests__/PersonalAgentDetails.test.tsx @@ -0,0 +1,321 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {cleanup, fireEvent, render, screen, waitFor, within} from '@testing-library/react'; +import {Agent, ApiFetcher, createResourceInvalidator} from '@thunderid/browser'; +import {ReactElement, ReactNode} from 'react'; +import {Mock, afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import I18nProvider from '../../../../contexts/I18n/I18nProvider'; +import ThemeProvider from '../../../../contexts/Theme/ThemeProvider'; +import ThunderIDContext, {ThunderIDContextProps} from '../../../../contexts/ThunderID/ThunderIDContext'; +import BasePersonalAgentDetails, {BasePersonalAgentDetailsRenderProps} from '../BasePersonalAgentDetails'; +import PersonalAgentDetails from '../PersonalAgentDetails'; + +type FetcherMock = Mock; + +const {sdkFetcher} = vi.hoisted(() => ({sdkFetcher: {current: undefined as unknown as ApiFetcher}})); + +vi.mock('@thunderid/browser', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + createHttpClientFetcher: (): ApiFetcher => (url: string, init: RequestInit) => sdkFetcher.current(url, init), +})); + +const baseUrl = 'https://localhost:8090'; + +const respond = (body: unknown, status = 200): Response => + ({ + json: () => Promise.resolve(body), + ok: status >= 200 && status < 300, + status, + statusText: '', + text: () => Promise.resolve(JSON.stringify(body)), + }) as Response; + +const assistant: Agent = { + attributes: {name: 'Spending assistant', software: 'assistant-x'}, + clientId: 'pa_1', + description: 'Answers questions about my spending', + id: 'a-1', + inboundAuthConfig: [ + { + config: { + grantTypes: ['authorization_code'], + redirectUris: ['https://assistant.example.com/callback'], + responseTypes: ['code'], + }, + type: 'oauth2', + }, + ], + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', +}; + +interface Server { + fetcher: FetcherMock; + requests: () => {body?: unknown; method: string; url: string}[]; +} + +const createServer = (agent: Agent = assistant): Server => { + const fetcher: FetcherMock = vi.fn().mockImplementation((url: string, init?: RequestInit) => { + const method: string = init?.method ?? 'GET'; + + if (method === 'GET' || method === 'PUT') { + return Promise.resolve(respond(agent)); + } + + return Promise.resolve(respond(undefined, 204)); + }); + + return { + fetcher, + requests: () => + fetcher.mock.calls.map(([url, init]: [string, RequestInit]) => ({ + body: typeof init?.body === 'string' ? (JSON.parse(init.body) as unknown) : undefined, + method: init?.method ?? 'GET', + url, + })), + }; +}; + +const renderWithProviders = (ui: ReactElement, httpFetcher?: ApiFetcher): ReturnType => { + const thunderID = { + baseUrl, + http: {fetcher: httpFetcher}, + instanceId: 0, + invalidator: createResourceInvalidator(), + isInitialized: true, + isLoading: false, + vendor: 'thunderid', + } as unknown as ThunderIDContextProps; + + function Providers({children}: {children: ReactNode}): ReactElement { + return ( + + + {children} + + + ); + } + + return render(ui, {wrapper: Providers}); +}; + +const serve = (agent: Agent): void => { + server = createServer(agent); + sdkFetcher.current = server.fetcher; +}; + +let server: Server; + +beforeEach(() => { + serve(assistant); +}); + +afterEach(() => { + cleanup(); +}); + +describe('PersonalAgentDetails', () => { + it("shows the agent through the SDK's own transport, and offers no action unless the app turns it on", async () => { + const httpFetcher: FetcherMock = vi.fn(); + renderWithProviders(, httpFetcher); + + expect(await screen.findByRole('heading', {name: 'Spending assistant'})).toBeTruthy(); + expect(screen.getByText('Authorization code')).toBeTruthy(); + expect(screen.getByText('https://assistant.example.com/callback')).toBeTruthy(); + expect(screen.getByText('software')).toBeTruthy(); + expect(screen.getByText('assistant-x')).toBeTruthy(); + expect(server.requests()[0]).toEqual({ + body: undefined, + method: 'GET', + url: `${baseUrl}/users/me/agents/a-1?include=display`, + }); + expect(httpFetcher).not.toHaveBeenCalled(); + ['Edit', 'Suspend', 'Unsuspend', 'Delete agent'].forEach((name: string) => + expect(screen.queryByRole('button', {name})).toBeNull(), + ); + }); + + it('suspends the agent after confirmation, then offers to lift the suspension', async () => { + renderWithProviders(); + + fireEvent.click(await screen.findByRole('button', {name: 'Suspend'})); + serve({...assistant, status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}}); + fireEvent.click( + within(screen.getByRole('group', {name: /^Suspend Spending assistant\?/})).getByRole('button', { + name: 'Confirm', + }), + ); + + await waitFor(() => + expect(server.requests()).toContainEqual({ + body: undefined, + method: 'POST', + url: `${baseUrl}/users/me/agents/a-1/suspend`, + }), + ); + expect(await screen.findByRole('button', {name: 'Unsuspend'})).toBeTruthy(); + expect(screen.getByText('You suspended this agent.')).toBeTruthy(); + }); + + it("lifts the owner's suspension, which needs no confirmation", async () => { + serve({...assistant, status: {details: {appliedBy: ['owner']}, value: 'SUSPENDED'}}); + renderWithProviders(); + + fireEvent.click(await screen.findByRole('button', {name: 'Unsuspend'})); + + await waitFor(() => + expect(server.requests()).toContainEqual({ + body: undefined, + method: 'POST', + url: `${baseUrl}/users/me/agents/a-1/unsuspend`, + }), + ); + }); + + it("explains the organization's suspension and offers only the owner's own", async () => { + serve({...assistant, status: {details: {appliedBy: ['organization']}, value: 'SUSPENDED'}}); + renderWithProviders(); + + expect( + await screen.findByText( + 'Your organization suspended this agent. Only an administrator can lift that suspension.', + ), + ).toBeTruthy(); + expect(screen.getByRole('button', {name: 'Suspend'})).toBeTruthy(); + expect(screen.queryByRole('button', {name: 'Unsuspend'})).toBeNull(); + }); + + it('saves the editable part, keeping the attributes it does not edit', async () => { + serve({...assistant, attributes: {...assistant.attributes, tags: ['finance']}}); + renderWithProviders(); + + fireEvent.click(await screen.findByRole('button', {name: 'Edit'})); + fireEvent.change(screen.getByLabelText(/^Name/), {target: {value: 'Budget assistant'}}); + fireEvent.change(screen.getByLabelText('software'), {target: {value: 'assistant-y'}}); + fireEvent.click(screen.getByLabelText('Refresh token')); + fireEvent.click(screen.getByRole('button', {name: 'Save changes'})); + + await waitFor(() => + expect(server.requests()).toContainEqual({ + body: { + attributes: {name: 'Budget assistant', software: 'assistant-y', tags: ['finance']}, + description: 'Answers questions about my spending', + grantTypes: ['authorization_code', 'refresh_token'], + redirectUris: ['https://assistant.example.com/callback'], + }, + method: 'PUT', + url: `${baseUrl}/users/me/agents/a-1`, + }), + ); + }); + + it('keeps the save off while the authorization code grant has no redirect URI', async () => { + renderWithProviders(); + + fireEvent.click(await screen.findByRole('button', {name: 'Edit'})); + fireEvent.change(screen.getByLabelText(/^Redirect URIs/), {target: {value: ''}}); + + expect(screen.getByRole('button', {name: 'Save changes'}).disabled).toBe(true); + + fireEvent.click(screen.getByLabelText('Authorization code')); + expect(screen.getByRole('button', {name: 'Save changes'}).disabled).toBe(false); + }); + + it('deletes the agent after confirmation', async () => { + const onDeleted: Mock = vi.fn(); + renderWithProviders(); + + fireEvent.click(await screen.findByRole('button', {name: 'Delete agent'})); + expect(server.requests().some(({method}: {method: string}) => method === 'DELETE')).toBe(false); + fireEvent.click(screen.getByRole('button', {name: 'Confirm'})); + + await waitFor(() => expect(onDeleted).toHaveBeenCalled()); + expect(server.requests()).toContainEqual({ + body: undefined, + method: 'DELETE', + url: `${baseUrl}/users/me/agents/a-1`, + }); + }); + + it('offers no edit or deletion for a declarative agent', async () => { + serve({...assistant, isReadOnly: true}); + renderWithProviders(); + + expect(await screen.findByRole('button', {name: 'Suspend'})).toBeTruthy(); + expect(screen.queryByRole('button', {name: 'Edit'})).toBeNull(); + expect(screen.queryByRole('button', {name: 'Delete agent'})).toBeNull(); + }); +}); + +describe('BasePersonalAgentDetails', () => { + it("closes the edit form when the agent changes, so one agent's values are never saved onto another", () => { + const onUpdate: Mock = vi.fn(); + const other: Agent = {...assistant, attributes: {name: 'Travel planner'}, id: 'a-2'}; + const {rerender} = renderWithProviders(); + + fireEvent.click(screen.getByRole('button', {name: 'Edit'})); + fireEvent.change(screen.getByLabelText(/^Name/), {target: {value: 'Budget assistant'}}); + rerender(); + + expect(screen.queryByRole('button', {name: 'Save changes'})).toBeNull(); + fireEvent.click(screen.getByRole('button', {name: 'Edit'})); + expect((screen.getByLabelText(/^Name/) as HTMLInputElement).value).toBe('Travel planner'); + expect(onUpdate).not.toHaveBeenCalled(); + }); + + it('hands a custom render the agent and only the actions that apply', () => { + const renderDetails: Mock<(props: BasePersonalAgentDetailsRenderProps) => ReactNode> = vi.fn(() => ( +

custom view

+ )); + const onUnsuspend: Mock = vi.fn(); + const agent: Agent = { + ...assistant, + isReadOnly: true, + status: {details: {appliedBy: ['owner']}, value: 'SUSPENDED'}, + }; + + renderWithProviders( + + {renderDetails} + , + ); + + expect(screen.getByText('custom view')).toBeTruthy(); + const props: BasePersonalAgentDetailsRenderProps = renderDetails.mock.calls[0][0]; + expect(props.agent).toEqual(agent); + expect(props.oauth?.grantTypes).toEqual(['authorization_code']); + expect(props.onDelete).toBeUndefined(); + expect(props.onUpdate).toBeUndefined(); + expect(props.onSuspend).toBeUndefined(); + props.onUnsuspend?.(); + expect(onUnsuspend).toHaveBeenCalled(); + }); + + it('hands a custom render the suspension of an agent the owner has not suspended', () => { + const renderDetails: Mock<(props: BasePersonalAgentDetailsRenderProps) => ReactNode> = vi.fn(() => null); + + renderWithProviders( + + {renderDetails} + , + ); + + const props: BasePersonalAgentDetailsRenderProps = renderDetails.mock.calls[0][0]; + expect(props.onSuspend).toBeDefined(); + expect(props.onUnsuspend).toBeUndefined(); + }); +}); diff --git a/packages/react/src/components/account/PersonalAgentList/BasePersonalAgentList.tsx b/packages/react/src/components/account/PersonalAgentList/BasePersonalAgentList.tsx new file mode 100644 index 00000000..10525846 --- /dev/null +++ b/packages/react/src/components/account/PersonalAgentList/BasePersonalAgentList.tsx @@ -0,0 +1,203 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {BasicAgent, Preferences, getAgentName} from '@thunderid/browser'; +import {FC, ReactElement, ReactNode} from 'react'; +import useTranslation from '../../../hooks/useTranslation'; +import {AccessStatusBadge} from '../../management/shared/AccountLifecycleParts'; +import {AdminListRenderProps} from '../../management/shared/AdminListRenderProps'; +import {ConfirmButton} from '../../management/shared/AdminParts'; +import AdminSection from '../../management/shared/AdminSection'; +import Alert from '../../primitives/Alert/Alert'; +import DataTable, {DataTableColumn} from '../../primitives/DataTable/DataTable'; + +/** + * What {@link BasePersonalAgentList} hands its `children` render function. `agents` and `rows` are the same array. + */ +export type BasePersonalAgentListRenderProps = AdminListRenderProps & { + /** + * Why the last suspend-all request failed, already translated. + */ + actionError: string | null; + agents: BasicAgent[]; + isSuspendingAll: boolean; + /** + * Suspends every personal agent of the signed-in user. Undefined when not allowed, or when there are none. + * The built-in UI asks for confirmation first, and a custom render must too. + */ + onSuspendAll?: () => void; + /** + * How many agents the last suspend-all request suspended, until the list is shown again. + */ + suspendedCount: number | null; +}; + +export interface BasePersonalAgentListProps { + /** + * Why the last suspend-all request failed, already translated. + */ + actionError?: string | null; + /** + * Controls rendered next to the title. + */ + actions?: ReactNode; + agents: BasicAgent[]; + /** + * Renders custom UI in place of the default table. Receives the agents, the default columns, the loading + * and error state, the pagination and selection handlers, and the suspend-all action when it is allowed. + */ + children?: (props: BasePersonalAgentListRenderProps) => ReactNode; + className?: string; + description?: string; + error?: string | null; + isLoading?: boolean; + isSuspendingAll?: boolean; + /** + * Page size. + * @default 20 + */ + limit?: number; + offset?: number; + /** + * Called with the offset of the page to show. Pagination is hidden when omitted. + */ + onPageChange?: (offset: number) => void; + /** + * Called when an agent is chosen. Rows are selectable only when set. + */ + onSelect?: (agent: BasicAgent) => void; + /** + * Suspends every personal agent of the signed-in user. The action is hidden when omitted. + */ + onSuspendAll?: () => void; + preferences?: Preferences; + selectedAgentId?: string; + suspendedCount?: number | null; + /** + * Heading of the list. Pass an empty string to hide it. + */ + title?: string; + totalResults?: number; +} + +/** + * Lists the signed-in user's personal agents with their client and status. Holds no data of its own: pass the page of + * agents and handle selection, pagination and suspending them all. + */ +const BasePersonalAgentList: FC = ({ + actionError = null, + actions, + agents, + children, + className, + description, + error = null, + isLoading = false, + isSuspendingAll = false, + limit = 20, + offset = 0, + onPageChange, + onSelect, + onSuspendAll, + preferences, + selectedAgentId, + suspendedCount = null, + title, + totalResults, +}: BasePersonalAgentListProps): ReactElement => { + const {t} = useTranslation(preferences?.i18n); + const canSuspendAll: boolean = Boolean(onSuspendAll) && agents.length > 0; + + const columns: DataTableColumn[] = [ + { + header: t('user.agents.list.columns.name'), + id: 'name', + render: (agent: BasicAgent): ReactNode => getAgentName(agent), + }, + { + header: t('user.agents.details.client_id'), + id: 'clientId', + render: (agent: BasicAgent): ReactNode => {agent.clientId ?? ''}, + }, + { + header: t('user.agents.list.columns.status'), + id: 'status', + render: (agent: BasicAgent): ReactNode => , + }, + ]; + + if (children) { + return ( +
+ {children({ + actionError, + agents, + columns, + error, + isLoading, + isSuspendingAll, + limit, + offset, + onPageChange, + onSelect, + onSuspendAll: canSuspendAll ? onSuspendAll : undefined, + rows: agents, + selectedRowId: selectedAgentId, + suspendedCount, + totalResults: totalResults ?? agents.length, + })} +
+ ); + } + + return ( + + {actions} + {onSuspendAll && canSuspendAll && ( + + {t('user.agents.suspend_all.action')} + + )} + + } + > + {actionError && ( + + {actionError} + + )} + {suspendedCount !== null && ( + + {t('user.agents.suspend_all.done', {count: suspendedCount})} + + )} + agent.id} + isLoading={isLoading} + error={error} + emptyText={t('user.agents.list.empty')} + onRowClick={onSelect} + selectedRowId={selectedAgentId} + pagination={ + onPageChange ? {limit, offset, onChange: onPageChange, total: totalResults ?? agents.length} : undefined + } + /> + + ); +}; + +export default BasePersonalAgentList; diff --git a/packages/react/src/components/account/PersonalAgentList/PersonalAgentList.tsx b/packages/react/src/components/account/PersonalAgentList/PersonalAgentList.tsx new file mode 100644 index 00000000..8620696f --- /dev/null +++ b/packages/react/src/components/account/PersonalAgentList/PersonalAgentList.tsx @@ -0,0 +1,96 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + AgentListResponse, + AgentQueryKeys, + PERSONAL_AGENT_KIND, + SuspendAllMeAgentsResponse, + resolveResourceEndpoint, + toManagementErrorMessage, +} from '@thunderid/browser'; +import {FC, ReactElement, useState} from 'react'; +import BasePersonalAgentList, {BasePersonalAgentListProps} from './BasePersonalAgentList'; +import getMeAgents from '../../../api/account/getMeAgents'; +import suspendAllMeAgents from '../../../api/account/suspendAllMeAgents'; +import useThunderID from '../../../contexts/ThunderID/useThunderID'; +import useResourceMutation, {ResourceMutationResult} from '../../../hooks/management/useResourceMutation'; +import useResourceQuery, {ResourceQueryResult} from '../../../hooks/management/useResourceQuery'; +import useTranslation from '../../../hooks/useTranslation'; + +export type PersonalAgentListProps = Omit< + BasePersonalAgentListProps, + | 'actionError' + | 'agents' + | 'error' + | 'isLoading' + | 'isSuspendingAll' + | 'offset' + | 'onPageChange' + | 'onSuspendAll' + | 'suspendedCount' + | 'totalResults' +> & { + /** + * Whether the user can suspend all their personal agents from this view. + * @default false + */ + suspendable?: boolean; +}; + +/** + * Lists the signed-in user's personal agents, a page at a time. Pair it with `PersonalAgentDetails` to show + * the agent the user chooses. + * + * @example + * ```tsx + * setAgentId(agent.id)} /> + * ``` + */ +const PersonalAgentList: FC = ({ + limit = 20, + preferences, + suspendable = false, + ...rest +}: PersonalAgentListProps): ReactElement => { + const {t} = useTranslation(preferences?.i18n); + const {baseUrl, endpoints, instanceId} = useThunderID(); + const url: string | undefined = resolveResourceEndpoint('usersMeAgents', {endpoints}); + const [offset, setOffset] = useState(0); + const [suspendedCount, setSuspendedCount] = useState(null); + + // These are the user's own requests, so they go through the SDK's transport for this instance, like the other + // `users/me` operations, and never the management `http.fetcher` the hooks would otherwise hand them. + const {data, error, isLoading}: ResourceQueryResult = useResourceQuery( + [AgentQueryKeys.ME_AGENTS, {limit, offset}], + () => getMeAgents({baseUrl, instanceId, kind: PERSONAL_AGENT_KIND, limit, offset, url}), + ); + const suspendAll: ResourceMutationResult = useResourceMutation( + () => suspendAllMeAgents({baseUrl, instanceId, url}), + () => [[AgentQueryKeys.ME_AGENT], [AgentQueryKeys.ME_AGENTS]], + {onSuccess: (result: SuspendAllMeAgentsResponse): void => setSuspendedCount(result.suspendedCount)}, + ); + + return ( + { + setOffset(next); + setSuspendedCount(null); + }} + actionError={toManagementErrorMessage(t, suspendAll.error, 'user.agents.action.error')} + isSuspendingAll={suspendAll.isLoading} + onSuspendAll={suspendable ? (): void => void suspendAll.mutate(undefined) : undefined} + suspendedCount={suspendedCount} + preferences={preferences} + {...rest} + /> + ); +}; + +export default PersonalAgentList; diff --git a/packages/react/src/components/account/PersonalAgentList/__tests__/PersonalAgentList.test.tsx b/packages/react/src/components/account/PersonalAgentList/__tests__/PersonalAgentList.test.tsx new file mode 100644 index 00000000..625752c7 --- /dev/null +++ b/packages/react/src/components/account/PersonalAgentList/__tests__/PersonalAgentList.test.tsx @@ -0,0 +1,189 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {cleanup, fireEvent, render, screen, within} from '@testing-library/react'; +import {ApiFetcher, BasicAgent, createResourceInvalidator} from '@thunderid/browser'; +import {ReactElement, ReactNode} from 'react'; +import {Mock, afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import I18nProvider from '../../../../contexts/I18n/I18nProvider'; +import ThemeProvider from '../../../../contexts/Theme/ThemeProvider'; +import ThunderIDContext, {ThunderIDContextProps} from '../../../../contexts/ThunderID/ThunderIDContext'; +import BasePersonalAgentList, {BasePersonalAgentListRenderProps} from '../BasePersonalAgentList'; +import PersonalAgentList from '../PersonalAgentList'; + +type FetcherMock = Mock; + +const {sdkFetcher} = vi.hoisted(() => ({sdkFetcher: {current: undefined as unknown as ApiFetcher}})); + +vi.mock('@thunderid/browser', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + createHttpClientFetcher: (): ApiFetcher => (url: string, init: RequestInit) => sdkFetcher.current(url, init), +})); + +const baseUrl = 'https://localhost:8090'; + +const respond = (body: unknown, status = 200): Response => + ({ + json: () => Promise.resolve(body), + ok: status >= 200 && status < 300, + status, + statusText: '', + text: () => Promise.resolve(JSON.stringify(body)), + }) as Response; + +const assistant: BasicAgent = { + attributes: {name: 'Spending assistant'}, + clientId: 'pa_1', + id: 'a-1', + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', +}; + +const createFetcher = (overrides: Record = {}): FetcherMock => + vi.fn().mockImplementation((url: string, init?: RequestInit) => { + const method: string = init?.method ?? 'GET'; + const path: string = new URL(url).pathname; + const override: Response | undefined = overrides[`${method} ${path}`]; + + if (override) { + return Promise.resolve(override); + } + if (method === 'POST' && path === '/users/me/agents/suspend') { + return Promise.resolve(respond({suspendedCount: 1})); + } + + return Promise.resolve(respond({agents: [assistant], count: 1, startIndex: 1, totalResults: 1})); + }); + +const renderWithProviders = ( + ui: ReactElement, + {endpoints, httpFetcher}: {endpoints?: ThunderIDContextProps['endpoints']; httpFetcher?: ApiFetcher} = {}, +): ReturnType => { + const thunderID = { + baseUrl, + endpoints, + http: {fetcher: httpFetcher}, + instanceId: 0, + invalidator: createResourceInvalidator(), + isInitialized: true, + isLoading: false, + vendor: 'thunderid', + } as unknown as ThunderIDContextProps; + + function Providers({children}: {children: ReactNode}): ReactElement { + return ( + + + {children} + + + ); + } + + return render(ui, {wrapper: Providers}); +}; + +const requests = (fetcher: FetcherMock): {method: string; url: string}[] => + fetcher.mock.calls.map(([url, init]: [string, RequestInit]) => ({method: init?.method ?? 'GET', url})); + +let fetcher: FetcherMock; + +beforeEach(() => { + fetcher = createFetcher(); + sdkFetcher.current = fetcher; +}); + +afterEach(() => { + cleanup(); +}); + +describe('PersonalAgentList', () => { + it("lists the user's personal agents through the SDK's own transport, not the management fetcher", async () => { + const httpFetcher: FetcherMock = vi.fn(); + const onSelect: Mock = vi.fn(); + + renderWithProviders(, {httpFetcher}); + + const table: HTMLElement = await screen.findByRole('table', {name: 'Personal agents'}); + expect(await within(table).findByText('Spending assistant')).toBeTruthy(); + expect(within(table).getByText('pa_1')).toBeTruthy(); + expect(within(table).getByText('Active')).toBeTruthy(); + expect(requests(fetcher)[0]).toEqual({ + method: 'GET', + url: `${baseUrl}/users/me/agents?kind=personal-assistant&limit=20&offset=0`, + }); + expect(httpFetcher).not.toHaveBeenCalled(); + + fireEvent.click(within(table).getByText('Spending assistant')); + expect(onSelect).toHaveBeenCalledWith(assistant); + }); + + it('sends requests to the usersMeAgents endpoint override', async () => { + renderWithProviders(, {endpoints: {usersMeAgents: 'https://rs.example.com/users/me/agents'}}); + + await screen.findByText('Spending assistant'); + expect(requests(fetcher)[0].url).toBe( + 'https://rs.example.com/users/me/agents?kind=personal-assistant&limit=20&offset=0', + ); + }); + + it('offers no suspend-all unless the app turns it on', async () => { + renderWithProviders(); + + await screen.findByText('Spending assistant'); + expect(screen.queryByRole('button', {name: 'Suspend all'})).toBeNull(); + }); + + it('suspends every agent after confirmation and says how many', async () => { + renderWithProviders(); + + fireEvent.click(await screen.findByRole('button', {name: 'Suspend all'})); + expect(requests(fetcher).some(({method}: {method: string}) => method === 'POST')).toBe(false); + fireEvent.click(screen.getByRole('button', {name: 'Confirm'})); + + expect(await screen.findByText('Agents suspended: 1')).toBeTruthy(); + expect(requests(fetcher)).toContainEqual({method: 'POST', url: `${baseUrl}/users/me/agents/suspend`}); + }); + + it('shows a translated message, never the server text, when a request is refused', async () => { + fetcher = createFetcher({ + 'GET /users/me/agents': respond({code: 'AGT-1061', message: {defaultValue: 'Delegated token'}}, 403), + }); + sdkFetcher.current = fetcher; + renderWithProviders(); + + expect(await screen.findByText('You do not have permission to do this.')).toBeTruthy(); + expect(screen.queryByText('Delegated token')).toBeNull(); + }); +}); + +describe('BasePersonalAgentList', () => { + it('says so when the user has no personal agents, and hides suspend-all', () => { + renderWithProviders(); + + expect(screen.getByText("You don't have any personal agents.")).toBeTruthy(); + expect(screen.queryByRole('button', {name: 'Suspend all'})).toBeNull(); + }); + + it('hands a custom render the agents, the columns and suspend-all', () => { + const renderList: Mock<(props: BasePersonalAgentListRenderProps) => ReactNode> = vi.fn(() =>

custom list

); + const onSuspendAll: Mock = vi.fn(); + + renderWithProviders( + + {renderList} + , + ); + + expect(screen.getByText('custom list')).toBeTruthy(); + const props: BasePersonalAgentListRenderProps = renderList.mock.calls[0][0]; + expect(props.agents).toEqual([assistant]); + expect(props.rows).toEqual([assistant]); + expect(props.columns.map((column: {id: string}) => column.id)).toEqual(['name', 'clientId', 'status']); + expect(props.totalResults).toBe(1); + props.onSuspendAll?.(); + expect(onSuspendAll).toHaveBeenCalled(); + }); +}); diff --git a/packages/react/src/components/management/AgentDetails/AgentDetails.tsx b/packages/react/src/components/management/AgentDetails/AgentDetails.tsx index 7ac0162f..5153eb76 100644 --- a/packages/react/src/components/management/AgentDetails/AgentDetails.tsx +++ b/packages/react/src/components/management/AgentDetails/AgentDetails.tsx @@ -95,6 +95,7 @@ const AgentDetails: FC = ({ ); const lifecycle: AccountLifecycleState = useAccountLifecycle({ + appliedBy: agent.data?.status?.details?.appliedBy, enabled: lifecycleActions, invalidatedKeys: [[AgentQueryKeys.AGENT, agentId], [AgentQueryKeys.AGENTS]], kind: 'agent', diff --git a/packages/react/src/components/management/AgentDetails/BaseAgentDetails.tsx b/packages/react/src/components/management/AgentDetails/BaseAgentDetails.tsx index 5bdfc888..04b5fdd0 100644 --- a/packages/react/src/components/management/AgentDetails/BaseAgentDetails.tsx +++ b/packages/react/src/components/management/AgentDetails/BaseAgentDetails.tsx @@ -1,7 +1,15 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {AccountLifecycleAction, Agent, MembershipGroup, Preferences, getAgentName} from '@thunderid/browser'; +import { + AccountLifecycleAction, + Agent, + MembershipGroup, + Preferences, + SuspensionAppliedBy, + getAgentName, + isPersonalAgent, +} from '@thunderid/browser'; import {FC, ReactElement, ReactNode} from 'react'; import useTranslation from '../../../hooks/useTranslation'; import Alert from '../../primitives/Alert/Alert'; @@ -146,10 +154,24 @@ const BaseAgentDetails: FC = ({ {label: t('admin.common.columns.organization_unit'), value: agent.ouHandle ?? agent.ouId}, ]; + if (isPersonalAgent(agent)) { + details.push({label: t('admin.agents.details.kind'), value: t('admin.agents.kind.personal')}); + } + if (agent.status) { details.push({label: t('admin.common.columns.status'), value: }); } + const suspendedBy: SuspensionAppliedBy[] = + agent.status?.value === 'SUSPENDED' ? (agent.status.details?.appliedBy ?? []) : []; + + if (suspendedBy.length > 0) { + details.push({ + label: t('admin.agents.details.suspension.title'), + value: suspendedBy.map((party: SuspensionAppliedBy) => t(`admin.agents.details.suspension.${party}`)).join(', '), + }); + } + if (agent.clientId) { details.push({label: t('admin.agents.list.columns.client_id'), value: }); } diff --git a/packages/react/src/components/management/AgentList/BaseAgentList.tsx b/packages/react/src/components/management/AgentList/BaseAgentList.tsx index e8f32450..b2757df2 100644 --- a/packages/react/src/components/management/AgentList/BaseAgentList.tsx +++ b/packages/react/src/components/management/AgentList/BaseAgentList.tsx @@ -1,13 +1,14 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {BasicAgent, Preferences, SelectOption, getAgentName} from '@thunderid/browser'; +import {BasicAgent, Preferences, SelectOption, getAgentName, isPersonalAgent} from '@thunderid/browser'; import {FC, ReactElement, ReactNode} from 'react'; import useTranslation from '../../../hooks/useTranslation'; import DataTable, {DataTableColumn} from '../../primitives/DataTable/DataTable'; import {AdminListRenderProps} from '../shared/AdminListRenderProps'; import AdminSearch, {AdminSearchValue} from '../shared/AdminSearch'; import AdminSection from '../shared/AdminSection'; +import useAdminPartStyles from '../shared/useAdminPartStyles'; /** * What {@link BaseAgentList} hands its `children` render function. `agents` and `rows` are the same array. @@ -91,12 +92,21 @@ const BaseAgentList: FC = ({ totalResults, }: BaseAgentListProps): ReactElement => { const {t} = useTranslation(preferences?.i18n); + const styles: Record = useAdminPartStyles(); const columns: DataTableColumn[] = [ { header: t('admin.agents.list.columns.name'), id: 'name', - render: (agent: BasicAgent): ReactNode => getAgentName(agent), + render: (agent: BasicAgent): ReactNode => + isPersonalAgent(agent) ? ( + + {getAgentName(agent)} + {t('admin.agents.kind.personal')} + + ) : ( + getAgentName(agent) + ), }, {header: t('admin.agents.list.columns.type'), id: 'type', render: (agent: BasicAgent): ReactNode => agent.type}, { diff --git a/packages/react/src/components/management/__tests__/managementComponents.test.tsx b/packages/react/src/components/management/__tests__/managementComponents.test.tsx index 25e1fedf..9983028e 100644 --- a/packages/react/src/components/management/__tests__/managementComponents.test.tsx +++ b/packages/react/src/components/management/__tests__/managementComponents.test.tsx @@ -269,6 +269,52 @@ describe('BaseAgentDetails', () => { expect(screen.getByText('No owner')).toBeTruthy(); }); + + it('marks a personal agent and names every party holding it suspended', () => { + renderWithProviders( + , + ); + + expect(screen.getByText('Personal')).toBeTruthy(); + expect(screen.getByText("Owner, Owner's account suspension")).toBeTruthy(); + }); + + it('names no suspending party for an agent that is not suspended', () => { + renderWithProviders(); + + expect(screen.queryByText('Suspended by')).toBeNull(); + expect(screen.queryByText('Personal')).toBeNull(); + }); +}); + +describe('BaseAgentList', () => { + it('marks only the personal agents', () => { + renderWithProviders( + , + ); + + const rows: HTMLElement[] = within(screen.getByRole('table', {name: 'Agents'})).getAllByRole('row'); + expect( + within(rows.find((row: HTMLElement) => row.textContent?.includes('Spending assistant'))!).getByText('Personal'), + ).toBeTruthy(); + expect( + within(rows.find((row: HTMLElement) => row.textContent?.includes('Billing bot'))!).queryByText('Personal'), + ).toBeNull(); + }); }); describe('BaseUserDetails', () => { @@ -1896,6 +1942,32 @@ describe('administration flows', () => { ); }); + it("offers the organization's own suspension, not an unsuspend, for an agent only its owner suspended", async () => { + const fetcher: FetcherMock = createFlowServer({ + configured: {agentSuspendFlow: 'suspend-agent', agentUnsuspendFlow: 'unsuspend-agent'}, + resources: { + '/agents/a-1': { + attributes: {name: 'Spending assistant'}, + id: 'a-1', + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'bot', + }, + }, + }); + + renderWithProviders(, {fetcher}); + + fireEvent.click(await screen.findByRole('button', {name: 'Suspend'})); + expect(screen.queryByRole('button', {name: 'Unsuspend'})).toBeNull(); + fireEvent.click( + within(screen.getByRole('group', {name: /^Suspend Spending assistant\?/})).getByRole('button', {name: 'Suspend'}), + ); + + await waitFor(() => expect(executions(fetcher)).toEqual([{flowId: 'id-suspend-agent', inputs: {subject: 'a-1'}}])); + }); + it('suspends an application without asking for an operator note', async () => { const fetcher: FetcherMock = createFlowServer({ configured: {applicationSuspendFlow: 'suspend-app'}, diff --git a/packages/react/src/components/management/shared/AdminParts.styles.ts b/packages/react/src/components/management/shared/AdminParts.styles.ts index 86bc55da..30bdd88e 100644 --- a/packages/react/src/components/management/shared/AdminParts.styles.ts +++ b/packages/react/src/components/management/shared/AdminParts.styles.ts @@ -47,6 +47,7 @@ const useStyles = (theme: Theme, colorScheme: string): Record => detail: css` display: grid; grid-template-columns: fit-content(200px) minmax(0, 1fr); + align-items: baseline; gap: ${unit} calc(${unit} * 2); margin: 0; font-size: ${theme.vars.typography.fontSizes.sm}; diff --git a/packages/react/src/hooks/management/useAccountLifecycle.ts b/packages/react/src/hooks/management/useAccountLifecycle.ts index 78a07f93..a42d4e69 100644 --- a/packages/react/src/hooks/management/useAccountLifecycle.ts +++ b/packages/react/src/hooks/management/useAccountLifecycle.ts @@ -8,6 +8,7 @@ import { AccountLifecycleResult, AccountLifecycleSubjectKind, ResourceQueryKey, + SuspensionAppliedBy, getAccountLifecycleActions, resolveAdministrationFlows, runAccountLifecycleAction, @@ -23,6 +24,10 @@ interface AccountLifecycleVariables { } export interface AccountLifecycleOptions { + /** + * Who holds a suspension, from the read's `status.details.appliedBy`. The organization lifts only its own. + */ + appliedBy?: SuspensionAppliedBy[]; /** * Whether to offer the actions at all. The configured flows are read only when it is on. */ @@ -70,6 +75,7 @@ export interface AccountLifecycleState { * ``` */ const useAccountLifecycle = ({ + appliedBy, enabled, invalidatedKeys, kind, @@ -89,8 +95,8 @@ const useAccountLifecycle = ({ ); const actions: AccountLifecycleAction[] = useMemo( - () => (enabled && flows.data ? getAccountLifecycleActions(kind, status, flows.data) : []), - [enabled, flows.data, kind, status], + () => (enabled && flows.data ? getAccountLifecycleActions(kind, status, flows.data, appliedBy) : []), + [appliedBy, enabled, flows.data, kind, status], ); return { diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 7b54d52b..27d38ad4 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -67,6 +67,10 @@ export {default as useFetchUsers} from './hooks/management/useFetchUsers'; export {default as useFetchUserTypes} from './hooks/management/useFetchUserTypes'; export {default as useManagementRequestConfig} from './hooks/management/useManagementRequestConfig'; export type {ManagementCollection} from './hooks/management/useManagementRequestConfig'; +export {default as useResourceQuery} from './hooks/management/useResourceQuery'; +export type {ResourceQueryOptions, ResourceQueryResult} from './hooks/management/useResourceQuery'; +export {default as useResourceMutation} from './hooks/management/useResourceMutation'; +export type {ResourceMutationOptions, ResourceMutationResult} from './hooks/management/useResourceMutation'; export {default as useGrantedPermissions} from './hooks/management/useGrantedPermissions'; export type {GrantedPermissions} from './hooks/management/useGrantedPermissions'; @@ -199,6 +203,18 @@ export * from './components/account/VerifyAttribute/BaseVerifyAttribute'; export {default as VerifyAttribute} from './components/account/VerifyAttribute/VerifyAttribute'; export * from './components/account/VerifyAttribute/VerifyAttribute'; +export {default as BasePersonalAgentList} from './components/account/PersonalAgentList/BasePersonalAgentList'; +export * from './components/account/PersonalAgentList/BasePersonalAgentList'; + +export {default as PersonalAgentList} from './components/account/PersonalAgentList/PersonalAgentList'; +export * from './components/account/PersonalAgentList/PersonalAgentList'; + +export {default as BasePersonalAgentDetails} from './components/account/PersonalAgentDetails/BasePersonalAgentDetails'; +export * from './components/account/PersonalAgentDetails/BasePersonalAgentDetails'; + +export {default as PersonalAgentDetails} from './components/account/PersonalAgentDetails/PersonalAgentDetails'; +export * from './components/account/PersonalAgentDetails/PersonalAgentDetails'; + export * from './components/management/shared/AdminListRenderProps'; export type {AdminSearchValue} from './components/management/shared/AdminSearch'; @@ -517,6 +533,20 @@ export {default as getMeProfile} from './api/account/getUsersMe'; export * from './api/account/getUsersMe'; export {default as getUsersMeMeta} from './api/account/getUsersMeMeta'; export * from './api/account/getUsersMeMeta'; +export {default as getMeAgents} from './api/account/getMeAgents'; +export type {GetMeAgentsConfig} from './api/account/getMeAgents'; +export {default as getMeAgent} from './api/account/getMeAgent'; +export type {GetMeAgentConfig} from './api/account/getMeAgent'; +export {default as updateMeAgent} from './api/account/updateMeAgent'; +export type {UpdateMeAgentConfig} from './api/account/updateMeAgent'; +export {default as deleteMeAgent} from './api/account/deleteMeAgent'; +export type {DeleteMeAgentConfig} from './api/account/deleteMeAgent'; +export {default as suspendMeAgent} from './api/account/suspendMeAgent'; +export type {SuspendMeAgentConfig} from './api/account/suspendMeAgent'; +export {default as unsuspendMeAgent} from './api/account/unsuspendMeAgent'; +export type {UnsuspendMeAgentConfig} from './api/account/unsuspendMeAgent'; +export {default as suspendAllMeAgents} from './api/account/suspendAllMeAgents'; +export type {SuspendAllMeAgentsConfig} from './api/account/suspendAllMeAgents'; export { ThunderIDRuntimeError, @@ -705,6 +735,18 @@ export { updateAgent, updateApplication, updateUser, + getMeAgentSuspensionAction, + getPersonalAgentOAuthConfig, + isPersonalAgentFormValid, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, + type PersonalAgentFormValues, + PERSONAL_AGENT_GRANT_TYPES, + PERSONAL_AGENT_KIND, + type SuspensionAppliedBy, + type AgentKind, + type SuspendAllMeAgentsResponse, + type UpdateMeAgentRequest, type Agent, type AgentListResponse, type ApiFetcher, @@ -758,6 +800,7 @@ export { getAccountLifecycleActions, getAgentName, getAgentType, + isPersonalAgent, getUserType, getUserTypes, getUserUsages, diff --git a/packages/vue/src/__tests__/api/account/me-agents.test.ts b/packages/vue/src/__tests__/api/account/me-agents.test.ts new file mode 100644 index 00000000..55ff02f2 --- /dev/null +++ b/packages/vue/src/__tests__/api/account/me-agents.test.ts @@ -0,0 +1,93 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {Mock, beforeEach, describe, expect, it, vi} from 'vitest'; +import deleteMeAgent from '../../../api/account/deleteMeAgent'; +import getMeAgent from '../../../api/account/getMeAgent'; +import getMeAgents from '../../../api/account/getMeAgents'; +import suspendAllMeAgents from '../../../api/account/suspendAllMeAgents'; +import suspendMeAgent from '../../../api/account/suspendMeAgent'; +import unsuspendMeAgent from '../../../api/account/unsuspendMeAgent'; +import updateMeAgent from '../../../api/account/updateMeAgent'; + +const {mockBase, mockCreateFetcher} = vi.hoisted(() => ({ + mockBase: { + deleteMeAgent: vi.fn(), + getMeAgent: vi.fn(), + getMeAgents: vi.fn(), + suspendAllMeAgents: vi.fn(), + suspendMeAgent: vi.fn(), + unsuspendMeAgent: vi.fn(), + updateMeAgent: vi.fn(), + } as Record, + mockCreateFetcher: vi.fn() as Mock, +})); + +vi.mock('@thunderid/browser', () => ({ + createHttpClientFetcher: (...args: unknown[]): unknown => mockCreateFetcher(...args) as unknown, + deleteMeAgent: (...args: unknown[]): unknown => mockBase['deleteMeAgent'](...args) as unknown, + getMeAgent: (...args: unknown[]): unknown => mockBase['getMeAgent'](...args) as unknown, + getMeAgents: (...args: unknown[]): unknown => mockBase['getMeAgents'](...args) as unknown, + suspendAllMeAgents: (...args: unknown[]): unknown => mockBase['suspendAllMeAgents'](...args) as unknown, + suspendMeAgent: (...args: unknown[]): unknown => mockBase['suspendMeAgent'](...args) as unknown, + unsuspendMeAgent: (...args: unknown[]): unknown => mockBase['unsuspendMeAgent'](...args) as unknown, + updateMeAgent: (...args: unknown[]): unknown => mockBase['updateMeAgent'](...args) as unknown, +})); + +const baseUrl = 'https://localhost:8090'; +const payload = {attributes: {name: 'Spending assistant'}, grantTypes: ['ciba'], redirectUris: []}; + +const calls: [string, (fetcher?: Mock) => Promise, Record][] = [ + ['getMeAgents', (fetcher) => getMeAgents({baseUrl, fetcher, instanceId: 2, limit: 5}), {baseUrl, limit: 5}], + ['getMeAgent', (fetcher) => getMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), {agentId: 'a-1', baseUrl}], + [ + 'updateMeAgent', + (fetcher) => updateMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2, payload}), + {agentId: 'a-1', baseUrl, payload}, + ], + [ + 'deleteMeAgent', + (fetcher) => deleteMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), + {agentId: 'a-1', baseUrl}, + ], + [ + 'suspendMeAgent', + (fetcher) => suspendMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), + {agentId: 'a-1', baseUrl}, + ], + [ + 'unsuspendMeAgent', + (fetcher) => unsuspendMeAgent({agentId: 'a-1', baseUrl, fetcher, instanceId: 2}), + {agentId: 'a-1', baseUrl}, + ], + ['suspendAllMeAgents', (fetcher) => suspendAllMeAgents({baseUrl, fetcher, instanceId: 2}), {baseUrl}], +]; + +describe('personal agent self-service functions (React)', () => { + beforeEach(() => { + vi.clearAllMocks(); + Object.values(mockBase).forEach((mock: Mock) => mock.mockResolvedValue(undefined)); + }); + + it.each(calls)( + "%s uses the SDK's HTTP client, which attaches the access token, for the instance", + async (name, call, expected) => { + const fetcher: Mock = vi.fn(); + mockCreateFetcher.mockReturnValue(fetcher); + + await call(); + + expect(mockCreateFetcher).toHaveBeenCalledWith(2); + expect(mockBase[name]).toHaveBeenCalledWith({...expected, fetcher}); + }, + ); + + it.each(calls)('%s keeps a fetcher the caller supplies', async (name, call) => { + const fetcher: Mock = vi.fn(); + + await call(fetcher); + + expect(mockCreateFetcher).not.toHaveBeenCalled(); + expect(mockBase[name].mock.calls[0][0]).toMatchObject({fetcher}); + }); +}); diff --git a/packages/vue/src/__tests__/components/account/personal-agents.test.ts b/packages/vue/src/__tests__/components/account/personal-agents.test.ts new file mode 100644 index 00000000..488009d4 --- /dev/null +++ b/packages/vue/src/__tests__/components/account/personal-agents.test.ts @@ -0,0 +1,429 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import type {Agent, ApiFetcher} from '@thunderid/browser'; +import {type DOMWrapper, type VueWrapper, mount} from '@vue/test-utils'; +import {type Mock, afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {h} from 'vue'; +import BasePersonalAgentDetails, { + type BasePersonalAgentDetailsRenderProps, +} from '../../../components/account/personal-agent-details/BasePersonalAgentDetails'; +import PersonalAgentDetails from '../../../components/account/personal-agent-details/PersonalAgentDetails'; +import BasePersonalAgentList, { + type BasePersonalAgentListRenderProps, +} from '../../../components/account/personal-agent-list/BasePersonalAgentList'; +import PersonalAgentList from '../../../components/account/personal-agent-list/PersonalAgentList'; +import {createManagementContext, jsonResponse, translate} from '../../helpers/managementContext'; + +type FetcherMock = Mock; + +const {sdkFetcher} = vi.hoisted(() => ({sdkFetcher: {current: undefined as unknown as ApiFetcher}})); + +vi.mock('@thunderid/browser', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + createHttpClientFetcher: (): ApiFetcher => (url: string, init: RequestInit) => sdkFetcher.current(url, init), +})); + +const baseUrl = 'https://thunder.example'; + +const assistant: Agent = { + attributes: {name: 'Spending assistant', software: 'assistant-x'}, + clientId: 'pa_1', + description: 'Answers questions about my spending', + id: 'a-1', + inboundAuthConfig: [ + { + config: { + grantTypes: ['authorization_code'], + redirectUris: ['https://assistant.example.com/callback'], + responseTypes: ['code'], + }, + type: 'oauth2', + }, + ], + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', +}; + +interface Request { + body?: unknown; + method: string; + url: string; +} + +/** Answers like the server: the agent for a read or update, the list, suspend-all, and 204 for the rest. */ +const createServer = (agent: Agent = assistant, overrides: Record = {}): FetcherMock => + vi.fn().mockImplementation((url: string, init?: RequestInit) => { + const method: string = init?.method ?? 'GET'; + const path: string = new URL(url).pathname; + const override: Response | undefined = overrides[`${method} ${path}`]; + + if (override) { + return Promise.resolve(override); + } + if (path === '/users/me/agents') { + return Promise.resolve(jsonResponse({agents: [agent], count: 1, startIndex: 1, totalResults: 1})); + } + if (method === 'POST' && path === '/users/me/agents/suspend') { + return Promise.resolve(jsonResponse({suspendedCount: 1})); + } + if (method === 'GET' || method === 'PUT') { + return Promise.resolve(jsonResponse(agent)); + } + + return Promise.resolve(jsonResponse(undefined, 204)); + }); + +const requests = (fetcher: FetcherMock): Request[] => + fetcher.mock.calls.map(([url, init]: [string, RequestInit]) => ({ + body: typeof init?.body === 'string' ? (JSON.parse(init.body) as unknown) : undefined, + method: init?.method ?? 'GET', + url, + })); + +const mounted: VueWrapper[] = []; +let server: FetcherMock; + +const serve = (agent: Agent, overrides: Record = {}): void => { + server = createServer(agent, overrides); + sdkFetcher.current = server; +}; + +const mountWith = ( + component: unknown, + props: Record = {}, + {endpoints, slots = {}}: {endpoints?: Record; slots?: Record} = {}, +): {context: ReturnType; wrapper: VueWrapper} => { + const context = createManagementContext({endpoints}); + const wrapper: VueWrapper = mount(component as never, { + attachTo: document.body, + global: {provide: context.provide}, + props, + slots: slots as never, + }); + mounted.push(wrapper); + + return {context, wrapper}; +}; + +const button = (wrapper: VueWrapper | DOMWrapper, name: string): DOMWrapper | undefined => + wrapper.findAll('button').find((candidate: DOMWrapper) => candidate.text() === name); + +const field = (wrapper: VueWrapper, name: string): DOMWrapper => + wrapper.find(`input[name="${name}"]`); + +beforeEach(() => { + serve(assistant); +}); + +afterEach(() => { + mounted.splice(0).forEach((wrapper: VueWrapper) => wrapper.unmount()); +}); + +describe('PersonalAgentList', () => { + it("lists the user's personal agents through the SDK's own transport, not the management fetcher", async () => { + const onSelect: Mock = vi.fn(); + const {context, wrapper} = mountWith(PersonalAgentList, {onSelect}); + + await vi.waitFor(() => expect(wrapper.find('tbody').text()).toContain('Spending assistant')); + expect(wrapper.find('caption').text()).toBe(translate('user.agents.title')); + expect(wrapper.find('tbody').text()).toContain('pa_1'); + expect(wrapper.find('tbody').text()).toContain(translate('admin.common.status.active')); + expect(requests(server)[0]).toEqual({ + body: undefined, + method: 'GET', + url: `${baseUrl}/users/me/agents?kind=personal-assistant&limit=20&offset=0`, + }); + expect(context.fetcher).not.toHaveBeenCalled(); + + await wrapper.find('tbody button').trigger('click'); + expect(onSelect).toHaveBeenCalledWith(assistant); + }); + + it('sends requests to the usersMeAgents endpoint override', async () => { + mountWith(PersonalAgentList, {}, {endpoints: {usersMeAgents: 'https://rs.example.com/users/me/agents'}}); + + await vi.waitFor(() => expect(server).toHaveBeenCalled()); + expect(requests(server)[0].url).toBe( + 'https://rs.example.com/users/me/agents?kind=personal-assistant&limit=20&offset=0', + ); + }); + + it('offers no suspend-all unless the app turns it on', async () => { + const {wrapper} = mountWith(PersonalAgentList); + + await vi.waitFor(() => expect(wrapper.text()).toContain('Spending assistant')); + expect(button(wrapper, translate('user.agents.suspend_all.action'))).toBeUndefined(); + }); + + it('suspends every agent after confirmation and says how many', async () => { + const {wrapper} = mountWith(PersonalAgentList, {suspendable: true}); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.suspend_all.action'))).toBeDefined()); + await button(wrapper, translate('user.agents.suspend_all.action'))!.trigger('click'); + expect(requests(server).some(({method}: Request) => method === 'POST')).toBe(false); + await button(wrapper.find('[role="group"]'), translate('admin.common.actions.confirm'))!.trigger('click'); + + await vi.waitFor(() => expect(wrapper.text()).toContain(translate('user.agents.suspend_all.done', {count: 1}))); + expect(requests(server)).toContainEqual({ + body: undefined, + method: 'POST', + url: `${baseUrl}/users/me/agents/suspend`, + }); + }); + + it('shows a translated message, never the server text, when a request is refused', async () => { + serve(assistant, { + 'GET /users/me/agents': jsonResponse({code: 'AGT-1061', message: {defaultValue: 'Delegated token'}}, 403), + }); + const {wrapper} = mountWith(PersonalAgentList); + + await vi.waitFor(() => expect(wrapper.text()).toContain(translate('admin.common.errors.forbidden'))); + expect(wrapper.text()).not.toContain('Delegated token'); + }); +}); + +describe('BasePersonalAgentList', () => { + it('says so when the user has no personal agents, and hides suspend-all', () => { + const {wrapper} = mountWith(BasePersonalAgentList, {agents: [], onSuspendAll: vi.fn()}); + + expect(wrapper.text()).toContain(translate('user.agents.list.empty')); + expect(button(wrapper, translate('user.agents.suspend_all.action'))).toBeUndefined(); + }); + + it('hands a custom render the agents, the columns and suspend-all', () => { + let props: BasePersonalAgentListRenderProps | undefined; + const onSuspendAll: Mock = vi.fn(); + const {wrapper} = mountWith( + BasePersonalAgentList, + {agents: [assistant], onSuspendAll}, + { + slots: { + default: (renderProps: BasePersonalAgentListRenderProps) => { + props = renderProps; + return h('p', 'custom list'); + }, + }, + }, + ); + + expect(wrapper.text()).toContain('custom list'); + expect(props?.agents).toEqual([assistant]); + expect(props?.rows).toEqual([assistant]); + expect(props?.columns.map((column: {id: string}) => column.id)).toEqual(['name', 'clientId', 'status']); + expect(props?.totalResults).toBe(1); + props?.onSuspendAll?.(); + expect(onSuspendAll).toHaveBeenCalled(); + }); +}); + +describe('PersonalAgentDetails', () => { + it("shows the agent through the SDK's own transport, and offers no action unless the app turns it on", async () => { + const {context, wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1'}); + + await vi.waitFor(() => expect(wrapper.find('h2').text()).toBe('Spending assistant')); + expect(wrapper.text()).toContain(translate('user.agents.grant_types.authorization_code')); + expect(wrapper.text()).toContain('https://assistant.example.com/callback'); + expect(wrapper.text()).toContain('software'); + expect(wrapper.text()).toContain('assistant-x'); + expect(requests(server)[0]).toEqual({ + body: undefined, + method: 'GET', + url: `${baseUrl}/users/me/agents/a-1?include=display`, + }); + expect(context.fetcher).not.toHaveBeenCalled(); + [ + translate('user.agents.edit.action'), + translate('user.agents.suspend.action'), + translate('user.agents.unsuspend.action'), + translate('user.agents.delete.action'), + ].forEach((name: string) => expect(button(wrapper, name)).toBeUndefined()); + }); + + it('suspends the agent after confirmation, then offers to lift the suspension', async () => { + const {wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1', suspendable: true}); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.suspend.action'))).toBeDefined()); + await button(wrapper, translate('user.agents.suspend.action'))!.trigger('click'); + serve({...assistant, status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}}); + const confirmation: DOMWrapper = wrapper.find('[role="group"]'); + expect(confirmation.attributes('aria-label')).toBe( + translate('user.agents.suspend.confirm', {name: 'Spending assistant'}), + ); + await button(confirmation, translate('admin.common.actions.confirm'))!.trigger('click'); + + await vi.waitFor(() => + expect(requests(server)).toContainEqual({ + body: undefined, + method: 'POST', + url: `${baseUrl}/users/me/agents/a-1/suspend`, + }), + ); + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.unsuspend.action'))).toBeDefined()); + expect(wrapper.text()).toContain(translate('user.agents.suspension.owner')); + }); + + it("lifts the owner's suspension, which needs no confirmation", async () => { + serve({...assistant, status: {details: {appliedBy: ['owner']}, value: 'SUSPENDED'}}); + const {wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1', suspendable: true}); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.unsuspend.action'))).toBeDefined()); + await button(wrapper, translate('user.agents.unsuspend.action'))!.trigger('click'); + + await vi.waitFor(() => + expect(requests(server)).toContainEqual({ + body: undefined, + method: 'POST', + url: `${baseUrl}/users/me/agents/a-1/unsuspend`, + }), + ); + }); + + it("explains the organization's suspension and offers only the owner's own", async () => { + serve({...assistant, status: {details: {appliedBy: ['organization']}, value: 'SUSPENDED'}}); + const {wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1', suspendable: true}); + + await vi.waitFor(() => expect(wrapper.text()).toContain(translate('user.agents.suspension.organization'))); + expect(button(wrapper, translate('user.agents.suspend.action'))).toBeDefined(); + expect(button(wrapper, translate('user.agents.unsuspend.action'))).toBeUndefined(); + }); + + it('saves the editable part, keeping the attributes it does not edit', async () => { + serve({...assistant, attributes: {...assistant.attributes, tags: ['finance']}}); + const {wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1', editable: true}); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.edit.action'))).toBeDefined()); + await button(wrapper, translate('user.agents.edit.action'))!.trigger('click'); + await field(wrapper, 'name').setValue('Budget assistant'); + await field(wrapper, 'attribute-software').setValue('assistant-y'); + await field(wrapper, 'grantType-refresh_token').setValue(true); + await wrapper.find('form').trigger('submit'); + + await vi.waitFor(() => + expect(requests(server)).toContainEqual({ + body: { + attributes: {name: 'Budget assistant', software: 'assistant-y', tags: ['finance']}, + description: 'Answers questions about my spending', + grantTypes: ['authorization_code', 'refresh_token'], + redirectUris: ['https://assistant.example.com/callback'], + }, + method: 'PUT', + url: `${baseUrl}/users/me/agents/a-1`, + }), + ); + }); + + it('keeps the save off while the authorization code grant has no redirect URI', async () => { + const {wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1', editable: true}); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.edit.action'))).toBeDefined()); + await button(wrapper, translate('user.agents.edit.action'))!.trigger('click'); + await field(wrapper, 'redirectUris').setValue(''); + + expect(button(wrapper, translate('user.agents.edit.save'))!.element.disabled).toBe(true); + + await field(wrapper, 'grantType-authorization_code').setValue(false); + expect(button(wrapper, translate('user.agents.edit.save'))!.element.disabled).toBe(false); + }); + + it('deletes the agent after confirmation', async () => { + const {wrapper} = mountWith(PersonalAgentDetails, {agentId: 'a-1', deletable: true}); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.delete.action'))).toBeDefined()); + await button(wrapper, translate('user.agents.delete.action'))!.trigger('click'); + expect(requests(server).some(({method}: Request) => method === 'DELETE')).toBe(false); + await button(wrapper.find('[role="group"]'), translate('admin.common.actions.confirm'))!.trigger('click'); + + await vi.waitFor(() => expect(wrapper.emitted('deleted')).toHaveLength(1)); + expect(requests(server)).toContainEqual({body: undefined, method: 'DELETE', url: `${baseUrl}/users/me/agents/a-1`}); + }); + + it('offers no edit or deletion for a declarative agent', async () => { + serve({...assistant, isReadOnly: true}); + const {wrapper} = mountWith(PersonalAgentDetails, { + agentId: 'a-1', + deletable: true, + editable: true, + suspendable: true, + }); + + await vi.waitFor(() => expect(button(wrapper, translate('user.agents.suspend.action'))).toBeDefined()); + expect(button(wrapper, translate('user.agents.edit.action'))).toBeUndefined(); + expect(button(wrapper, translate('user.agents.delete.action'))).toBeUndefined(); + }); +}); + +describe('BasePersonalAgentDetails', () => { + const renderSlot = (agent: Agent, handlers: Record): BasePersonalAgentDetailsRenderProps => { + let props: BasePersonalAgentDetailsRenderProps | undefined; + mountWith( + BasePersonalAgentDetails, + {agent, ...handlers}, + { + slots: { + default: (renderProps: BasePersonalAgentDetailsRenderProps) => { + props = renderProps; + return h('p', 'custom view'); + }, + }, + }, + ); + + return props!; + }; + + it("closes the edit form when the agent changes, so one agent's values are never saved onto another", async () => { + const onUpdate: Mock = vi.fn(); + const {wrapper} = mountWith(BasePersonalAgentDetails, {agent: assistant, onUpdate}); + + await button(wrapper, translate('user.agents.edit.action'))!.trigger('click'); + await field(wrapper, 'name').setValue('Budget assistant'); + await wrapper.setProps({agent: {...assistant, attributes: {name: 'Travel planner'}, id: 'a-2'}}); + + expect(wrapper.find('form').exists()).toBe(false); + await button(wrapper, translate('user.agents.edit.action'))!.trigger('click'); + expect(field(wrapper, 'name').element.value).toBe('Travel planner'); + expect(onUpdate).not.toHaveBeenCalled(); + }); + + it('hands a custom render the agent and only the actions that apply', () => { + const onUnsuspend: Mock = vi.fn(); + const agent: Agent = { + ...assistant, + isReadOnly: true, + status: {details: {appliedBy: ['owner']}, value: 'SUSPENDED'}, + }; + const props: BasePersonalAgentDetailsRenderProps = renderSlot(agent, { + onDelete: vi.fn(), + onSuspend: vi.fn(), + onUnsuspend, + onUpdate: vi.fn(), + }); + + expect(props.agent).toEqual(agent); + expect(props.oauth?.grantTypes).toEqual(['authorization_code']); + expect(props.onDelete).toBeUndefined(); + expect(props.onUpdate).toBeUndefined(); + expect(props.onSuspend).toBeUndefined(); + props.onUnsuspend?.(); + expect(onUnsuspend).toHaveBeenCalled(); + }); + + it('hands a custom render the suspension of an agent the owner has not suspended', () => { + const props: BasePersonalAgentDetailsRenderProps = renderSlot( + {...assistant, status: {details: {appliedBy: ['organization']}, value: 'SUSPENDED'}}, + {onSuspend: vi.fn(), onUnsuspend: vi.fn()}, + ); + + expect(props.onSuspend).toBeDefined(); + expect(props.onUnsuspend).toBeUndefined(); + }); + + it('says the agent was not found when there is none to show', () => { + const {wrapper} = mountWith(BasePersonalAgentDetails, {}); + + expect(wrapper.find('[role="alert"]').text()).toBe(translate('admin.common.errors.not_found')); + }); +}); diff --git a/packages/vue/src/__tests__/components/management/management-components.test.ts b/packages/vue/src/__tests__/components/management/management-components.test.ts index 6f904941..d87a7ab0 100644 --- a/packages/vue/src/__tests__/components/management/management-components.test.ts +++ b/packages/vue/src/__tests__/components/management/management-components.test.ts @@ -1221,6 +1221,46 @@ describe('admin components (vue)', () => { const {wrapper: unowned} = mountWith(BaseAgentDetails, {agent: {id: 'ag-3', ouId: 'ou-1', type: 'bot'}}); expect(unowned.text()).toContain(translate('admin.agents.details.no_owner')); }); + + it('marks a personal agent and names every party holding it suspended', () => { + const {wrapper} = mountWith(BaseAgentDetails, { + agent: { + id: 'a-1', + kind: 'personal-assistant', + ouId: 'ou-1', + owner: {id: 'u-1'}, + status: {details: {appliedBy: ['owner', 'cascade']}, value: 'SUSPENDED'}, + type: 'x', + }, + }); + + expect(wrapper.text()).toContain(translate('admin.agents.kind.personal')); + expect(wrapper.text()).toContain( + `${translate('admin.agents.details.suspension.owner')}, ${translate('admin.agents.details.suspension.cascade')}`, + ); + }); + + it('names no suspending party for an agent that is not suspended', () => { + const {wrapper} = mountWith(BaseAgentDetails, { + agent: {id: 'a-1', ouId: 'ou-1', status: {value: 'ACTIVE'}, type: 'x'}, + }); + + expect(wrapper.text()).not.toContain(translate('admin.agents.details.suspension.title')); + expect(wrapper.text()).not.toContain(translate('admin.agents.kind.personal')); + }); + + it('marks only the personal agents in the list', () => { + const {wrapper} = mountWith(BaseAgentList, { + agents: [ + {attributes: {name: 'Spending assistant'}, id: 'ag-1', kind: 'personal-assistant', ouId: 'ou-1', type: 'x'}, + {attributes: {name: 'Billing bot'}, id: 'ag-2', ouId: 'ou-1', type: 'x'}, + ], + }); + + const rows: DOMWrapper[] = wrapper.findAll('tbody tr'); + expect(rows[0].text()).toContain(translate('admin.agents.kind.personal')); + expect(rows[1].text()).not.toContain(translate('admin.agents.kind.personal')); + }); }); describe('search and filters', () => { @@ -1893,6 +1933,36 @@ describe('admin components (vue)', () => { expect(context.fetcher.mock.calls.some(([url]) => url.endsWith('/members/remove'))).toBe(false); }); + it("offers the organization's own suspension, not an unsuspend, for an agent only its owner suspended", async () => { + const context = createFlowContext({ + configured: {agentSuspendFlow: 'suspend-agent', agentUnsuspendFlow: 'unsuspend-agent'}, + resources: { + '/agents/a-1': { + attributes: {name: 'Spending assistant'}, + id: 'a-1', + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'bot', + }, + }, + }); + const {wrapper} = mountWith(AgentDetails, {agentId: 'a-1', lifecycleActions: true}, context); + + await vi.waitFor(() => + expect(lifecycleButton(wrapper, translate('admin.common.lifecycle.suspend'))).toBeDefined(), + ); + expect(lifecycleButton(wrapper, translate('admin.common.lifecycle.unsuspend'))).toBeUndefined(); + await lifecycleButton(wrapper, translate('admin.common.lifecycle.suspend'))!.trigger('click'); + await lifecycleButton(wrapper.find('[role="group"]'), translate('admin.common.lifecycle.suspend'))!.trigger( + 'click', + ); + + await vi.waitFor(() => + expect(executions(context)).toEqual([{flowId: 'id-suspend-agent', inputs: {subject: 'a-1'}}]), + ); + }); + it('unsuspends an agent through its flow', async () => { const context = createFlowContext({ configured: {agentSuspendFlow: 'suspend-agent', agentUnsuspendFlow: 'unsuspend-agent'}, diff --git a/packages/vue/src/api/account/deleteMeAgent.ts b/packages/vue/src/api/account/deleteMeAgent.ts new file mode 100644 index 00000000..ea6cb61d --- /dev/null +++ b/packages/vue/src/api/account/deleteMeAgent.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + deleteMeAgent as baseDeleteMeAgent, + DeleteMeAgentConfig as BaseDeleteMeAgentConfig, +} from '@thunderid/browser'; + +export interface DeleteMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Deletes one of the signed-in user's personal agents, with the signed-in user's access token attached by the + * SDK's HTTP client. + * + * @example + * ```typescript + * await deleteMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const deleteMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: DeleteMeAgentConfig): Promise => + baseDeleteMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default deleteMeAgent; diff --git a/packages/vue/src/api/account/getMeAgent.ts b/packages/vue/src/api/account/getMeAgent.ts new file mode 100644 index 00000000..cebe7e3d --- /dev/null +++ b/packages/vue/src/api/account/getMeAgent.ts @@ -0,0 +1,38 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + Agent, + createHttpClientFetcher, + getMeAgent as baseGetMeAgent, + GetMeAgentConfig as BaseGetMeAgentConfig, +} from '@thunderid/browser'; + +export interface GetMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Retrieves one of the agents the signed-in user owns, with the signed-in user's access token attached by the + * SDK's HTTP client. + * + * @example + * ```typescript + * const agent = await getMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const getMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: GetMeAgentConfig): Promise => + baseGetMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default getMeAgent; diff --git a/packages/vue/src/api/account/getMeAgents.ts b/packages/vue/src/api/account/getMeAgents.ts new file mode 100644 index 00000000..b00d2169 --- /dev/null +++ b/packages/vue/src/api/account/getMeAgents.ts @@ -0,0 +1,46 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + AgentListResponse, + createHttpClientFetcher, + getMeAgents as baseGetMeAgents, + GetMeAgentsConfig as BaseGetMeAgentsConfig, +} from '@thunderid/browser'; + +export interface GetMeAgentsConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Retrieves a page of the agents the signed-in user owns, from `/users/me/agents`, with the signed-in user's + * access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * const {agents, totalResults} = await getMeAgents({ + * baseUrl: 'https://localhost:8090', + * kind: PERSONAL_AGENT_KIND, + * limit: 10, + * }); + * ``` + */ +const getMeAgents = async ({ + fetcher, + instanceId = 0, + ...requestConfig +}: GetMeAgentsConfig): Promise => + baseGetMeAgents({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default getMeAgents; diff --git a/packages/vue/src/api/account/suspendAllMeAgents.ts b/packages/vue/src/api/account/suspendAllMeAgents.ts new file mode 100644 index 00000000..87634f93 --- /dev/null +++ b/packages/vue/src/api/account/suspendAllMeAgents.ts @@ -0,0 +1,42 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + SuspendAllMeAgentsResponse, + suspendAllMeAgents as baseSuspendAllMeAgents, + SuspendAllMeAgentsConfig as BaseSuspendAllMeAgentsConfig, +} from '@thunderid/browser'; + +export interface SuspendAllMeAgentsConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Suspends every personal agent of the signed-in user that the user has not already suspended, with the + * signed-in user's access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * const {suspendedCount} = await suspendAllMeAgents({baseUrl: 'https://localhost:8090'}); + * ``` + */ +const suspendAllMeAgents = async ({ + fetcher, + instanceId = 0, + ...requestConfig +}: SuspendAllMeAgentsConfig): Promise => + baseSuspendAllMeAgents({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default suspendAllMeAgents; diff --git a/packages/vue/src/api/account/suspendMeAgent.ts b/packages/vue/src/api/account/suspendMeAgent.ts new file mode 100644 index 00000000..3a940cae --- /dev/null +++ b/packages/vue/src/api/account/suspendMeAgent.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + suspendMeAgent as baseSuspendMeAgent, + SuspendMeAgentConfig as BaseSuspendMeAgentConfig, +} from '@thunderid/browser'; + +export interface SuspendMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Places the owner's suspension on one of the signed-in user's personal agents, with the signed-in user's + * access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * await suspendMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const suspendMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: SuspendMeAgentConfig): Promise => + baseSuspendMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default suspendMeAgent; diff --git a/packages/vue/src/api/account/unsuspendMeAgent.ts b/packages/vue/src/api/account/unsuspendMeAgent.ts new file mode 100644 index 00000000..67d851df --- /dev/null +++ b/packages/vue/src/api/account/unsuspendMeAgent.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + createHttpClientFetcher, + unsuspendMeAgent as baseUnsuspendMeAgent, + UnsuspendMeAgentConfig as BaseUnsuspendMeAgentConfig, +} from '@thunderid/browser'; + +export interface UnsuspendMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Lifts the owner's suspension from one of the signed-in user's personal agents, with the signed-in user's + * access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * await unsuspendMeAgent({baseUrl: 'https://localhost:8090', agentId: 'a-1'}); + * ``` + */ +const unsuspendMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: UnsuspendMeAgentConfig): Promise => + baseUnsuspendMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default unsuspendMeAgent; diff --git a/packages/vue/src/api/account/updateMeAgent.ts b/packages/vue/src/api/account/updateMeAgent.ts new file mode 100644 index 00000000..dca4df93 --- /dev/null +++ b/packages/vue/src/api/account/updateMeAgent.ts @@ -0,0 +1,42 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + Agent, + createHttpClientFetcher, + updateMeAgent as baseUpdateMeAgent, + UpdateMeAgentConfig as BaseUpdateMeAgentConfig, +} from '@thunderid/browser'; + +export interface UpdateMeAgentConfig extends Omit { + /** + * Optional custom fetcher function. If not provided, the ThunderID SPA client's httpClient is used, which + * attaches the signed-in user's access token. + */ + fetcher?: (url: string, config: RequestInit) => Promise; + /** + * Optional instance ID for multi-instance support. Defaults to 0. + */ + instanceId?: number; +} + +/** + * Replaces the part of one of the signed-in user's personal agents its owner may change, with the signed-in + * user's access token attached by the SDK's HTTP client. + * + * @example + * ```typescript + * const agent = await updateMeAgent({ + * baseUrl: 'https://localhost:8090', + * agentId: 'a-1', + * payload: {attributes: {name: 'Spending assistant'}, grantTypes: ['ciba'], redirectUris: []}, + * }); + * ``` + */ +const updateMeAgent = async ({fetcher, instanceId = 0, ...requestConfig}: UpdateMeAgentConfig): Promise => + baseUpdateMeAgent({ + ...requestConfig, + fetcher: fetcher ?? createHttpClientFetcher(instanceId), + }); + +export default updateMeAgent; diff --git a/packages/vue/src/components/account/personal-agent-details/BasePersonalAgentDetails.ts b/packages/vue/src/components/account/personal-agent-details/BasePersonalAgentDetails.ts new file mode 100644 index 00000000..8b49e84b --- /dev/null +++ b/packages/vue/src/components/account/personal-agent-details/BasePersonalAgentDetails.ts @@ -0,0 +1,407 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + type Agent, + type OAuth2Config, + PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS, + PERSONAL_AGENT_GRANT_TYPES, + type PersonalAgentFormValues, + type Preferences, + type SuspensionAppliedBy, + type UpdateMeAgentRequest, + getAgentName, + getMeAgentSuspensionAction, + getPersonalAgentOAuthConfig, + isPersonalAgentFormValid, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, + withVendorCSSClassPrefix, +} from '@thunderid/browser'; +import { + type Component, + type PropType, + type Ref, + type SetupContext, + type VNode, + type VNodeChild, + defineComponent, + h, + ref, + watch, +} from 'vue'; +import AccessStatusBadge from '../../management/shared/AccessStatusBadge'; +import AdminSection from '../../management/shared/AdminSection'; +import ConfirmButton from '../../management/shared/ConfirmButton'; +import DetailList, {type DetailListItem} from '../../management/shared/DetailList'; +import Panel from '../../management/shared/Panel'; +import renderEditPanel from '../../management/shared/renderEditPanel'; +import useAdminTranslation, {type AdminTranslate} from '../../management/shared/useAdminTranslation'; +import Alert from '../../primitives/Alert/Alert'; +import Button from '../../primitives/Button/Button'; +import Checkbox from '../../primitives/Checkbox/Checkbox'; +import CopyableText from '../../primitives/CopyableText/CopyableText'; +import Spinner from '../../primitives/Spinner/Spinner'; +import TextField from '../../primitives/TextField/TextField'; + +/** + * What `BasePersonalAgentDetails` hands its default scoped slot, so the agent can be shown with any UI. An action + * is undefined when the app has not turned it on, or when it does not apply to the agent. + */ +export interface BasePersonalAgentDetailsRenderProps { + agent?: Agent; + error: string | null; + isChangingSuspension: boolean; + isDeleting: boolean; + isLoading: boolean; + isUpdating: boolean; + /** The agent's OAuth configuration. Undefined when it has no OAuth client. */ + oauth?: OAuth2Config; + /** Deletes the agent. The built-in UI asks for confirmation first, and a custom render must too. */ + onDelete?: () => void; + /** Places the owner's suspension on the agent. Offered unless the owner already holds it suspended. */ + onSuspend?: () => void; + /** Lifts the owner's suspension of the agent. Offered only while the owner holds it suspended. */ + onUnsuspend?: () => void; + /** Replaces the editable part of the agent. */ + onUpdate?: (changes: UpdateMeAgentRequest) => void; +} + +type BasePersonalAgentDetailsProps = Readonly<{ + agent: Agent | undefined; + className: string; + error: string | null; + isChangingSuspension: boolean; + isDeleting: boolean; + isLoading: boolean; + isUpdating: boolean; + onDelete: (() => void) | undefined; + onSuspend: (() => void) | undefined; + onUnsuspend: (() => void) | undefined; + onUpdate: ((changes: UpdateMeAgentRequest) => void) | undefined; + preferences: Preferences | undefined; +}>; + +const cls = (element: string): string => withVendorCSSClassPrefix(`admin__${element}`); + +const stringify = (value: unknown): string => { + if (value === null || value === undefined) { + return ''; + } + + return typeof value === 'object' ? JSON.stringify(value) : String(value as string | number | boolean); +}; + +/** + * Shows one of the signed-in user's personal agents with the actions its owner can take. Holds no data of its own: + * pass the agent and handle editing, deletion and the owner's suspension, each offered only when its handler is set. + * + * Slots: `actions`, rendered next to the agent's name; `default`, a scoped slot that replaces the view with custom + * UI and receives {@link BasePersonalAgentDetailsRenderProps}. + */ +const BasePersonalAgentDetails: Component = defineComponent({ + name: 'BasePersonalAgentDetails', + props: { + /** The agent to show. */ + agent: {default: undefined, type: Object as PropType}, + /** Extra CSS class added to the root element. */ + className: {default: '', type: String}, + /** An error message, already translated. */ + error: {default: null, type: String as PropType}, + isChangingSuspension: {default: false, type: Boolean}, + isDeleting: {default: false, type: Boolean}, + isLoading: {default: false, type: Boolean}, + isUpdating: {default: false, type: Boolean}, + /** Deletes the agent. Hidden when omitted, and for a declarative agent. Also available as `@delete`. */ + onDelete: {default: undefined, type: Function as PropType<() => void>}, + /** Places the owner's suspension on the agent. Hidden when omitted. Also available as `@suspend`. */ + onSuspend: {default: undefined, type: Function as PropType<() => void>}, + /** + * Lifts the owner's suspension of the agent. Shown only while the owner holds the agent suspended. Also + * available as `@unsuspend`. + */ + onUnsuspend: {default: undefined, type: Function as PropType<() => void>}, + /** + * Replaces the editable part of the agent. Hidden when omitted, and for a declarative agent. Also available + * as `@update`. + */ + onUpdate: {default: undefined, type: Function as PropType<(changes: UpdateMeAgentRequest) => void>}, + /** Component-level preferences, for example `i18n.bundles` overrides. */ + preferences: {default: undefined, type: Object as PropType}, + }, + setup(props: BasePersonalAgentDetailsProps, {slots}: SetupContext): () => VNode { + const t: AdminTranslate = useAdminTranslation(() => props.preferences); + const draft: Ref = ref(null); + + // Switching the agent closes the form, so one agent's values are never saved onto another. + watch( + () => props.agent?.id, + () => { + draft.value = null; + }, + ); + + const grantTypeLabel = (grantType: string): string => + PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS[grantType] ? t(PERSONAL_AGENT_GRANT_TYPE_LABEL_KEYS[grantType]) : grantType; + + const editDraft = (changes: Partial): void => { + if (draft.value) { + draft.value = {...draft.value, ...changes}; + } + }; + + const renderForm = (agent: Agent, values: PersonalAgentFormValues): VNode => + renderEditPanel({ + canSave: isPersonalAgentFormValid(values), + fields: [ + h(TextField, { + autoComplete: 'off', + label: t('user.agents.fields.name'), + modelValue: values.name, + name: 'name', + 'onUpdate:modelValue': (value: string): void => editDraft({name: value}), + required: true, + }), + ...Object.keys(values.attributes).map((attribute: string) => + h(TextField, { + autoComplete: 'off', + key: attribute, + label: attribute, + modelValue: values.attributes[attribute], + name: `attribute-${attribute}`, + 'onUpdate:modelValue': (value: string): void => + editDraft({attributes: {...values.attributes, [attribute]: value}}), + }), + ), + h(TextField, { + autoComplete: 'off', + label: t('user.agents.fields.description'), + modelValue: values.description, + name: 'description', + 'onUpdate:modelValue': (value: string): void => editDraft({description: value}), + }), + h(TextField, { + autoComplete: 'off', + helperText: t('user.agents.fields.redirect_uris_hint'), + label: t('user.agents.details.redirect_uris'), + modelValue: values.redirectUris, + name: 'redirectUris', + 'onUpdate:modelValue': (value: string): void => editDraft({redirectUris: value}), + }), + h('fieldset', {class: cls('row'), style: {border: 0, flexWrap: 'wrap', margin: 0, padding: 0}}, [ + h('legend', {class: cls('muted')}, t('user.agents.details.grant_types')), + ...PERSONAL_AGENT_GRANT_TYPES.map((grantType: string) => + h(Checkbox, { + key: grantType, + label: grantTypeLabel(grantType), + modelValue: values.grantTypes.includes(grantType), + name: `grantType-${grantType}`, + 'onUpdate:modelValue': (checked: boolean): void => + editDraft({ + grantTypes: checked + ? [...values.grantTypes, grantType] + : values.grantTypes.filter((value: string) => value !== grantType), + }), + }), + ), + ]), + ], + isSaving: props.isUpdating, + onCancel: (): void => { + draft.value = null; + }, + onSave: (): void => { + props.onUpdate?.(toUpdateMeAgentRequest(agent, values)); + draft.value = null; + }, + saveLabel: t('user.agents.edit.save'), + t, + title: t('user.agents.edit.title'), + }); + + return (): VNode => { + const {agent} = props; + const isWritable: boolean = Boolean(agent) && !agent?.isReadOnly; + const suspensionAction: 'suspend' | 'unsuspend' = getMeAgentSuspensionAction(agent?.status); + const canSuspend: boolean = Boolean(agent) && suspensionAction === 'suspend'; + const canUnsuspend: boolean = Boolean(agent) && suspensionAction === 'unsuspend'; + + if (slots['default']) { + const renderProps: BasePersonalAgentDetailsRenderProps = { + agent, + error: props.error, + isChangingSuspension: props.isChangingSuspension, + isDeleting: props.isDeleting, + isLoading: props.isLoading, + isUpdating: props.isUpdating, + oauth: agent ? getPersonalAgentOAuthConfig(agent) : undefined, + onDelete: isWritable ? props.onDelete : undefined, + onSuspend: canSuspend ? props.onSuspend : undefined, + onUnsuspend: canUnsuspend ? props.onUnsuspend : undefined, + onUpdate: isWritable ? props.onUpdate : undefined, + }; + + return h('div', {class: props.className}, slots['default'](renderProps)); + } + + if (props.isLoading && !agent) { + return h( + AdminSection, + {block: 'personal-agent-details', className: props.className}, + { + default: (): VNode => + h('span', {class: cls('muted'), role: 'status'}, [ + h(Spinner, {'aria-hidden': 'true', size: 'small'}), + t('admin.common.loading'), + ]), + }, + ); + } + + if (!agent) { + return h( + AdminSection, + {block: 'personal-agent-details', className: props.className}, + { + default: (): VNode => + h( + Alert, + {role: 'alert', severity: 'error'}, + {default: (): string[] => [props.error ?? t('admin.common.errors.not_found')]}, + ), + }, + ); + } + + const name: string = getAgentName(agent); + const oauth: OAuth2Config | undefined = getPersonalAgentOAuthConfig(agent); + const appliedBy: SuspensionAppliedBy[] = + agent.status?.value === 'SUSPENDED' ? (agent.status.details?.appliedBy ?? []) : []; + const none = (): VNode => h('span', {class: cls('muted')}, t('user.agents.details.none')); + const overview: DetailListItem[] = [ + { + label: t('user.agents.list.columns.status'), + value: h(AccessStatusBadge, {status: agent.status?.value, t}), + }, + { + label: t('user.agents.details.client_id'), + value: agent.clientId ? h(CopyableText, {value: agent.clientId}) : none(), + }, + { + label: t('user.agents.details.grant_types'), + value: oauth?.grantTypes?.length ? oauth.grantTypes.map(grantTypeLabel).join(', ') : none(), + }, + { + label: t('user.agents.details.redirect_uris'), + value: oauth?.redirectUris?.length + ? oauth.redirectUris.map((uri: string) => h('div', {key: uri}, uri)) + : none(), + }, + ]; + const attributes: [string, unknown][] = Object.entries(agent.attributes ?? {}); + + const content = (): VNodeChild[] => + draft.value + ? [renderForm(agent, draft.value)] + : [ + h( + Panel, + {title: t('user.agents.details.overview')}, + { + actions: (): VNode | null => + props.onUpdate && isWritable + ? h( + Button, + { + onClick: (): void => { + draft.value = toPersonalAgentFormValues(agent); + }, + size: 'small', + variant: 'outline', + }, + {default: (): string => t('user.agents.edit.action')}, + ) + : null, + default: (): VNode => h(DetailList, {items: overview}), + }, + ), + h( + Panel, + {title: t('user.agents.details.attributes')}, + { + default: (): VNode => + attributes.length > 0 + ? h(DetailList, { + items: attributes.map(([attribute, value]: [string, unknown]) => ({ + label: attribute, + value: stringify(value), + })), + }) + : none(), + }, + ), + ]; + + return h( + AdminSection, + {block: 'personal-agent-details', className: props.className, description: agent.description, title: name}, + { + actions: (): (VNode | VNode[] | null | undefined)[] => [ + slots['actions']?.(), + props.onUnsuspend && canUnsuspend + ? h( + Button, + { + disabled: props.isChangingSuspension, + loading: props.isChangingSuspension, + onClick: props.onUnsuspend, + variant: 'outline', + }, + {default: (): string => t('user.agents.unsuspend.action')}, + ) + : null, + props.onSuspend && canSuspend + ? h( + ConfirmButton, + { + confirmText: t('user.agents.suspend.confirm', {name}), + isLoading: props.isChangingSuspension, + onConfirm: props.onSuspend, + t, + }, + {default: (): string => t('user.agents.suspend.action')}, + ) + : null, + props.onDelete && isWritable + ? h( + ConfirmButton, + { + confirmText: t('user.agents.delete.confirm', {name}), + isLoading: props.isDeleting, + onConfirm: props.onDelete, + t, + }, + {default: (): string => t('user.agents.delete.action')}, + ) + : null, + ], + default: (): VNodeChild[] => [ + props.error + ? h(Alert, {role: 'alert', severity: 'error'}, {default: (): string[] => [props.error!]}) + : null, + ...appliedBy.map((party: SuspensionAppliedBy) => + h( + Alert, + {key: party, role: 'status', severity: party === 'owner' ? 'info' : 'warning'}, + {default: (): string[] => [t(`user.agents.suspension.${party}`)]}, + ), + ), + ...content(), + ], + }, + ); + }; + }, +}); + +export default BasePersonalAgentDetails; diff --git a/packages/vue/src/components/account/personal-agent-details/PersonalAgentDetails.ts b/packages/vue/src/components/account/personal-agent-details/PersonalAgentDetails.ts new file mode 100644 index 00000000..792b0471 --- /dev/null +++ b/packages/vue/src/components/account/personal-agent-details/PersonalAgentDetails.ts @@ -0,0 +1,120 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + type Agent, + AgentQueryKeys, + type Preferences, + type ResourceQueryKey, + type UpdateMeAgentRequest, + resolveResourceEndpoint, + toManagementErrorMessage, +} from '@thunderid/browser'; +import {type Component, type PropType, type SetupContext, type VNode, defineComponent, h} from 'vue'; +import BasePersonalAgentDetails from './BasePersonalAgentDetails'; +import deleteMeAgent from '../../../api/account/deleteMeAgent'; +import getMeAgent from '../../../api/account/getMeAgent'; +import suspendMeAgent from '../../../api/account/suspendMeAgent'; +import unsuspendMeAgent from '../../../api/account/unsuspendMeAgent'; +import updateMeAgent from '../../../api/account/updateMeAgent'; +import useResourceMutation, {type ResourceMutationResult} from '../../../composables/management/useResourceMutation'; +import useResourceQuery, {type ResourceQueryResult} from '../../../composables/management/useResourceQuery'; +import useThunderID from '../../../composables/useThunderID'; +import type {ThunderIDContext} from '../../../models/contexts'; +import useAdminTranslation, {type AdminTranslate} from '../../management/shared/useAdminTranslation'; + +type PersonalAgentDetailsProps = Readonly<{ + agentId: string; + className: string; + deletable: boolean; + editable: boolean; + preferences: Preferences | undefined; + suspendable: boolean; +}>; + +/** + * Shows one of the signed-in user's personal agents, and, when the app allows it, lets the user edit, delete and + * suspend it. Emits `deleted` after the agent has been deleted. + * + * Slots: `actions`, rendered next to the agent's name; `default`, a scoped slot that replaces the view with custom + * UI and receives `BasePersonalAgentDetailsRenderProps`. + * + * @example + * ```vue + * + * ``` + */ +const PersonalAgentDetails: Component = defineComponent({ + name: 'PersonalAgentDetails', + props: { + /** Identifier of the agent to show. */ + agentId: {required: true, type: String}, + /** Extra CSS class added to the root element. */ + className: {default: '', type: String}, + /** Whether the agent can be deleted from this view. */ + deletable: {default: false, type: Boolean}, + /** Whether the agent can be edited from this view. */ + editable: {default: false, type: Boolean}, + /** Component-level preferences, for example `i18n.bundles` overrides. */ + preferences: {default: undefined, type: Object as PropType}, + /** Whether the user can suspend the agent, and lift their own suspension, from this view. */ + suspendable: {default: false, type: Boolean}, + }, + emits: ['deleted'], + setup(props: PersonalAgentDetailsProps, {emit, slots}: SetupContext): () => VNode { + const t: AdminTranslate = useAdminTranslation(() => props.preferences); + const {baseUrl, endpoints, instanceId}: ThunderIDContext = useThunderID(); + const url: string | undefined = resolveResourceEndpoint('usersMeAgents', {endpoints}); + const changed = (): ResourceQueryKey[] => [[AgentQueryKeys.ME_AGENT, props.agentId], [AgentQueryKeys.ME_AGENTS]]; + + // These are the user's own requests, so they go through the SDK's transport for this instance, like the other + // `users/me` operations, and never the management `http.fetcher` the composables would otherwise hand them. + const agent: ResourceQueryResult = useResourceQuery( + () => [AgentQueryKeys.ME_AGENT, props.agentId], + () => getMeAgent({agentId: props.agentId, baseUrl, instanceId, url}), + {enabled: (): boolean => Boolean(props.agentId)}, + ); + const update: ResourceMutationResult = useResourceMutation( + (payload: UpdateMeAgentRequest) => updateMeAgent({agentId: props.agentId, baseUrl, instanceId, payload, url}), + changed, + ); + const deletion: ResourceMutationResult = useResourceMutation( + () => deleteMeAgent({agentId: props.agentId, baseUrl, instanceId, url}), + () => [[AgentQueryKeys.ME_AGENTS]], + {onSuccess: (): void => emit('deleted')}, + ); + const suspension: ResourceMutationResult = useResourceMutation( + (action: 'suspend' | 'unsuspend') => + (action === 'suspend' ? suspendMeAgent : unsuspendMeAgent)({agentId: props.agentId, baseUrl, instanceId, url}), + changed, + ); + + return (): VNode => + h( + BasePersonalAgentDetails, + { + agent: agent.data.value, + className: props.className, + error: + toManagementErrorMessage(t, agent.error.value, 'user.agents.details.error') ?? + toManagementErrorMessage( + t, + update.error.value ?? deletion.error.value ?? suspension.error.value, + 'user.agents.action.error', + ), + isChangingSuspension: suspension.isLoading.value, + isDeleting: deletion.isLoading.value, + isLoading: agent.isLoading.value, + isUpdating: update.isLoading.value, + onDelete: props.deletable ? (): void => void deletion.mutate(undefined) : undefined, + onSuspend: props.suspendable ? (): void => void suspension.mutate('suspend') : undefined, + onUnsuspend: props.suspendable ? (): void => void suspension.mutate('unsuspend') : undefined, + onUpdate: props.editable ? (changes: UpdateMeAgentRequest): void => void update.mutate(changes) : undefined, + preferences: props.preferences, + }, + {...slots}, + ); + }, +}); + +export default PersonalAgentDetails; diff --git a/packages/vue/src/components/account/personal-agent-list/BasePersonalAgentList.ts b/packages/vue/src/components/account/personal-agent-list/BasePersonalAgentList.ts new file mode 100644 index 00000000..5faa4b4e --- /dev/null +++ b/packages/vue/src/components/account/personal-agent-list/BasePersonalAgentList.ts @@ -0,0 +1,190 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {type BasicAgent, type Preferences, getAgentName} from '@thunderid/browser'; +import {type Component, type PropType, type SetupContext, type VNode, type VNodeChild, defineComponent, h} from 'vue'; +import AccessStatusBadge from '../../management/shared/AccessStatusBadge'; +import AdminSection from '../../management/shared/AdminSection'; +import ConfirmButton from '../../management/shared/ConfirmButton'; +import {type AdminListRenderProps, adminListProps} from '../../management/shared/createAdminList'; +import useAdminTranslation, {type AdminTranslate} from '../../management/shared/useAdminTranslation'; +import Alert from '../../primitives/Alert/Alert'; +import DataTable, {type DataTableColumn} from '../../primitives/DataTable/DataTable'; + +/** + * What `BasePersonalAgentList` hands its default scoped slot. `agents` and `rows` are the same array. + */ +export type BasePersonalAgentListRenderProps = AdminListRenderProps & { + /** Why the last suspend-all request failed, already translated. */ + actionError: string | null; + agents: BasicAgent[]; + isSuspendingAll: boolean; + /** + * Suspends every personal agent of the signed-in user. Undefined when not allowed, or when there are none. + * The built-in UI asks for confirmation first, and a custom render must too. + */ + onSuspendAll?: () => void; + /** How many agents the last suspend-all request suspended, until the list is shown again. */ + suspendedCount: number | null; +}; + +type BasePersonalAgentListProps = Readonly<{ + actionError: string | null; + agents: BasicAgent[]; + className: string; + description: string | undefined; + error: string | null; + isLoading: boolean; + isSuspendingAll: boolean; + limit: number; + offset: number; + onPageChange: ((offset: number) => void) | undefined; + onSelect: ((agent: BasicAgent) => void) | undefined; + onSuspendAll: (() => void) | undefined; + preferences: Preferences | undefined; + selectedAgentId: string | undefined; + suspendedCount: number | null; + title: string | undefined; + totalResults: number | undefined; +}>; + +/** + * Lists the signed-in user's personal agents with their client and status. Holds no data of its own: pass the + * page of agents and handle selection, pagination and suspending them all. + * + * Props: `agents` (required), `selectedAgentId`, `isLoading`, `error`, `limit`, `offset`, `totalResults`, + * `onPageChange`, `onSelect` (`@select`), `onSuspendAll` (`@suspend-all`), `isSuspendingAll`, `suspendedCount`, + * `actionError`, `title`, `description`, `className`, `preferences`. Slots: `actions`, rendered next to the title; + * `default`, a scoped slot that replaces the table with custom UI and receives + * {@link BasePersonalAgentListRenderProps}. + */ +const BasePersonalAgentList: Component = defineComponent({ + name: 'BasePersonalAgentList', + props: { + ...adminListProps, + /** Why the last suspend-all request failed, already translated. */ + actionError: {default: null, type: String as PropType}, + /** The page of agents to show. */ + agents: {required: true, type: Array as PropType}, + isSuspendingAll: {default: false, type: Boolean}, + /** Called when an agent is chosen. Rows are selectable only when set. Also available as `@select`. */ + onSelect: {default: undefined, type: Function as PropType<(agent: BasicAgent) => void>}, + /** + * Suspends every personal agent of the signed-in user. The action is hidden when omitted. Also available as + * `@suspend-all`. + */ + onSuspendAll: {default: undefined, type: Function as PropType<() => void>}, + selectedAgentId: {default: undefined, type: String}, + /** How many agents the last suspend-all request suspended. */ + suspendedCount: {default: null, type: Number as PropType}, + }, + setup(props: BasePersonalAgentListProps, {slots}: SetupContext): () => VNode { + const t: AdminTranslate = useAdminTranslation(() => props.preferences); + + return (): VNode => { + const {agents} = props; + const canSuspendAll: boolean = Boolean(props.onSuspendAll) && agents.length > 0; + const title: string = props.title ?? t('user.agents.title'); + const columns: DataTableColumn[] = [ + { + header: t('user.agents.list.columns.name'), + id: 'name', + render: (agent: BasicAgent): VNodeChild => getAgentName(agent), + }, + { + header: t('user.agents.details.client_id'), + id: 'clientId', + render: (agent: BasicAgent): VNodeChild => h('code', {}, agent.clientId ?? ''), + }, + { + header: t('user.agents.list.columns.status'), + id: 'status', + render: (agent: BasicAgent): VNodeChild => h(AccessStatusBadge, {status: agent.status?.value, t}), + }, + ]; + + if (slots['default']) { + const renderProps: BasePersonalAgentListRenderProps = { + actionError: props.actionError, + agents, + columns, + error: props.error, + isLoading: props.isLoading, + isSuspendingAll: props.isSuspendingAll, + limit: props.limit, + offset: props.offset, + onPageChange: props.onPageChange, + onSelect: props.onSelect, + onSuspendAll: canSuspendAll ? props.onSuspendAll : undefined, + rows: agents, + selectedRowId: props.selectedAgentId, + suspendedCount: props.suspendedCount, + totalResults: props.totalResults ?? agents.length, + }; + + return h('div', {class: props.className}, slots['default'](renderProps)); + } + + return h( + AdminSection, + { + block: 'personal-agent-list', + className: props.className, + description: props.description ?? t('user.agents.description'), + title, + }, + { + actions: (): (VNode | VNode[] | null | undefined)[] => [ + slots['actions']?.(), + canSuspendAll + ? h( + ConfirmButton, + { + confirmText: t('user.agents.suspend_all.confirm'), + isLoading: props.isSuspendingAll, + onConfirm: props.onSuspendAll, + t, + }, + {default: (): string => t('user.agents.suspend_all.action')}, + ) + : null, + ], + default: (): (VNode | null)[] => [ + props.actionError + ? h(Alert, {role: 'alert', severity: 'error'}, {default: (): string[] => [props.actionError!]}) + : null, + props.suspendedCount !== null + ? h( + Alert, + {role: 'status', severity: 'success'}, + {default: (): string[] => [t('user.agents.suspend_all.done', {count: props.suspendedCount!})]}, + ) + : null, + h(DataTable, { + caption: props.title?.length ? props.title : t('user.agents.title'), + columns, + emptyText: t('user.agents.list.empty'), + error: props.error, + getRowId: (agent: BasicAgent): string => agent.id, + isLoading: props.isLoading, + onRowClick: props.onSelect, + pagination: props.onPageChange + ? { + limit: props.limit, + offset: props.offset, + onChange: props.onPageChange, + total: props.totalResults ?? agents.length, + } + : undefined, + rows: agents, + selectedRowId: props.selectedAgentId, + t, + }), + ], + }, + ); + }; + }, +}); + +export default BasePersonalAgentList; diff --git a/packages/vue/src/components/account/personal-agent-list/PersonalAgentList.ts b/packages/vue/src/components/account/personal-agent-list/PersonalAgentList.ts new file mode 100644 index 00000000..83cafff3 --- /dev/null +++ b/packages/vue/src/components/account/personal-agent-list/PersonalAgentList.ts @@ -0,0 +1,120 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + type AgentListResponse, + AgentQueryKeys, + PERSONAL_AGENT_KIND, + type Preferences, + type SuspendAllMeAgentsResponse, + resolveResourceEndpoint, + toManagementErrorMessage, +} from '@thunderid/browser'; +import {type Component, type PropType, type Ref, type SetupContext, type VNode, defineComponent, h, ref} from 'vue'; +import BasePersonalAgentList from './BasePersonalAgentList'; +import getMeAgents from '../../../api/account/getMeAgents'; +import suspendAllMeAgents from '../../../api/account/suspendAllMeAgents'; +import useResourceMutation, {type ResourceMutationResult} from '../../../composables/management/useResourceMutation'; +import useResourceQuery, {type ResourceQueryResult} from '../../../composables/management/useResourceQuery'; +import useThunderID from '../../../composables/useThunderID'; +import type {ThunderIDContext} from '../../../models/contexts'; +import useAdminTranslation, {type AdminTranslate} from '../../management/shared/useAdminTranslation'; + +type PersonalAgentListProps = Readonly<{ + className: string; + description: string | undefined; + limit: number; + onSelect: ((agent: unknown) => void) | undefined; + preferences: Preferences | undefined; + selectedAgentId: string | undefined; + suspendable: boolean; + title: string | undefined; +}>; + +/** + * Lists the signed-in user's personal agents, a page at a time, and, when the app allows it, lets the user suspend + * them all. + * + * Props: `suspendable` (default `false`), `limit`, `selectedAgentId`, `onSelect` (`@select`), `title`, + * `description`, `className`, `preferences`. Slots: `actions`; `default`, a scoped slot that replaces the table with + * custom UI and receives `BasePersonalAgentListRenderProps`. + * + * @example + * ```vue + * + * ``` + */ +const PersonalAgentList: Component = defineComponent({ + name: 'PersonalAgentList', + props: { + /** Extra CSS class added to the root element. */ + className: {default: '', type: String}, + /** Text shown under the title. */ + description: {default: undefined, type: String}, + /** Page size. */ + limit: {default: 20, type: Number}, + /** Called when an agent is chosen. Rows are selectable only when set. Also available as `@select`. */ + onSelect: {default: undefined, type: Function as PropType<(agent: unknown) => void>}, + /** Component-level preferences, for example `i18n.bundles` overrides. */ + preferences: {default: undefined, type: Object as PropType}, + selectedAgentId: {default: undefined, type: String}, + /** Whether the user can suspend all their personal agents from this view. */ + suspendable: {default: false, type: Boolean}, + /** Heading of the list. Pass an empty string to hide it. */ + title: {default: undefined, type: String}, + }, + setup(props: PersonalAgentListProps, {slots}: SetupContext): () => VNode { + const t: AdminTranslate = useAdminTranslation(() => props.preferences); + const {baseUrl, endpoints, instanceId}: ThunderIDContext = useThunderID(); + const url: string | undefined = resolveResourceEndpoint('usersMeAgents', {endpoints}); + const offset: Ref = ref(0); + const suspendedCount: Ref = ref(null); + + // These are the user's own requests, so they go through the SDK's transport for this instance, like the other + // `users/me` operations, and never the management `http.fetcher` the composables would otherwise hand them. + const list: ResourceQueryResult = useResourceQuery( + () => [AgentQueryKeys.ME_AGENTS, {limit: props.limit, offset: offset.value}], + () => + getMeAgents({baseUrl, instanceId, kind: PERSONAL_AGENT_KIND, limit: props.limit, offset: offset.value, url}), + ); + const suspendAll: ResourceMutationResult = useResourceMutation( + () => suspendAllMeAgents({baseUrl, instanceId, url}), + () => [[AgentQueryKeys.ME_AGENT], [AgentQueryKeys.ME_AGENTS]], + { + onSuccess: (result: SuspendAllMeAgentsResponse): void => { + suspendedCount.value = result.suspendedCount; + }, + }, + ); + + return (): VNode => + h( + BasePersonalAgentList, + { + actionError: toManagementErrorMessage(t, suspendAll.error.value, 'user.agents.action.error'), + agents: list.data.value?.agents ?? [], + className: props.className, + description: props.description, + error: toManagementErrorMessage(t, list.error.value, 'user.agents.list.error'), + isLoading: list.isLoading.value, + isSuspendingAll: suspendAll.isLoading.value, + limit: props.limit, + offset: offset.value, + onPageChange: (next: number): void => { + offset.value = next; + suspendedCount.value = null; + }, + onSelect: props.onSelect, + onSuspendAll: props.suspendable ? (): void => void suspendAll.mutate(undefined) : undefined, + preferences: props.preferences, + selectedAgentId: props.selectedAgentId, + suspendedCount: suspendedCount.value, + title: props.title, + totalResults: list.data.value?.totalResults, + }, + {...slots}, + ); + }, +}); + +export default PersonalAgentList; diff --git a/packages/vue/src/components/management/AgentDetails/AgentDetails.ts b/packages/vue/src/components/management/AgentDetails/AgentDetails.ts index 8f5ef669..fe3a7a8e 100644 --- a/packages/vue/src/components/management/AgentDetails/AgentDetails.ts +++ b/packages/vue/src/components/management/AgentDetails/AgentDetails.ts @@ -83,6 +83,7 @@ const AgentDetails: Component = defineComponent({ {onSuccess: (): void => emit('deleted')}, ); const lifecycle: AccountLifecycleState = useAccountLifecycle({ + appliedBy: () => agent.data.value?.status?.details?.appliedBy, enabled: (): boolean => props.lifecycleActions, invalidatedKeys: () => [[AgentQueryKeys.AGENT, props.agentId], [AgentQueryKeys.AGENTS]], kind: 'agent', diff --git a/packages/vue/src/components/management/AgentDetails/BaseAgentDetails.ts b/packages/vue/src/components/management/AgentDetails/BaseAgentDetails.ts index bbc85465..083b5765 100644 --- a/packages/vue/src/components/management/AgentDetails/BaseAgentDetails.ts +++ b/packages/vue/src/components/management/AgentDetails/BaseAgentDetails.ts @@ -6,7 +6,9 @@ import { type Agent, type MembershipGroup, type Preferences, + type SuspensionAppliedBy, getAgentName, + isPersonalAgent, withVendorCSSClassPrefix, } from '@thunderid/browser'; import {type Component, type PropType, type SetupContext, type VNode, defineComponent, h} from 'vue'; @@ -157,6 +159,10 @@ const BaseAgentDetails: Component = defineComponent({ {label: t('admin.common.columns.organization_unit'), value: agent.ouHandle ?? agent.ouId}, ]; + if (isPersonalAgent(agent)) { + details.push({label: t('admin.agents.details.kind'), value: t('admin.agents.kind.personal')}); + } + if (agent.status) { details.push({ label: t('admin.common.columns.status'), @@ -164,6 +170,18 @@ const BaseAgentDetails: Component = defineComponent({ }); } + const suspendedBy: SuspensionAppliedBy[] = + agent.status?.value === 'SUSPENDED' ? (agent.status.details?.appliedBy ?? []) : []; + + if (suspendedBy.length > 0) { + details.push({ + label: t('admin.agents.details.suspension.title'), + value: suspendedBy + .map((party: SuspensionAppliedBy) => t(`admin.agents.details.suspension.${party}`)) + .join(', '), + }); + } + if (agent.clientId) { details.push({ label: t('admin.agents.list.columns.client_id'), diff --git a/packages/vue/src/components/management/AgentList/BaseAgentList.ts b/packages/vue/src/components/management/AgentList/BaseAgentList.ts index d93c6bf6..df8a64cd 100644 --- a/packages/vue/src/components/management/AgentList/BaseAgentList.ts +++ b/packages/vue/src/components/management/AgentList/BaseAgentList.ts @@ -1,11 +1,13 @@ // Copyright 2026 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {type BasicAgent, getAgentName} from '@thunderid/browser'; +import {type BasicAgent, getAgentName, isPersonalAgent, withVendorCSSClassPrefix} from '@thunderid/browser'; import {type Component, type VNodeChild, h} from 'vue'; import createAdminList from '../shared/createAdminList'; import type {AdminTranslate} from '../shared/useAdminTranslation'; +const cls = (element: string): string => withVendorCSSClassPrefix(`admin__${element}`); + /** * Lists agents with their type, client identifier and organization unit. Holds no data of its own: * pass the page of agents and handle selection and pagination. @@ -21,7 +23,13 @@ const BaseAgentList: Component = createAdminList({ { header: t('admin.agents.list.columns.name'), id: 'name', - render: (agent: BasicAgent): VNodeChild => getAgentName(agent), + render: (agent: BasicAgent): VNodeChild => + isPersonalAgent(agent) + ? h('span', {class: cls('row')}, [ + getAgentName(agent), + h('span', {class: cls('chip')}, t('admin.agents.kind.personal')), + ]) + : getAgentName(agent), }, {header: t('admin.agents.list.columns.type'), id: 'type', render: (agent: BasicAgent): VNodeChild => agent.type}, { diff --git a/packages/vue/src/composables/management/useAccountLifecycle.ts b/packages/vue/src/composables/management/useAccountLifecycle.ts index f4e74a4f..8f8b1d09 100644 --- a/packages/vue/src/composables/management/useAccountLifecycle.ts +++ b/packages/vue/src/composables/management/useAccountLifecycle.ts @@ -8,6 +8,7 @@ import { type AccountLifecycleResult, type AccountLifecycleSubjectKind, type ResourceQueryKey, + type SuspensionAppliedBy, getAccountLifecycleActions, resolveAdministrationFlows, runAccountLifecycleAction, @@ -24,6 +25,10 @@ interface AccountLifecycleVariables { } export interface AccountLifecycleOptions { + /** + * Who holds a suspension, from the read's `status.details.appliedBy`. The organization lifts only its own. + */ + appliedBy?: () => SuspensionAppliedBy[] | undefined; /** * Whether to offer the actions at all. The configured flows are read only when it is on. */ @@ -77,6 +82,7 @@ export interface AccountLifecycleState { * ``` */ const useAccountLifecycle = ({ + appliedBy, enabled, invalidatedKeys, kind, @@ -97,7 +103,7 @@ const useAccountLifecycle = ({ return { actions: computed((): AccountLifecycleAction[] => - enabled() && flows.data.value ? getAccountLifecycleActions(kind, status(), flows.data.value) : [], + enabled() && flows.data.value ? getAccountLifecycleActions(kind, status(), flows.data.value, appliedBy?.()) : [], ), error: computed((): Error | null => execution.error.value), isRunning: computed((): boolean => execution.isLoading.value), diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index 3e2e4143..23968d88 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -38,6 +38,10 @@ export {default as useFetchUserTypes} from './composables/management/useFetchUse export {default as useManagementEndpoint} from './composables/management/useManagementEndpoint'; export type {ManagementEndpoint, ManagementEndpointKey} from './composables/management/useManagementEndpoint'; export {default as useManagementRequestConfig} from './composables/management/useManagementRequestConfig'; +export {default as useResourceQuery} from './composables/management/useResourceQuery'; +export type {ResourceQueryOptions, ResourceQueryResult} from './composables/management/useResourceQuery'; +export {default as useResourceMutation} from './composables/management/useResourceMutation'; +export type {ResourceMutationOptions, ResourceMutationResult} from './composables/management/useResourceMutation'; export {default as useGrantedPermissions} from './composables/management/useGrantedPermissions'; export type {GrantedPermissions} from './composables/management/useGrantedPermissions'; export {createResourceInvalidator} from '@thunderid/browser'; @@ -170,6 +174,12 @@ export {default as BaseChangeCredential} from './components/account/change-crede export type {ChangePasswordValues} from './components/account/change-credential/BaseChangeCredential'; export {default as OrganizationUnitSwitcher} from './components/account/organization-unit-switcher/OrganizationUnitSwitcher'; export {default as BaseOrganizationUnitSwitcher} from './components/account/organization-unit-switcher/BaseOrganizationUnitSwitcher'; +export {default as PersonalAgentList} from './components/account/personal-agent-list/PersonalAgentList'; +export {default as BasePersonalAgentList} from './components/account/personal-agent-list/BasePersonalAgentList'; +export type {BasePersonalAgentListRenderProps} from './components/account/personal-agent-list/BasePersonalAgentList'; +export {default as PersonalAgentDetails} from './components/account/personal-agent-details/PersonalAgentDetails'; +export {default as BasePersonalAgentDetails} from './components/account/personal-agent-details/BasePersonalAgentDetails'; +export type {BasePersonalAgentDetailsRenderProps} from './components/account/personal-agent-details/BasePersonalAgentDetails'; export type { BaseOrganizationUnitSwitcherProps, OrganizationUnitSwitcherRenderProps, @@ -348,6 +358,20 @@ export {default as executeEmbeddedSelfFlow} from './api/auth/executeEmbeddedSelf export type {ExecuteEmbeddedSelfFlowConfig} from './api/auth/executeEmbeddedSelfFlow'; export {default as getAccessibleOrganizationUnits} from './api/account/getAccessibleOrganizationUnits'; export type {GetAccessibleOrganizationUnitsConfig} from './api/account/getAccessibleOrganizationUnits'; +export {default as getMeAgents} from './api/account/getMeAgents'; +export type {GetMeAgentsConfig} from './api/account/getMeAgents'; +export {default as getMeAgent} from './api/account/getMeAgent'; +export type {GetMeAgentConfig} from './api/account/getMeAgent'; +export {default as updateMeAgent} from './api/account/updateMeAgent'; +export type {UpdateMeAgentConfig} from './api/account/updateMeAgent'; +export {default as deleteMeAgent} from './api/account/deleteMeAgent'; +export type {DeleteMeAgentConfig} from './api/account/deleteMeAgent'; +export {default as suspendMeAgent} from './api/account/suspendMeAgent'; +export type {SuspendMeAgentConfig} from './api/account/suspendMeAgent'; +export {default as unsuspendMeAgent} from './api/account/unsuspendMeAgent'; +export type {UnsuspendMeAgentConfig} from './api/account/unsuspendMeAgent'; +export {default as suspendAllMeAgents} from './api/account/suspendAllMeAgents'; +export type {SuspendAllMeAgentsConfig} from './api/account/suspendAllMeAgents'; export { OrganizationUnitSwitchErrorCodes, type AccessibleOrganizationUnit, @@ -507,6 +531,19 @@ export { getAccountLifecycleActions, getAgentName, getAgentType, + getMeAgentSuspensionAction, + getPersonalAgentOAuthConfig, + isPersonalAgent, + isPersonalAgentFormValid, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, + PERSONAL_AGENT_GRANT_TYPES, + PERSONAL_AGENT_KIND, + type AgentKind, + type PersonalAgentFormValues, + type SuspendAllMeAgentsResponse, + type SuspensionAppliedBy, + type UpdateMeAgentRequest, getUserType, getUserTypes, getUserUsages, diff --git a/playgrounds/react/src/pages/capabilities.ts b/playgrounds/react/src/pages/capabilities.ts index 96912123..5463bb53 100644 --- a/playgrounds/react/src/pages/capabilities.ts +++ b/playgrounds/react/src/pages/capabilities.ts @@ -12,6 +12,7 @@ import { getAgentTypes, getGroup, getGroupMembers, + getMeAgents, getGroups, getRole, getRoleAssignments, @@ -20,6 +21,7 @@ import { getUserGroups, getUserTypes, hasPermission, + PERSONAL_AGENT_KIND, resolveResourceEndpoint, type SessionData, } from '@thunderid/browser'; @@ -516,6 +518,33 @@ export const CAPABILITIES: Capability[] = [ }, section: 'User', }, + { + api: 'getMeAgents() · · ', + id: 'personal-agents', + name: 'Personal agents', + run: async (getContext: () => CapabilityContext) => { + const gate: CapabilityResult | null = requireSignedIn(getContext()); + + if (gate) return gate; + + const {sdk} = getContext(); + const list = await track('getMeAgents', () => + getMeAgents({ + baseUrl: sdk.baseUrl, + fetcher: createTokenFetcher(sdk.getAccessToken), + kind: PERSONAL_AGENT_KIND, + limit: 5, + url: resolveResourceEndpoint('usersMeAgents', {endpoints: sdk.endpoints}), + }), + ); + const suspended: number = list.agents.filter((agent) => agent.status?.value === 'SUSPENDED').length; + + return pass( + `${plural(list.totalResults, 'personal agent')}; ${suspended} suspended on this page. Manage them in Components > PersonalAgentList and PersonalAgentDetails (live)`, + ); + }, + section: 'User', + }, { api: ' · resolveResourceEndpoint()', id: 'endpoints', diff --git a/playgrounds/react/src/pages/explorer/CustomRenderWidgets.tsx b/playgrounds/react/src/pages/explorer/CustomRenderWidgets.tsx index 3c0cfb4a..789e8c2d 100644 --- a/playgrounds/react/src/pages/explorer/CustomRenderWidgets.tsx +++ b/playgrounds/react/src/pages/explorer/CustomRenderWidgets.tsx @@ -326,7 +326,7 @@ export const AgentForm = (form: BaseAgentCreateRenderProps): ReactElement => ( ); -const ChipRow = ({ +export const ChipRow = ({ items, color = undefined, }: { @@ -341,7 +341,8 @@ const ChipRow = ({ ); -const DetailsCard = ({ +export const DetailsCard = ({ + actions = undefined, children, isDeleting, isLoading, @@ -349,11 +350,12 @@ const DetailsCard = ({ subheader = undefined, title = undefined, }: { + actions?: ReactNode; children: ReactNode; isDeleting: boolean; isLoading: boolean; onDelete?: () => void; - subheader?: string; + subheader?: ReactNode; title?: string; }): ReactElement => ( @@ -365,11 +367,14 @@ const DetailsCard = ({ {children} - {onDelete && ( + {(actions !== undefined || onDelete !== undefined) && ( - + {actions} + {onDelete && ( + + )} )} diff --git a/playgrounds/react/src/pages/explorer/PersonalAgentStoryWidgets.tsx b/playgrounds/react/src/pages/explorer/PersonalAgentStoryWidgets.tsx new file mode 100644 index 00000000..68d461e6 --- /dev/null +++ b/playgrounds/react/src/pages/explorer/PersonalAgentStoryWidgets.tsx @@ -0,0 +1,359 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import MuiAlert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import List from '@mui/material/List'; +import ListItemButton from '@mui/material/ListItemButton'; +import ListItemText from '@mui/material/ListItemText'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; +import { + type Agent, + type BasePersonalAgentDetailsRenderProps, + type BasePersonalAgentListRenderProps, + type BasicAgent, + BasePersonalAgentDetails, + BasePersonalAgentList, + getAgentName, + isPersonalAgentFormValid, + type PersonalAgentFormValues, + toPersonalAgentFormValues, + toUpdateMeAgentRequest, + type UpdateMeAgentRequest, +} from '@thunderid/react'; +import {ChangeEvent, ReactElement, useState} from 'react'; +import {ChipRow, DetailsCard, Mui} from './CustomRenderWidgets'; +import {bool, str} from './storyHelpers'; +import type {Action, Args} from './types'; + +const oauth = (grantTypes: string[], redirectUris: string[]): Agent['inboundAuthConfig'] => [ + { + config: {grantTypes, redirectUris, responseTypes: grantTypes.includes('authorization_code') ? ['code'] : []}, + type: 'oauth2', + }, +]; + +const SAMPLE_PERSONAL_AGENTS: Agent[] = [ + { + attributes: {name: 'Spending assistant', software: 'Budget Buddy 2.1'}, + clientId: 'pa_7f3e9c2a', + description: 'Answers questions about my spending', + id: 'pa-1', + inboundAuthConfig: oauth(['authorization_code', 'refresh_token'], ['https://assistant.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', + }, + { + attributes: {name: 'Travel planner'}, + clientId: 'pa_41b0d7e5', + id: 'pa-2', + inboundAuthConfig: oauth(['authorization_code'], ['https://travel.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, + { + attributes: {name: 'Inbox triage'}, + clientId: 'pa_9c2d11aa', + id: 'pa-3', + inboundAuthConfig: oauth(['authorization_code'], ['https://inbox.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['organization'], reason: 'ADMINISTRATIVE_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, +]; + +const suspendedByOwner = (agent: Agent): Agent['status'] => { + const others: ('cascade' | 'organization' | 'owner')[] = (agent.status?.details?.appliedBy ?? []).filter( + (holder: string) => holder !== 'owner', + ); + + return {details: {appliedBy: [...others, 'owner']}, value: 'SUSPENDED'}; +}; + +const liftedByOwner = (agent: Agent): Agent['status'] => { + const others: ('cascade' | 'organization' | 'owner')[] = (agent.status?.details?.appliedBy ?? []).filter( + (holder: string) => holder !== 'owner', + ); + + return others.length ? {details: {appliedBy: others}, value: 'SUSPENDED'} : {value: 'ACTIVE'}; +}; + +/** + * The personal agent list drawn with MUI through the children render function. + */ +export const MuiPersonalAgentList = ({ + agents, + error, + onSelect, + onSuspendAll, + suspendedCount, +}: BasePersonalAgentListRenderProps): ReactElement => ( + + + {error && {error}} + {suspendedCount !== null && {`Agents suspended: ${suspendedCount}`}} + {onSuspendAll && ( + + )} + + {agents.map((agent: BasicAgent) => ( + onSelect?.(agent)}> + + + ))} + + + +); + +/** + * The personal agent's editable fields drawn with MUI, saved through `onUpdate`. + */ +const MuiPersonalAgentForm = ({ + agent, + isUpdating, + onCancel, + onSave, +}: { + agent: Agent; + isUpdating: boolean; + onCancel: () => void; + onSave: (changes: UpdateMeAgentRequest) => void; +}): ReactElement => { + const [values, setValues] = useState(() => toPersonalAgentFormValues(agent)); + const set = + (field: 'description' | 'name' | 'redirectUris') => + (event: ChangeEvent): void => + setValues((current: PersonalAgentFormValues) => ({...current, [field]: event.target.value})); + + return ( + + + + + + + + + + ); +}; + +/** + * The personal agent details drawn as an MUI card, like the admin agent details' custom render. + */ +export const MuiPersonalAgentDetails = ({ + agent, + error, + isChangingSuspension, + isDeleting, + isLoading, + isUpdating, + oauth: oauthConfig, + onDelete, + onSuspend, + onUnsuspend, + onUpdate, +}: BasePersonalAgentDetailsRenderProps): ReactElement => { + const [isEditing, setIsEditing] = useState(false); + const suspended: boolean = agent?.status?.value === 'SUSPENDED'; + const canEdit = Boolean(onUpdate && agent && !isEditing); + + return ( + + + {agent.clientId} + + + ) + } + isLoading={isLoading} + isDeleting={isDeleting} + onDelete={isEditing ? undefined : onDelete} + actions={ + !isEditing && (canEdit || onSuspend || onUnsuspend) ? ( + <> + {canEdit && } + {onUnsuspend && ( + + )} + {onSuspend && ( + + )} + + ) : undefined + } + > + {error && {error}} + {agent && isEditing && onUpdate ? ( + setIsEditing(false)} + onSave={(changes: UpdateMeAgentRequest): void => { + onUpdate(changes); + setIsEditing(false); + }} + /> + ) : ( + <> + {agent?.description && {agent.description}} + Attributes + name !== 'name') + .map(([name, value]: [string, unknown]) => ({id: name, label: `${name}: ${String(value)}`}))} + /> + Grant types + ({id: grantType, label: grantType}))} + /> + Redirect URIs + ({id: uri, label: uri}))} /> + + )} + + + ); +}; + +/** + * The Base list with sample agents, suspended locally. + */ +export const SamplePersonalAgentList = ({args, action}: {action: Action; args: Args}): ReactElement => { + const [agents, setAgents] = useState(SAMPLE_PERSONAL_AGENTS); + const [selectedId, setSelectedId] = useState(undefined); + const [suspendedCount, setSuspendedCount] = useState(null); + + return ( + { + action('onSelect', agent.id); + setSelectedId(agent.id); + }} + onSuspendAll={ + bool(args, 'suspendable') + ? (): void => { + const count: number = agents.filter( + (agent: Agent) => !agent.status?.details?.appliedBy?.includes('owner'), + ).length; + action('onSuspendAll', String(count)); + setAgents((current: Agent[]) => + current.map((agent: Agent) => ({...agent, status: suspendedByOwner(agent)})), + ); + setSuspendedCount(count); + } + : undefined + } + > + {str(args, 'source') === 'custom' + ? (props: BasePersonalAgentListRenderProps): ReactElement => + : undefined} + + ); +}; + +/** + * The Base details with a sample agent, edited and suspended locally. + */ +export const SamplePersonalAgentDetails = ({args, action}: {action: Action; args: Args}): ReactElement => { + const initial: Agent = + SAMPLE_PERSONAL_AGENTS.find((agent: Agent) => agent.id === str(args, 'sample')) ?? SAMPLE_PERSONAL_AGENTS[0]; + const [agent, setAgent] = useState(initial); + + return ( + { + action('onUpdate', JSON.stringify(changes)); + setAgent( + (current: Agent | undefined) => + current && { + ...current, + attributes: changes.attributes, + description: changes.description, + inboundAuthConfig: oauth(changes.grantTypes, changes.redirectUris), + }, + ); + } + : undefined + } + onDelete={ + bool(args, 'deletable') + ? (): void => { + action('onDelete', initial.id); + setAgent(undefined); + } + : undefined + } + onSuspend={ + bool(args, 'suspendable') + ? (): void => { + action('onSuspend', initial.id); + setAgent((current: Agent | undefined) => current && {...current, status: suspendedByOwner(current)}); + } + : undefined + } + onUnsuspend={ + bool(args, 'suspendable') + ? (): void => { + action('onUnsuspend', initial.id); + setAgent((current: Agent | undefined) => current && {...current, status: liftedByOwner(current)}); + } + : undefined + } + > + {str(args, 'source') === 'custom' + ? (props: BasePersonalAgentDetailsRenderProps): ReactElement => + : undefined} + + ); +}; diff --git a/playgrounds/react/src/pages/explorer/personalAgentStories.tsx b/playgrounds/react/src/pages/explorer/personalAgentStories.tsx new file mode 100644 index 00000000..11332fe6 --- /dev/null +++ b/playgrounds/react/src/pages/explorer/personalAgentStories.tsx @@ -0,0 +1,208 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {PersonalAgentDetails, PersonalAgentList} from '@thunderid/react'; +import {RequiresId} from './AdminStoryWidgets'; +import {SamplePersonalAgentDetails, SamplePersonalAgentList} from './PersonalAgentStoryWidgets'; +import {bool, jsx, str} from './storyHelpers'; +import {Narrow} from './StoryWidgets'; +import type {Action, Args, ComponentDef, PropControl} from './types'; + +const pick = (args: Args, ...keys: string[]): Args => + Object.fromEntries(Object.entries(args).filter(([key]: [string, unknown]) => keys.includes(key))); + +const SOURCE: PropControl = { + control: ['base', 'live', 'custom'], + description: + "base renders the Base component with sample agents; live manages the signed-in user's personal agents; custom draws the sample agents with MUI through the children render function.", + name: 'source', + type: "'base' | 'live' | 'custom' (playground only)", +}; + +const SUSPENDABLE: PropControl = { + control: 'bool', + description: 'Lets the user suspend agents and lift their own suspension.', + name: 'suspendable', + type: 'boolean', +}; + +export const PERSONAL_AGENT_LIST_STORY: ComponentDef = { + code: (args: Args) => { + if (str(args, 'source') === 'custom') { + return { + imports: ['PersonalAgentList', 'getAgentName'], + jsx: ` setAgentId(agent.id)}> + {({agents, onSelect, onSuspendAll, error}) => ( + + {error && {error}} + {onSuspendAll && } + {agents.map((agent) => ( + onSelect?.(agent)}> + + + ))} + + )} +`, + otherImports: ["import {Alert, Button, List, ListItemButton, ListItemText} from '@mui/material';"], + }; + } + + return str(args, 'source') === 'live' + ? { + imports: ['PersonalAgentList'], + jsx: jsx('PersonalAgentList', pick(args, 'suspendable', 'title'), { + extra: ['onSelect={(agent) => setAgentId(agent.id)}'], + }), + } + : { + imports: ['BasePersonalAgentList'], + jsx: jsx('BasePersonalAgentList', pick(args, 'title'), { + extra: [ + 'agents={agents}', + 'onSelect={select}', + ...(bool(args, 'suspendable') ? ['onSuspendAll={suspendAll}'] : []), + ], + }), + }; + }, + controls: [ + SOURCE, + SUSPENDABLE, + { + control: 'bool', + description: 'Shows the empty list (base only).', + name: 'empty', + type: 'boolean (playground only)', + }, + {control: 'text', description: 'Heading. Pass an empty string for the default.', name: 'title', type: 'string'}, + ], + defaults: {empty: false, source: 'base', suspendable: false, title: ''}, + group: 'User', + id: 'personalagentlist', + live: true, + name: 'PersonalAgentList', + render: (args: Args, action: Action) => ( + + {str(args, 'source') === 'live' ? ( + action('onSelect', agent.id)} + /> + ) : ( + + )} + + ), + stories: [ + {args: {suspendable: true}, id: 'base', name: 'Sample agents'}, + {args: {empty: true}, id: 'empty', name: 'No agents'}, + {args: {source: 'custom', suspendable: true}, id: 'custom', name: 'Custom rendering'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user'}, + ], +}; + +export const PERSONAL_AGENT_DETAILS_STORY: ComponentDef = { + code: (args: Args) => { + if (str(args, 'source') === 'custom') { + return { + imports: ['PersonalAgentDetails', 'getAgentName'], + jsx: ` + {({agent, onSuspend, onUnsuspend, error}) => ( + + {error && {error}} + {agent && {getAgentName(agent)}} + {onSuspend && } + {onUnsuspend && } + + )} +`, + otherImports: ["import {Alert, Button, Stack, Typography} from '@mui/material';"], + }; + } + + return str(args, 'source') === 'live' + ? { + imports: ['PersonalAgentDetails'], + jsx: jsx('PersonalAgentDetails', pick(args, 'agentId', 'editable', 'deletable', 'suspendable'), { + extra: ['onDeleted={backToList}'], + }), + } + : { + imports: ['BasePersonalAgentDetails'], + jsx: jsx('BasePersonalAgentDetails', pick(args, 'isLoading', 'error'), { + extra: [ + 'agent={agent}', + ...(bool(args, 'editable') ? ['onUpdate={update}'] : []), + ...(bool(args, 'deletable') ? ['onDelete={remove}'] : []), + ...(bool(args, 'suspendable') ? ['onSuspend={suspend}', 'onUnsuspend={unsuspend}'] : []), + ], + }), + }; + }, + controls: [ + SOURCE, + { + control: 'text', + description: 'Live only: the ID of one of your personal agents.', + name: 'agentId', + type: 'string', + }, + { + control: ['pa-1', 'pa-2', 'pa-3'], + description: 'Base only: pa-1 is active, pa-2 is suspended by its owner, pa-3 by the organization.', + name: 'sample', + type: 'string (playground only)', + }, + {control: 'bool', description: 'Lets the user edit the agent.', name: 'editable', type: 'boolean'}, + {control: 'bool', description: 'Lets the user delete the agent.', name: 'deletable', type: 'boolean'}, + SUSPENDABLE, + {control: 'bool', description: 'Base only: shows the loading state.', name: 'isLoading', type: 'boolean'}, + {control: 'text', description: 'Base only: an error message to show.', name: 'error', type: 'string'}, + ], + defaults: { + agentId: '', + deletable: false, + editable: false, + error: '', + isLoading: false, + sample: 'pa-1', + source: 'base', + suspendable: false, + }, + group: 'User', + id: 'personalagentdetails', + live: true, + name: 'PersonalAgentDetails', + render: (args: Args, action: Action) => { + if (str(args, 'source') === 'live') { + if (!str(args, 'agentId')) return ; + + return ( + + action('onDeleted')} + /> + + ); + } + + return ( + + + + ); + }, + stories: [ + {args: {deletable: true, editable: true, suspendable: true}, id: 'base', name: 'Sample agent'}, + {args: {sample: 'pa-2', suspendable: true}, id: 'owner-suspended', name: 'Suspended by its owner'}, + {args: {sample: 'pa-3', suspendable: true}, id: 'org-suspended', name: 'Suspended by the organization'}, + {args: {source: 'custom', suspendable: true}, id: 'custom', name: 'Custom rendering'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user (needs agentId)'}, + ], +}; diff --git a/playgrounds/react/src/pages/explorer/stories.tsx b/playgrounds/react/src/pages/explorer/stories.tsx index d8f920c4..e62cba87 100644 --- a/playgrounds/react/src/pages/explorer/stories.tsx +++ b/playgrounds/react/src/pages/explorer/stories.tsx @@ -48,6 +48,7 @@ import {ADMIN_COMPONENTS} from './adminStories'; import {SAMPLE_VERIFICATION_STEP, submitSampleVerification, withCustomStory} from './customRenderStories'; import {ORGANIZATION_UNIT_ADMIN_STORIES} from './organizationUnitAdminStories'; import {ORGANIZATION_UNIT_SWITCHER_STORY} from './organizationUnitStories'; +import {PERSONAL_AGENT_DETAILS_STORY, PERSONAL_AGENT_LIST_STORY} from './personalAgentStories'; import {PROJECT_STORIES} from './projectStories'; import {SHARING_STORIES} from './sharingStories'; import {bool, jsx, num, omit, SOURCE_CONTROL, str} from './storyHelpers'; @@ -1134,6 +1135,8 @@ export const COMPONENTS: ComponentDef[] = [ ], }, ORGANIZATION_UNIT_SWITCHER_STORY, + PERSONAL_AGENT_LIST_STORY, + PERSONAL_AGENT_DETAILS_STORY, ...ADMIN_COMPONENTS, ...PROJECT_STORIES, ...ORGANIZATION_UNIT_ADMIN_STORIES, diff --git a/playgrounds/vue/src/pages/explorer/personalAgentStories.ts b/playgrounds/vue/src/pages/explorer/personalAgentStories.ts new file mode 100644 index 00000000..8db7893d --- /dev/null +++ b/playgrounds/vue/src/pages/explorer/personalAgentStories.ts @@ -0,0 +1,357 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import type {Agent, AgentListResponse, BasicAgent, SuspensionAppliedBy, UpdateMeAgentRequest} from '@thunderid/browser'; +import { + BasePersonalAgentDetails, + BasePersonalAgentList, + PERSONAL_AGENT_KIND, + PersonalAgentDetails, + PersonalAgentList, + getMeAgents, + useThunderID, +} from '@thunderid/vue'; +import {Component, defineComponent, h, PropType, Ref, ref, VNode} from 'vue'; +import FirstResource from './FirstResource'; +import {bool, handler, omit, quoted, SOURCE_CONTROL, str, tpl} from './storyKit'; +import type {Action, Args, ComponentDef, PropControl, Snippet} from './types'; +import {narrow} from './widgets'; +import useApiQuery from '../../lib/useApiQuery'; + +const oauth = (grantTypes: string[], redirectUris: string[]): Agent['inboundAuthConfig'] => [ + { + config: {grantTypes, redirectUris, responseTypes: grantTypes.includes('authorization_code') ? ['code'] : []}, + type: 'oauth2', + }, +]; + +/** Sample personal agents for the Base stories. Nothing here reaches a server. */ +const SAMPLE_PERSONAL_AGENTS: Agent[] = [ + { + attributes: {name: 'Spending assistant', software: 'Budget Buddy 2.1'}, + clientId: 'pa_7f3e9c2a', + description: 'Answers questions about my spending', + id: 'pa-1', + inboundAuthConfig: oauth(['authorization_code', 'refresh_token'], ['https://assistant.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', + }, + { + attributes: {name: 'Travel planner'}, + clientId: 'pa_41b0d7e5', + id: 'pa-2', + inboundAuthConfig: oauth(['authorization_code'], ['https://travel.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, + { + attributes: {name: 'Inbox triage'}, + clientId: 'pa_9c2d11aa', + id: 'pa-3', + inboundAuthConfig: oauth(['authorization_code'], ['https://inbox.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['organization'], reason: 'ADMINISTRATIVE_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, +]; + +const othersThan = (agent: Agent): SuspensionAppliedBy[] => + (agent.status?.details?.appliedBy ?? []).filter((party: SuspensionAppliedBy) => party !== 'owner'); + +const suspendedByOwner = (agent: Agent): Agent['status'] => ({ + details: {appliedBy: [...othersThan(agent), 'owner']}, + value: 'SUSPENDED', +}); + +const liftedByOwner = (agent: Agent): Agent['status'] => + othersThan(agent).length ? {details: {appliedBy: othersThan(agent)}, value: 'SUSPENDED'} : {value: 'ACTIVE'}; + +/** The Base list with the sample agents, suspended locally. */ +const SamplePersonalAgentList: Component = defineComponent({ + name: 'SamplePersonalAgentList', + props: { + action: {required: true, type: Function as PropType}, + empty: {default: false, type: Boolean}, + suspendable: {default: false, type: Boolean}, + title: {default: undefined, type: String}, + }, + setup(props: {action: Action; empty: boolean; suspendable: boolean; title?: string}): () => VNode { + const agents: Ref = ref(SAMPLE_PERSONAL_AGENTS); + const selectedId: Ref = ref(undefined); + const suspendedCount: Ref = ref(null); + + return (): VNode => + h(BasePersonalAgentList, { + agents: props.empty ? [] : agents.value, + onSelect: (agent: BasicAgent): void => { + selectedId.value = agent.id; + props.action('select', quoted(agent.id)); + }, + onSuspendAll: props.suspendable + ? (): void => { + const count: number = agents.value.filter( + (agent: Agent) => !agent.status?.details?.appliedBy?.includes('owner'), + ).length; + agents.value = agents.value.map((agent: Agent) => ({...agent, status: suspendedByOwner(agent)})); + suspendedCount.value = count; + props.action('suspend-all', String(count)); + } + : undefined, + selectedAgentId: selectedId.value, + suspendedCount: suspendedCount.value, + title: props.title, + }); + }, +}); + +/** The Base details with one sample agent, edited and suspended locally. */ +const SamplePersonalAgentDetails: Component = defineComponent({ + name: 'SamplePersonalAgentDetails', + props: { + action: {required: true, type: Function as PropType}, + deletable: {default: false, type: Boolean}, + editable: {default: false, type: Boolean}, + error: {default: null, type: String as PropType}, + isLoading: {default: false, type: Boolean}, + sample: {default: 'pa-1', type: String}, + suspendable: {default: false, type: Boolean}, + }, + setup(props: { + action: Action; + deletable: boolean; + editable: boolean; + error: string | null; + isLoading: boolean; + sample: string; + suspendable: boolean; + }): () => VNode { + const initial: Agent = + SAMPLE_PERSONAL_AGENTS.find((agent: Agent) => agent.id === props.sample) ?? SAMPLE_PERSONAL_AGENTS[0]; + const agent: Ref = ref(initial); + const change = (next: (current: Agent) => Agent): void => { + agent.value = agent.value && next(agent.value); + }; + + return (): VNode => + h(BasePersonalAgentDetails, { + agent: agent.value, + error: props.error, + isLoading: props.isLoading, + onDelete: props.deletable + ? (): void => { + props.action('delete', quoted(initial.id)); + agent.value = undefined; + } + : undefined, + onSuspend: props.suspendable + ? (): void => { + props.action('suspend', quoted(initial.id)); + change((current: Agent) => ({...current, status: suspendedByOwner(current)})); + } + : undefined, + onUnsuspend: props.suspendable + ? (): void => { + props.action('unsuspend', quoted(initial.id)); + change((current: Agent) => ({...current, status: liftedByOwner(current)})); + } + : undefined, + onUpdate: props.editable + ? (changes: UpdateMeAgentRequest): void => { + props.action('update', JSON.stringify(changes)); + change((current: Agent) => ({ + ...current, + attributes: changes.attributes, + description: changes.description, + inboundAuthConfig: oauth(changes.grantTypes, changes.redirectUris), + })); + } + : undefined, + }); + }, +}); + +const isLive = (args: Args): boolean => str(args, 'source') === 'live'; + +const SUSPENDABLE: PropControl = { + control: 'bool', + description: 'Lets the user suspend agents and lift their own suspension.', + name: 'suspendable', + type: 'boolean', +}; + +export const PERSONAL_AGENT_COMPONENTS: ComponentDef[] = [ + { + code: (args: Args): Snippet => + isLive(args) + ? { + imports: ['BasicAgent', 'PersonalAgentList'], + script: ['const handleSelect = (agent: BasicAgent): void => {};'], + template: tpl('PersonalAgentList', omit(args, 'source', 'empty'), {extra: ['@select="handleSelect"']}), + } + : { + imports: ['BasePersonalAgentList', 'BasicAgent'], + script: [ + 'const agents = ref([]);', + 'const handleSelect = (agent: BasicAgent): void => {};', + ...(bool(args, 'suspendable') ? handler('handleSuspendAll') : []), + ], + template: tpl('BasePersonalAgentList', omit(args, 'source', 'empty', 'suspendable'), { + extra: [ + ':agents="agents"', + '@select="handleSelect"', + ...(bool(args, 'suspendable') ? ['@suspend-all="handleSuspendAll"'] : []), + ], + }), + vueImports: ['ref'], + }, + controls: [ + SOURCE_CONTROL, + SUSPENDABLE, + { + control: 'bool', + description: 'Base only: shows the empty list.', + name: 'empty', + type: 'boolean (playground only)', + }, + {control: 'text', description: 'Heading. Leave empty for the default.', name: 'title', type: 'string'}, + ], + defaults: {empty: false, source: 'base', suspendable: false, title: ''}, + group: 'User', + id: 'personalagentlist', + live: true, + name: 'PersonalAgentList', + render: (args: Args, action: Action): VNode => + narrow( + 640, + isLive(args) + ? h(PersonalAgentList, { + onSelect: (agent: BasicAgent) => action('select', quoted(agent.id)), + suspendable: bool(args, 'suspendable'), + title: str(args, 'title') || undefined, + }) + : h(SamplePersonalAgentList, { + action, + empty: bool(args, 'empty'), + suspendable: bool(args, 'suspendable'), + title: str(args, 'title') || undefined, + }), + ), + stories: [ + {args: {suspendable: true}, id: 'base', name: 'Sample agents'}, + {args: {empty: true}, id: 'empty', name: 'No agents'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user'}, + ], + }, + { + code: (args: Args): Snippet => + isLive(args) + ? { + imports: ['PersonalAgentDetails'], + script: handler('handleDeleted'), + template: tpl('PersonalAgentDetails', omit(args, 'source', 'sample', 'isLoading', 'error', 'agentId'), { + extra: [`agent-id="${str(args, 'agentId') || 'pa-1'}"`, '@deleted="handleDeleted"'], + }), + } + : { + imports: ['Agent', 'BasePersonalAgentDetails', 'UpdateMeAgentRequest'], + script: [ + 'const agent = ref();', + ...(bool(args, 'editable') ? ['const handleUpdate = (changes: UpdateMeAgentRequest): void => {};'] : []), + ...(bool(args, 'deletable') ? handler('handleDelete') : []), + ...(bool(args, 'suspendable') ? [...handler('handleSuspend'), ...handler('handleUnsuspend')] : []), + ], + template: tpl( + 'BasePersonalAgentDetails', + {}, + { + extra: [ + ':agent="agent"', + ...(bool(args, 'editable') ? ['@update="handleUpdate"'] : []), + ...(bool(args, 'deletable') ? ['@delete="handleDelete"'] : []), + ...(bool(args, 'suspendable') ? ['@suspend="handleSuspend"', '@unsuspend="handleUnsuspend"'] : []), + ], + }, + ), + vueImports: ['ref'], + }, + controls: [ + SOURCE_CONTROL, + { + control: 'text', + description: 'Live only: the ID of one of your personal agents. Empty uses your first one.', + name: 'agentId', + type: 'string', + }, + { + control: ['pa-1', 'pa-2', 'pa-3'], + description: 'Base only: pa-1 is active, pa-2 is suspended by its owner, pa-3 by the organization.', + name: 'sample', + type: 'string (playground only)', + }, + {control: 'bool', description: 'Lets the user edit the agent.', name: 'editable', type: 'boolean'}, + {control: 'bool', description: 'Lets the user delete the agent.', name: 'deletable', type: 'boolean'}, + SUSPENDABLE, + {control: 'bool', description: 'Base only: shows the loading state.', name: 'isLoading', type: 'boolean'}, + {control: 'text', description: 'Base only: an error message to show.', name: 'error', type: 'string'}, + ], + defaults: { + agentId: '', + deletable: false, + editable: false, + error: '', + isLoading: false, + sample: 'pa-1', + source: 'base', + suspendable: false, + }, + group: 'User', + id: 'personalagentdetails', + live: true, + name: 'PersonalAgentDetails', + render: (args: Args, action: Action): VNode => + narrow( + 640, + isLive(args) + ? h(FirstResource, { + explicit: str(args, 'agentId'), + noun: 'personal agent', + pick: (data: unknown): string | undefined => (data as AgentListResponse | undefined)?.agents?.[0]?.id, + query: () => { + const {baseUrl, instanceId} = useThunderID(); + + return useApiQuery(() => getMeAgents({baseUrl, instanceId, kind: PERSONAL_AGENT_KIND, limit: 1})); + }, + render: (agentId: string): VNode => + h(PersonalAgentDetails, { + agentId, + deletable: bool(args, 'deletable'), + editable: bool(args, 'editable'), + key: agentId, + onDeleted: () => action('deleted', quoted(agentId)), + suspendable: bool(args, 'suspendable'), + }), + }) + : h(SamplePersonalAgentDetails, { + action, + deletable: bool(args, 'deletable'), + editable: bool(args, 'editable'), + error: str(args, 'error') || null, + isLoading: bool(args, 'isLoading'), + key: str(args, 'sample'), + sample: str(args, 'sample'), + suspendable: bool(args, 'suspendable'), + }), + ), + stories: [ + {args: {deletable: true, editable: true, suspendable: true}, id: 'base', name: 'Sample agent'}, + {args: {sample: 'pa-2', suspendable: true}, id: 'owner-suspended', name: 'Suspended by its owner'}, + {args: {sample: 'pa-3', suspendable: true}, id: 'org-suspended', name: 'Suspended by the organization'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user (first agent)'}, + ], + }, +]; diff --git a/playgrounds/vue/src/pages/explorer/stories.ts b/playgrounds/vue/src/pages/explorer/stories.ts index c2c46c8a..5e98155f 100644 --- a/playgrounds/vue/src/pages/explorer/stories.ts +++ b/playgrounds/vue/src/pages/explorer/stories.ts @@ -52,6 +52,7 @@ import {ADMIN_COMPONENTS} from './adminStories'; import {CUSTOM_RENDER_COMPONENTS, SAMPLE_VERIFICATION_STEP, submitSampleVerification} from './customRenderStories'; import {ORGANIZATION_UNIT_ADMIN_STORIES, PROJECT_STORIES, SHARING_STORIES} from './managementAreaStories'; import {SampleOrganizationUnitSwitcher} from './organizationUnitSamples'; +import {PERSONAL_AGENT_COMPONENTS} from './personalAgentStories'; import {bool, CARD_VARIANT, handler, num, omit, quoted, SIZE, slot, SOURCE_CONTROL, str, tpl} from './storyKit'; import type {Action, Args, ComponentDef} from './types'; import {narrow, VModel} from './widgets'; @@ -1323,6 +1324,7 @@ export const COMPONENTS: ComponentDef[] = [ {args: {source: 'base'}, id: 'base', name: 'Base'}, ], }, + ...PERSONAL_AGENT_COMPONENTS, ...ADMIN_COMPONENTS, ...PROJECT_STORIES, ...ORGANIZATION_UNIT_ADMIN_STORIES, From 95b4e080ef12b6beabe4d38e2e520039a39a2705 Mon Sep 17 00:00:00 2001 From: sajitha-tj Date: Wed, 18 Nov 2026 10:09:04 +0530 Subject: [PATCH 2/2] Add personal agent self-service to the server-side SDKs Let a signed-in user manage their own personal agents in Next.js through server actions and in Nuxt through server routes, keeping the access token on the server and passing only the fields an owner may change. Refs thunder-id/thunderid#4468 Signed-off-by: sajitha-tj --- .../__tests__/loadMeAgentFromAction.test.ts | 22 ++ .../PersonalAgentDetails.tsx | 103 ++++++++ .../PersonalAgentList/PersonalAgentList.tsx | 89 +++++++ .../__tests__/PersonalAgents.test.ts | 178 ++++++++++++++ packages/nextjs/src/client/index.ts | 6 + .../src/client/loadMeAgentFromAction.ts | 30 +++ .../account/__tests__/meAgentActions.test.ts | 221 ++++++++++++++++++ .../actions/account/deleteMeAgentAction.ts | 21 ++ .../actions/account/getMeAgentAction.ts | 21 ++ .../actions/account/getMeAgentsAction.ts | 23 ++ .../actions/account/runMeAgentRequest.ts | 69 ++++++ .../account/suspendAllMeAgentsAction.ts | 16 ++ .../actions/account/suspendMeAgentAction.ts | 21 ++ .../actions/account/unsuspendMeAgentAction.ts | 21 ++ .../actions/account/updateMeAgentAction.ts | 26 +++ packages/node/src/index.ts | 1 + .../parseUpdateMeAgentRequest.test.ts | 37 +++ .../src/utils/parseUpdateMeAgentRequest.ts | 38 +++ packages/nuxt/src/module.ts | 44 +++- .../account/PersonalAgentDetails.ts | 107 +++++++++ .../components/account/PersonalAgentList.ts | 112 +++++++++ .../src/runtime/constants/NuxtAPIRoutes.ts | 7 + .../src/runtime/server/ThunderIDNuxtClient.ts | 18 ++ .../auth/user/agents/agent-suspend.post.ts | 19 ++ .../auth/user/agents/agent-unsuspend.post.ts | 19 ++ .../routes/auth/user/agents/agent.delete.ts | 19 ++ .../routes/auth/user/agents/agent.get.ts | 18 ++ .../routes/auth/user/agents/agent.put.ts | 32 +++ .../auth/user/agents/agents-suspend.post.ts | 19 ++ .../routes/auth/user/agents/agents.get.ts | 36 +++ .../src/runtime/server/utils/meAgentRoute.ts | 70 ++++++ .../src/runtime/utils/loadMeAgentFromRoute.ts | 32 +++ .../unit/load-me-agent-from-route.test.ts | 24 ++ .../nuxt/tests/unit/personal-agents.test.ts | 190 +++++++++++++++ .../tests/unit/user-agents-routes.test.ts | 171 ++++++++++++++ .../explorer/PersonalAgentStoryWidgets.tsx | 151 ++++++++++++ .../src/explorer/personalAgentStories.tsx | 169 ++++++++++++++ playgrounds/nextjs/src/explorer/stories.tsx | 3 + playgrounds/nuxt/lib/personalAgentSamples.ts | 164 +++++++++++++ playgrounds/nuxt/lib/personalAgentStories.ts | 165 +++++++++++++ playgrounds/nuxt/lib/stories.ts | 2 + 41 files changed, 2533 insertions(+), 1 deletion(-) create mode 100644 packages/nextjs/src/client/__tests__/loadMeAgentFromAction.test.ts create mode 100644 packages/nextjs/src/client/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx create mode 100644 packages/nextjs/src/client/components/account/PersonalAgentList/PersonalAgentList.tsx create mode 100644 packages/nextjs/src/client/components/account/PersonalAgentList/__tests__/PersonalAgents.test.ts create mode 100644 packages/nextjs/src/client/loadMeAgentFromAction.ts create mode 100644 packages/nextjs/src/server/actions/account/__tests__/meAgentActions.test.ts create mode 100644 packages/nextjs/src/server/actions/account/deleteMeAgentAction.ts create mode 100644 packages/nextjs/src/server/actions/account/getMeAgentAction.ts create mode 100644 packages/nextjs/src/server/actions/account/getMeAgentsAction.ts create mode 100644 packages/nextjs/src/server/actions/account/runMeAgentRequest.ts create mode 100644 packages/nextjs/src/server/actions/account/suspendAllMeAgentsAction.ts create mode 100644 packages/nextjs/src/server/actions/account/suspendMeAgentAction.ts create mode 100644 packages/nextjs/src/server/actions/account/unsuspendMeAgentAction.ts create mode 100644 packages/nextjs/src/server/actions/account/updateMeAgentAction.ts create mode 100644 packages/node/src/utils/__tests__/parseUpdateMeAgentRequest.test.ts create mode 100644 packages/node/src/utils/parseUpdateMeAgentRequest.ts create mode 100644 packages/nuxt/src/runtime/components/account/PersonalAgentDetails.ts create mode 100644 packages/nuxt/src/runtime/components/account/PersonalAgentList.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-suspend.post.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-unsuspend.post.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.delete.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.get.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.put.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agents-suspend.post.ts create mode 100644 packages/nuxt/src/runtime/server/routes/auth/user/agents/agents.get.ts create mode 100644 packages/nuxt/src/runtime/server/utils/meAgentRoute.ts create mode 100644 packages/nuxt/src/runtime/utils/loadMeAgentFromRoute.ts create mode 100644 packages/nuxt/tests/unit/load-me-agent-from-route.test.ts create mode 100644 packages/nuxt/tests/unit/personal-agents.test.ts create mode 100644 packages/nuxt/tests/unit/user-agents-routes.test.ts create mode 100644 playgrounds/nextjs/src/explorer/PersonalAgentStoryWidgets.tsx create mode 100644 playgrounds/nextjs/src/explorer/personalAgentStories.tsx create mode 100644 playgrounds/nuxt/lib/personalAgentSamples.ts create mode 100644 playgrounds/nuxt/lib/personalAgentStories.ts diff --git a/packages/nextjs/src/client/__tests__/loadMeAgentFromAction.test.ts b/packages/nextjs/src/client/__tests__/loadMeAgentFromAction.test.ts new file mode 100644 index 00000000..58ca5eff --- /dev/null +++ b/packages/nextjs/src/client/__tests__/loadMeAgentFromAction.test.ts @@ -0,0 +1,22 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDAPIError} from '@thunderid/node'; +import {describe, expect, it} from 'vitest'; +import loadMeAgentFromAction from '../loadMeAgentFromAction'; + +describe('loadMeAgentFromAction', () => { + it('returns the data of a successful action', async () => { + await expect(loadMeAgentFromAction(Promise.resolve({data: 3, success: true}))).resolves.toBe(3); + }); + + it('raises a refusal as an API error with its status and code', async () => { + await expect( + loadMeAgentFromAction(Promise.resolve({code: 'X-1', statusCode: 403, success: false})), + ).rejects.toMatchObject({code: 'X-1', statusCode: 403}); + await expect(loadMeAgentFromAction(Promise.resolve({success: false}))).rejects.toThrow(ThunderIDAPIError); + await expect(loadMeAgentFromAction(Promise.resolve({success: false}))).rejects.toMatchObject({ + code: 'PersonalAgents-ResponseError-001', + }); + }); +}); diff --git a/packages/nextjs/src/client/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx b/packages/nextjs/src/client/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx new file mode 100644 index 00000000..f19aed58 --- /dev/null +++ b/packages/nextjs/src/client/components/account/PersonalAgentDetails/PersonalAgentDetails.tsx @@ -0,0 +1,103 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use client'; + +import {Agent, AgentQueryKeys, ResourceQueryKey, UpdateMeAgentRequest, toManagementErrorMessage} from '@thunderid/node'; +import { + BasePersonalAgentDetails, + PersonalAgentDetailsProps as ReactPersonalAgentDetailsProps, + ResourceMutationResult, + ResourceQueryResult, + useResourceMutation, + useResourceQuery, + useTranslation, +} from '@thunderid/react'; +import {FC, ReactElement, useMemo} from 'react'; +import deleteMeAgentAction from '../../../../server/actions/account/deleteMeAgentAction'; +import getMeAgentAction from '../../../../server/actions/account/getMeAgentAction'; +import suspendMeAgentAction from '../../../../server/actions/account/suspendMeAgentAction'; +import unsuspendMeAgentAction from '../../../../server/actions/account/unsuspendMeAgentAction'; +import updateMeAgentAction from '../../../../server/actions/account/updateMeAgentAction'; +import useThunderID from '../../../contexts/ThunderID/useThunderID'; +import loadMeAgentFromAction from '../../../loadMeAgentFromAction'; + +/** + * Props for the PersonalAgentDetails component. Mirrors `@thunderid/react`'s `PersonalAgentDetailsProps`, so a + * consumer moving between the React and Next.js SDKs calls it the same way. + */ +export type PersonalAgentDetailsProps = ReactPersonalAgentDetailsProps; + +/** + * Shows one of the signed-in user's personal agents, and, when the app allows it, lets the user edit, delete and + * suspend it. + * + * This is the Next.js implementation: it renders `BasePersonalAgentDetails` from `@thunderid/react` and reads and + * changes the agent through server actions, so the access token stays on the server. + * + * @example + * ```tsx + * router.back()} /> + * ``` + */ +const PersonalAgentDetails: FC = ({ + agentId, + deletable = false, + editable = false, + onDeleted, + preferences, + suspendable = false, + ...rest +}: PersonalAgentDetailsProps): ReactElement => { + const {preferences: contextPreferences} = useThunderID(); + const resolvedPreferences = useMemo( + () => ({...contextPreferences, ...preferences}), + [contextPreferences, preferences], + ); + const {t} = useTranslation(resolvedPreferences?.i18n); + const changed = (): ResourceQueryKey[] => [[AgentQueryKeys.ME_AGENT, agentId], [AgentQueryKeys.ME_AGENTS]]; + + const agent: ResourceQueryResult = useResourceQuery( + [AgentQueryKeys.ME_AGENT, agentId], + () => loadMeAgentFromAction(getMeAgentAction(agentId)), + {enabled: Boolean(agentId)}, + ); + const update: ResourceMutationResult = useResourceMutation( + (payload: UpdateMeAgentRequest) => loadMeAgentFromAction(updateMeAgentAction(agentId, payload)), + changed, + ); + const deletion: ResourceMutationResult = useResourceMutation( + () => loadMeAgentFromAction(deleteMeAgentAction(agentId)), + () => [[AgentQueryKeys.ME_AGENTS]], + {onSuccess: () => onDeleted?.()}, + ); + const suspension: ResourceMutationResult = useResourceMutation( + (action: 'suspend' | 'unsuspend') => + loadMeAgentFromAction(action === 'suspend' ? suspendMeAgentAction(agentId) : unsuspendMeAgentAction(agentId)), + changed, + ); + + return ( + void update.mutate(changes) : undefined} + onDelete={deletable ? (): void => void deletion.mutate(undefined) : undefined} + onSuspend={suspendable ? (): void => void suspension.mutate('suspend') : undefined} + onUnsuspend={suspendable ? (): void => void suspension.mutate('unsuspend') : undefined} + preferences={resolvedPreferences} + {...rest} + /> + ); +}; + +PersonalAgentDetails.displayName = 'PersonalAgentDetails'; + +export default PersonalAgentDetails; diff --git a/packages/nextjs/src/client/components/account/PersonalAgentList/PersonalAgentList.tsx b/packages/nextjs/src/client/components/account/PersonalAgentList/PersonalAgentList.tsx new file mode 100644 index 00000000..0ffa9bea --- /dev/null +++ b/packages/nextjs/src/client/components/account/PersonalAgentList/PersonalAgentList.tsx @@ -0,0 +1,89 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use client'; + +import {AgentListResponse, AgentQueryKeys, SuspendAllMeAgentsResponse, toManagementErrorMessage} from '@thunderid/node'; +import { + BasePersonalAgentList, + PersonalAgentListProps as ReactPersonalAgentListProps, + ResourceMutationResult, + ResourceQueryResult, + useResourceMutation, + useResourceQuery, + useTranslation, +} from '@thunderid/react'; +import {FC, ReactElement, useMemo, useState} from 'react'; +import getMeAgentsAction from '../../../../server/actions/account/getMeAgentsAction'; +import suspendAllMeAgentsAction from '../../../../server/actions/account/suspendAllMeAgentsAction'; +import useThunderID from '../../../contexts/ThunderID/useThunderID'; +import loadMeAgentFromAction from '../../../loadMeAgentFromAction'; + +/** + * Props for the PersonalAgentList component. Mirrors `@thunderid/react`'s `PersonalAgentListProps`, so a consumer + * moving between the React and Next.js SDKs calls it the same way. + */ +export type PersonalAgentListProps = ReactPersonalAgentListProps; + +/** + * Lists the signed-in user's personal agents, a page at a time, and, when the app allows it, lets the user suspend + * them all. + * + * This is the Next.js implementation: it renders `BasePersonalAgentList` from `@thunderid/react` and reads and + * changes the agents through server actions, so the access token stays on the server. + * + * @example + * ```tsx + * router.push(`/account/agents/${agent.id}`)} /> + * ``` + */ +const PersonalAgentList: FC = ({ + limit = 20, + preferences, + suspendable = false, + ...rest +}: PersonalAgentListProps): ReactElement => { + const {preferences: contextPreferences} = useThunderID(); + const resolvedPreferences = useMemo( + () => ({...contextPreferences, ...preferences}), + [contextPreferences, preferences], + ); + const {t} = useTranslation(resolvedPreferences?.i18n); + const [offset, setOffset] = useState(0); + const [suspendedCount, setSuspendedCount] = useState(null); + + const list: ResourceQueryResult = useResourceQuery( + [AgentQueryKeys.ME_AGENTS, {limit, offset}], + () => loadMeAgentFromAction(getMeAgentsAction({limit, offset})), + ); + const suspendAll: ResourceMutationResult = useResourceMutation( + () => loadMeAgentFromAction(suspendAllMeAgentsAction()), + () => [[AgentQueryKeys.ME_AGENT], [AgentQueryKeys.ME_AGENTS]], + {onSuccess: (result: SuspendAllMeAgentsResponse) => setSuspendedCount(result.suspendedCount)}, + ); + + return ( + { + setOffset(next); + setSuspendedCount(null); + }} + actionError={toManagementErrorMessage(t, suspendAll.error, 'user.agents.action.error')} + isSuspendingAll={suspendAll.isLoading} + onSuspendAll={suspendable ? (): void => void suspendAll.mutate(undefined) : undefined} + suspendedCount={suspendedCount} + preferences={resolvedPreferences} + {...rest} + /> + ); +}; + +PersonalAgentList.displayName = 'PersonalAgentList'; + +export default PersonalAgentList; diff --git a/packages/nextjs/src/client/components/account/PersonalAgentList/__tests__/PersonalAgents.test.ts b/packages/nextjs/src/client/components/account/PersonalAgentList/__tests__/PersonalAgents.test.ts new file mode 100644 index 00000000..92a63269 --- /dev/null +++ b/packages/nextjs/src/client/components/account/PersonalAgentList/__tests__/PersonalAgents.test.ts @@ -0,0 +1,178 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {AgentQueryKeys, ThunderIDAPIError} from '@thunderid/node'; +import {ReactElement} from 'react'; +import {beforeEach, describe, expect, it, Mock, vi} from 'vitest'; + +const BasePersonalAgentList: () => null = () => null; +const BasePersonalAgentDetails: () => null = () => null; + +vi.mock('react', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + // Lets the components run outside a renderer. + useMemo: (factory: () => T): T => factory(), + useState: (initial: T): [T, Mock] => [initial, vi.fn()], +})); + +interface Resource { + data: unknown; + error: Error | null; + isLoading: boolean; +} + +const resources: {key: unknown; load: () => unknown; options?: {enabled?: boolean}}[] = []; +const mutations: { + invalidates: () => unknown; + onSuccess?: (data: unknown) => void; + run: (variables: unknown) => unknown; +}[] = []; +const mutate: Mock = vi.fn(); +let resource: Resource = {data: undefined, error: null, isLoading: false}; +let mutationError: Error | null = null; + +vi.mock('@thunderid/react', () => ({ + BasePersonalAgentDetails, + BasePersonalAgentList, + useResourceMutation: ( + run: (variables: unknown) => unknown, + invalidates: () => unknown, + options?: {onSuccess?: (data: unknown) => void}, + ) => { + mutations.push({invalidates, onSuccess: options?.onSuccess, run}); + + return {error: mutationError, isLoading: false, mutate}; + }, + useResourceQuery: (key: unknown, load: () => unknown, options?: {enabled?: boolean}) => { + resources.push({key, load, options}); + + return resource; + }, + useTranslation: () => ({t: (key: string): string => key}), +})); + +vi.mock('../../../../contexts/ThunderID/useThunderID', () => ({default: () => ({preferences: {}})})); + +const succeed = (): Promise<{data: undefined; success: true}> => Promise.resolve({data: undefined, success: true}); + +const actions: Record = { + deleteMeAgentAction: vi.fn(succeed), + getMeAgentAction: vi.fn(succeed), + getMeAgentsAction: vi.fn(succeed), + suspendAllMeAgentsAction: vi.fn(succeed), + suspendMeAgentAction: vi.fn(succeed), + unsuspendMeAgentAction: vi.fn(succeed), + updateMeAgentAction: vi.fn(succeed), +}; + +Object.keys(actions).forEach((name: string) => { + vi.doMock(`../../../../../server/actions/account/${name}`, () => ({ + default: (...args: unknown[]): unknown => actions[name](...args) as unknown, + })); +}); + +const {default: PersonalAgentList} = await import('../PersonalAgentList'); +const {default: PersonalAgentDetails} = await import('../../PersonalAgentDetails/PersonalAgentDetails'); + +type Props = Record unknown> & Record; + +beforeEach(() => { + resources.length = 0; + mutations.length = 0; + resource = {data: undefined, error: null, isLoading: false}; + mutationError = null; + vi.clearAllMocks(); + Object.values(actions).forEach((action: Mock) => action.mockImplementation(succeed)); +}); + +describe('PersonalAgentList (Next.js)', () => { + it('renders the React Base list with the page read through the server action', () => { + resource = {data: {agents: [{id: 'a-1'}], totalResults: 7}, error: null, isLoading: false}; + const element = PersonalAgentList({limit: 5}) as ReactElement; + + expect(element.type).toBe(BasePersonalAgentList); + expect(element.props['agents']).toEqual([{id: 'a-1'}]); + expect(element.props['totalResults']).toBe(7); + expect(element.props['onSuspendAll']).toBeUndefined(); + expect(resources[0].key).toEqual([AgentQueryKeys.ME_AGENTS, {limit: 5, offset: 0}]); + + resources[0].load(); + expect(actions['getMeAgentsAction']).toHaveBeenCalledWith({limit: 5, offset: 0}); + }); + + it('suspends every agent through the server action when the app allows it', () => { + const element = PersonalAgentList({suspendable: true}) as ReactElement; + + element.props['onSuspendAll'](); + expect(mutate).toHaveBeenCalled(); + mutations[0].run(undefined); + expect(actions['suspendAllMeAgentsAction']).toHaveBeenCalled(); + expect(mutations[0].invalidates()).toEqual([[AgentQueryKeys.ME_AGENT], [AgentQueryKeys.ME_AGENTS]]); + }); + + it('translates a refusal', () => { + resource = {data: undefined, error: new ThunderIDAPIError('x', 'y', 'nextjs', 403), isLoading: false}; + const element = PersonalAgentList({}) as ReactElement; + + expect(element.props['error']).toBe('admin.common.errors.forbidden'); + }); +}); + +describe('PersonalAgentDetails (Next.js)', () => { + it('renders the React Base details with the agent read through the server action, offering nothing by default', () => { + resource = {data: {id: 'a-1'}, error: null, isLoading: false}; + const element = PersonalAgentDetails({agentId: 'a-1'}) as ReactElement; + + expect(element.type).toBe(BasePersonalAgentDetails); + expect(element.props['agent']).toEqual({id: 'a-1'}); + ['onUpdate', 'onDelete', 'onSuspend', 'onUnsuspend'].forEach((name: string) => + expect(element.props[name]).toBeUndefined(), + ); + resources[0].load(); + expect(actions['getMeAgentAction']).toHaveBeenCalledWith('a-1'); + }); + + it('runs each change through its server action for this agent', () => { + const onDeleted: Mock = vi.fn(); + const element = PersonalAgentDetails({ + agentId: 'a-1', + deletable: true, + editable: true, + onDeleted, + suspendable: true, + }) as ReactElement; + const [update, deletion, suspension] = mutations; + + element.props['onUpdate']({attributes: {}, grantTypes: [], redirectUris: []}); + element.props['onDelete'](); + element.props['onSuspend'](); + element.props['onUnsuspend'](); + expect(mutate.mock.calls).toEqual([ + [{attributes: {}, grantTypes: [], redirectUris: []}], + [undefined], + ['suspend'], + ['unsuspend'], + ]); + + update.run({attributes: {}}); + deletion.run(undefined); + suspension.run('suspend'); + suspension.run('unsuspend'); + expect(actions['updateMeAgentAction']).toHaveBeenCalledWith('a-1', {attributes: {}}); + expect(actions['deleteMeAgentAction']).toHaveBeenCalledWith('a-1'); + expect(actions['suspendMeAgentAction']).toHaveBeenCalledWith('a-1'); + expect(actions['unsuspendMeAgentAction']).toHaveBeenCalledWith('a-1'); + expect(suspension.invalidates()).toEqual([[AgentQueryKeys.ME_AGENT, 'a-1'], [AgentQueryKeys.ME_AGENTS]]); + + deletion.onSuccess?.(undefined); + expect(onDeleted).toHaveBeenCalled(); + }); + + it('translates a failed change', () => { + resource = {data: {id: 'a-1'}, error: null, isLoading: false}; + mutationError = new ThunderIDAPIError('x', 'y', 'nextjs', 500); + const element = PersonalAgentDetails({agentId: 'a-1'}) as ReactElement; + + expect(element.props['error']).toBe('user.agents.action.error'); + }); +}); diff --git a/packages/nextjs/src/client/index.ts b/packages/nextjs/src/client/index.ts index 3345a5a6..3bf55f56 100644 --- a/packages/nextjs/src/client/index.ts +++ b/packages/nextjs/src/client/index.ts @@ -44,6 +44,12 @@ export type {ChangeCredentialProps} from './components/account/ChangeCredential/ export {default as OrganizationUnitSwitcher} from './components/account/OrganizationUnitSwitcher/OrganizationUnitSwitcher'; export type {OrganizationUnitSwitcherProps} from './components/account/OrganizationUnitSwitcher/OrganizationUnitSwitcher'; + +export {default as PersonalAgentList} from './components/account/PersonalAgentList/PersonalAgentList'; +export type {PersonalAgentListProps} from './components/account/PersonalAgentList/PersonalAgentList'; + +export {default as PersonalAgentDetails} from './components/account/PersonalAgentDetails/PersonalAgentDetails'; +export type {PersonalAgentDetailsProps} from './components/account/PersonalAgentDetails/PersonalAgentDetails'; export {default as VerifyAttribute} from './components/account/VerifyAttribute/VerifyAttribute'; export type {VerifyAttributeProps} from './components/account/VerifyAttribute/VerifyAttribute'; diff --git a/packages/nextjs/src/client/loadMeAgentFromAction.ts b/packages/nextjs/src/client/loadMeAgentFromAction.ts new file mode 100644 index 00000000..42214890 --- /dev/null +++ b/packages/nextjs/src/client/loadMeAgentFromAction.ts @@ -0,0 +1,30 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDAPIError} from '@thunderid/node'; +import type {MeAgentActionResult} from '../server/actions/account/runMeAgentRequest'; + +/** + * Waits for a personal agent server action and returns its data, or raises its refusal as a + * {@link ThunderIDAPIError} carrying the server's status and code. The Nuxt SDK raises the same error from its + * server routes, so a refusal reads the same in both. + * + * @param action - The pending server action. + * @returns The action's data. + */ +const loadMeAgentFromAction = async (action: Promise>): Promise => { + const result: MeAgentActionResult = await action; + + if (!result.success) { + throw new ThunderIDAPIError( + 'Personal agent request failed', + result.code ?? 'PersonalAgents-ResponseError-001', + 'nextjs', + result.statusCode, + ); + } + + return result.data; +}; + +export default loadMeAgentFromAction; diff --git a/packages/nextjs/src/server/actions/account/__tests__/meAgentActions.test.ts b/packages/nextjs/src/server/actions/account/__tests__/meAgentActions.test.ts new file mode 100644 index 00000000..1fde5b32 --- /dev/null +++ b/packages/nextjs/src/server/actions/account/__tests__/meAgentActions.test.ts @@ -0,0 +1,221 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {afterEach, beforeEach, describe, expect, it, Mock, vi} from 'vitest'; +import getClient from '../../../getClient'; +import getAccessToken from '../../getAccessToken'; +import deleteMeAgentAction from '../deleteMeAgentAction'; +import getMeAgentAction from '../getMeAgentAction'; +import getMeAgentsAction from '../getMeAgentsAction'; +import suspendAllMeAgentsAction from '../suspendAllMeAgentsAction'; +import suspendMeAgentAction from '../suspendMeAgentAction'; +import unsuspendMeAgentAction from '../unsuspendMeAgentAction'; +import updateMeAgentAction from '../updateMeAgentAction'; + +vi.mock('../../../getClient', () => ({default: vi.fn()})); +vi.mock('../../getAccessToken', () => ({default: vi.fn()})); + +const baseUrl = 'https://localhost:8090'; +const agent = {attributes: {name: 'Spending assistant'}, id: 'a-1', kind: 'personal-assistant', ouId: 'ou-1'}; +const payload = { + attributes: {name: 'Budget assistant'}, + description: 'Budgets', + grantTypes: ['authorization_code'], + redirectUris: ['https://assistant.example.com/callback'], +}; + +describe('personal agent server actions', () => { + const fetchMock: Mock = vi.fn(); + + const respond = (body: unknown, status = 200): void => { + fetchMock.mockResolvedValue({ + json: () => Promise.resolve(body), + ok: status >= 200 && status < 300, + status, + statusText: '', + text: () => Promise.resolve(body === undefined ? '' : JSON.stringify(body)), + }); + }; + + const sent = (): {body?: unknown; method?: string; token?: string; url: string} => { + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + + return { + body: typeof init.body === 'string' ? (JSON.parse(init.body) as unknown) : undefined, + method: init.method, + token: (init.headers as Record)['Authorization'], + url, + }; + }; + + const configure = (config: Record = {baseUrl}): void => { + (getClient as unknown as Mock).mockReturnValue({ + getConfiguration: vi.fn().mockResolvedValue(config), + initialize: vi.fn(), + isInitialized: true, + }); + }; + + beforeEach(() => { + vi.resetAllMocks(); + vi.stubGlobal('fetch', fetchMock); + configure(); + (getAccessToken as unknown as Mock).mockResolvedValue('session-token'); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it('refuses without a session and sends nothing', async () => { + (getAccessToken as unknown as Mock).mockResolvedValue(undefined); + + expect(await getMeAgentsAction()).toEqual({statusCode: 401, success: false}); + expect(await suspendAllMeAgentsAction()).toEqual({statusCode: 401, success: false}); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("lists the personal agents with the session's token, keeping it on the server", async () => { + respond({agents: [agent], count: 1, startIndex: 1, totalResults: 1}); + + const result = await getMeAgentsAction({limit: 5, offset: 10}); + + expect(sent()).toEqual({ + body: undefined, + method: 'GET', + token: 'Bearer session-token', + url: `${baseUrl}/users/me/agents?kind=personal-assistant&limit=5&offset=10`, + }); + expect(result).toMatchObject({data: {agents: [agent], totalResults: 1}, success: true}); + }); + + it('ignores paging values that are not counts', async () => { + respond({agents: [], count: 0, startIndex: 1, totalResults: 0}); + + await getMeAgentsAction({limit: -1, offset: 'x' as never}); + + expect(sent().url).toBe(`${baseUrl}/users/me/agents?kind=personal-assistant`); + }); + + it('sends requests to the usersMeAgents endpoint override', async () => { + configure({baseUrl, endpoints: {usersMeAgents: 'https://rs.example.com/users/me/agents'}}); + respond(agent); + + await getMeAgentAction('a-1'); + + expect(sent().url).toBe('https://rs.example.com/users/me/agents/a-1?include=display'); + }); + + it.each([ + [ + 'getMeAgentAction', + (): Promise => getMeAgentAction('a/1'), + 'GET', + `${baseUrl}/users/me/agents/a%2F1?include=display`, + ], + [ + 'deleteMeAgentAction', + (): Promise => deleteMeAgentAction('a-1'), + 'DELETE', + `${baseUrl}/users/me/agents/a-1`, + ], + [ + 'suspendMeAgentAction', + (): Promise => suspendMeAgentAction('a-1'), + 'POST', + `${baseUrl}/users/me/agents/a-1/suspend`, + ], + [ + 'unsuspendMeAgentAction', + (): Promise => unsuspendMeAgentAction('a-1'), + 'POST', + `${baseUrl}/users/me/agents/a-1/unsuspend`, + ], + ])( + '%s addresses the one agent it was given', + async (_name: string, run: () => Promise, method: string, url: string) => { + respond(undefined, 204); + + expect(await run()).toMatchObject({success: true}); + expect(sent()).toMatchObject({method, token: 'Bearer session-token', url}); + }, + ); + + it.each([ + ['getMeAgentAction', (): Promise => getMeAgentAction('' as string)], + ['deleteMeAgentAction', (): Promise => deleteMeAgentAction(42 as unknown as string)], + ['suspendMeAgentAction', (): Promise => suspendMeAgentAction(' ')], + ['unsuspendMeAgentAction', (): Promise => unsuspendMeAgentAction(undefined as unknown as string)], + ])( + '%s refuses an identifier that is not one, without a request', + async (_name: string, run: () => Promise) => { + expect(await run()).toEqual({statusCode: 400, success: false}); + expect(fetchMock).not.toHaveBeenCalled(); + }, + ); + + it('suspends every personal agent and returns how many', async () => { + respond({suspendedCount: 2}); + + expect(await suspendAllMeAgentsAction()).toEqual({data: {suspendedCount: 2}, success: true}); + expect(sent()).toMatchObject({method: 'POST', url: `${baseUrl}/users/me/agents/suspend`}); + }); + + it('sends only the fields an owner may change', async () => { + respond(agent); + + await updateMeAgentAction('a-1', {...payload, clientSecret: 'stolen', owner: {id: 'someone'}} as never); + + expect(sent()).toMatchObject({body: payload, method: 'PUT', url: `${baseUrl}/users/me/agents/a-1`}); + }); + + it.each([ + ['no attributes', {...payload, attributes: undefined}], + ['attributes that are a list', {...payload, attributes: ['name']}], + ['a description that is not text', {...payload, description: 7}], + ['grant types that are not text', {...payload, grantTypes: [1]}], + ['no redirect URIs', {...payload, redirectUris: undefined}], + ['no payload', null], + ])('refuses an update with %s, without a request', async (_name: string, body: unknown) => { + expect(await updateMeAgentAction('a-1', body as never)).toEqual({statusCode: 400, success: false}); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('returns the status and code of a rejection without the server message', async () => { + fetchMock.mockResolvedValue({ + ok: false, + status: 403, + statusText: 'Forbidden', + text: () => Promise.resolve('Delegated token'), + }); + + const result = await suspendMeAgentAction('a-1'); + + expect(result).toMatchObject({statusCode: 403, success: false}); + expect(JSON.stringify(result)).not.toContain('Delegated token'); + }); + + it('reports a failure that is not an API error without details', async () => { + (getClient as unknown as Mock).mockReturnValue({ + getConfiguration: vi.fn().mockRejectedValue(new Error('storage down')), + initialize: vi.fn(), + isInitialized: true, + }); + + expect(await getMeAgentsAction()).toEqual({success: false}); + }); + + it('initializes the client before the first request', async () => { + const initialize: Mock = vi.fn(); + (getClient as unknown as Mock).mockReturnValue({ + getConfiguration: vi.fn().mockResolvedValue({baseUrl}), + initialize, + isInitialized: false, + }); + respond(agent); + + await getMeAgentAction('a-1'); + + expect(initialize).toHaveBeenCalled(); + }); +}); diff --git a/packages/nextjs/src/server/actions/account/deleteMeAgentAction.ts b/packages/nextjs/src/server/actions/account/deleteMeAgentAction.ts new file mode 100644 index 00000000..b6a47ba7 --- /dev/null +++ b/packages/nextjs/src/server/actions/account/deleteMeAgentAction.ts @@ -0,0 +1,21 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {deleteMeAgent} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult, isAgentId} from './runMeAgentRequest'; + +/** + * Deletes one of the signed-in user's agents with the session's access token, which stays on the server. Only the agent's identifier is taken from the + * caller, and the server answers only for an agent the user owns. + */ +const deleteMeAgentAction = async (agentId: string): Promise> => { + if (!isAgentId(agentId)) { + return {statusCode: 400, success: false}; + } + + return runMeAgentRequest((config) => deleteMeAgent({...config, agentId})); +}; + +export default deleteMeAgentAction; diff --git a/packages/nextjs/src/server/actions/account/getMeAgentAction.ts b/packages/nextjs/src/server/actions/account/getMeAgentAction.ts new file mode 100644 index 00000000..fb24069d --- /dev/null +++ b/packages/nextjs/src/server/actions/account/getMeAgentAction.ts @@ -0,0 +1,21 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {Agent, getMeAgent} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult, isAgentId} from './runMeAgentRequest'; + +/** + * Reads one of the signed-in user's agents with the session's access token, which stays on the server. Only the agent's identifier is taken from the + * caller, and the server answers only for an agent the user owns. + */ +const getMeAgentAction = async (agentId: string): Promise> => { + if (!isAgentId(agentId)) { + return {statusCode: 400, success: false}; + } + + return runMeAgentRequest((config) => getMeAgent({...config, agentId})); +}; + +export default getMeAgentAction; diff --git a/packages/nextjs/src/server/actions/account/getMeAgentsAction.ts b/packages/nextjs/src/server/actions/account/getMeAgentsAction.ts new file mode 100644 index 00000000..2b2f34cb --- /dev/null +++ b/packages/nextjs/src/server/actions/account/getMeAgentsAction.ts @@ -0,0 +1,23 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {AgentListResponse, PERSONAL_AGENT_KIND, getMeAgents} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult} from './runMeAgentRequest'; + +const toCount = (value: unknown): number | undefined => + typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined; + +/** + * Lists a page of the signed-in user's personal agents (`/users/me/agents?kind=personal-assistant`) with the + * session's access token, which stays on the server. Only `limit` and `offset` are taken from the caller. + */ +const getMeAgentsAction = async ({limit, offset}: {limit?: number; offset?: number} = {}): Promise< + MeAgentActionResult +> => + runMeAgentRequest((config) => + getMeAgents({...config, kind: PERSONAL_AGENT_KIND, limit: toCount(limit), offset: toCount(offset)}), + ); + +export default getMeAgentsAction; diff --git a/packages/nextjs/src/server/actions/account/runMeAgentRequest.ts b/packages/nextjs/src/server/actions/account/runMeAgentRequest.ts new file mode 100644 index 00000000..639c6765 --- /dev/null +++ b/packages/nextjs/src/server/actions/account/runMeAgentRequest.ts @@ -0,0 +1,69 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDAPIError, resolveResourceEndpoint} from '@thunderid/node'; +import {ThunderIDNextConfig} from '../../../models/config'; +import getClient from '../../getClient'; +import getAccessToken from '../getAccessToken'; + +/** + * What a personal agent server action returns. A failure carries the status and code of the refusal, never the + * server's message, so it crosses the server action boundary as plain data. + */ +export type MeAgentActionResult = {data: T; success: true} | {code?: string; statusCode?: number; success: false}; + +/** + * Where a personal agent request goes, with the session's access token, which never leaves the server. + */ +export interface MeAgentRequestConfig { + baseUrl: string | undefined; + headers: Record; + url: string | undefined; +} + +/** + * Runs one `/users/me/agents` request for the signed-in user of the request's session. Shared by the personal agent + * server actions, which take only typed values from the browser and build the request here. + * + * @param request - Performs the request with the session's token and the configured endpoint. + * @returns The result, or the refusal without the server's message. + */ +const runMeAgentRequest = async ( + request: (config: MeAgentRequestConfig) => Promise, +): Promise> => { + const accessToken: string | undefined = await getAccessToken(); + + if (!accessToken) { + return {statusCode: 401, success: false}; + } + + try { + const client = getClient(); + + if (!client.isInitialized) { + await client.initialize({} as ThunderIDNextConfig); + } + + const config: ThunderIDNextConfig = await client.getConfiguration(); + const data: T = await request({ + baseUrl: config.baseUrl, + headers: {Authorization: `Bearer ${accessToken}`}, + url: resolveResourceEndpoint('usersMeAgents', config), + }); + + return {data, success: true}; + } catch (error) { + if (error instanceof ThunderIDAPIError) { + return {code: error.code, statusCode: error.statusCode, success: false}; + } + + return {success: false}; + } +}; + +/** + * Whether a value from the browser is an agent identifier the actions can send on. + */ +export const isAgentId = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0; + +export default runMeAgentRequest; diff --git a/packages/nextjs/src/server/actions/account/suspendAllMeAgentsAction.ts b/packages/nextjs/src/server/actions/account/suspendAllMeAgentsAction.ts new file mode 100644 index 00000000..64f2f58c --- /dev/null +++ b/packages/nextjs/src/server/actions/account/suspendAllMeAgentsAction.ts @@ -0,0 +1,16 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {SuspendAllMeAgentsResponse, suspendAllMeAgents} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult} from './runMeAgentRequest'; + +/** + * Suspends every personal agent of the signed-in user that the user has not already suspended, with the session's + * access token, which stays on the server. Takes nothing from the caller. + */ +const suspendAllMeAgentsAction = async (): Promise> => + runMeAgentRequest((config) => suspendAllMeAgents(config)); + +export default suspendAllMeAgentsAction; diff --git a/packages/nextjs/src/server/actions/account/suspendMeAgentAction.ts b/packages/nextjs/src/server/actions/account/suspendMeAgentAction.ts new file mode 100644 index 00000000..46a4a1ba --- /dev/null +++ b/packages/nextjs/src/server/actions/account/suspendMeAgentAction.ts @@ -0,0 +1,21 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {suspendMeAgent} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult, isAgentId} from './runMeAgentRequest'; + +/** + * Places the owner's suspension on one of the signed-in user's agents with the session's access token, which stays on the server. Only the agent's identifier is taken from the + * caller, and the server answers only for an agent the user owns. + */ +const suspendMeAgentAction = async (agentId: string): Promise> => { + if (!isAgentId(agentId)) { + return {statusCode: 400, success: false}; + } + + return runMeAgentRequest((config) => suspendMeAgent({...config, agentId})); +}; + +export default suspendMeAgentAction; diff --git a/packages/nextjs/src/server/actions/account/unsuspendMeAgentAction.ts b/packages/nextjs/src/server/actions/account/unsuspendMeAgentAction.ts new file mode 100644 index 00000000..ef570b5e --- /dev/null +++ b/packages/nextjs/src/server/actions/account/unsuspendMeAgentAction.ts @@ -0,0 +1,21 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {unsuspendMeAgent} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult, isAgentId} from './runMeAgentRequest'; + +/** + * Lifts the owner's suspension of one of the signed-in user's agents with the session's access token, which stays on the server. Only the agent's identifier is taken from the + * caller, and the server answers only for an agent the user owns. + */ +const unsuspendMeAgentAction = async (agentId: string): Promise> => { + if (!isAgentId(agentId)) { + return {statusCode: 400, success: false}; + } + + return runMeAgentRequest((config) => unsuspendMeAgent({...config, agentId})); +}; + +export default unsuspendMeAgentAction; diff --git a/packages/nextjs/src/server/actions/account/updateMeAgentAction.ts b/packages/nextjs/src/server/actions/account/updateMeAgentAction.ts new file mode 100644 index 00000000..7b774bce --- /dev/null +++ b/packages/nextjs/src/server/actions/account/updateMeAgentAction.ts @@ -0,0 +1,26 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use server'; + +import {Agent, UpdateMeAgentRequest, parseUpdateMeAgentRequest, updateMeAgent} from '@thunderid/node'; +import runMeAgentRequest, {MeAgentActionResult, isAgentId} from './runMeAgentRequest'; + +/** + * Replaces the part of one of the signed-in user's agents its owner may change, with the session's access token, + * which stays on the server. Only the agent's identifier and the owner-editable fields are taken from the caller. + */ +const updateMeAgentAction = async ( + agentId: string, + payload: UpdateMeAgentRequest, +): Promise> => { + const request: UpdateMeAgentRequest | undefined = parseUpdateMeAgentRequest(payload); + + if (!isAgentId(agentId) || !request) { + return {statusCode: 400, success: false}; + } + + return runMeAgentRequest((config) => updateMeAgent({...config, agentId, payload: request})); +}; + +export default updateMeAgentAction; diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 2b6066aa..51edbd8e 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -73,6 +73,7 @@ export { type ManagementCollectionKey, } from './utils/managementCollections'; export {default as getSessionCookieOptions} from './utils/getSessionCookieOptions'; +export {default as parseUpdateMeAgentRequest} from './utils/parseUpdateMeAgentRequest'; // Re-export everything from the JavaScript SDK export * from '@thunderid/javascript'; diff --git a/packages/node/src/utils/__tests__/parseUpdateMeAgentRequest.test.ts b/packages/node/src/utils/__tests__/parseUpdateMeAgentRequest.test.ts new file mode 100644 index 00000000..9d70e554 --- /dev/null +++ b/packages/node/src/utils/__tests__/parseUpdateMeAgentRequest.test.ts @@ -0,0 +1,37 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {describe, expect, it} from 'vitest'; +import parseUpdateMeAgentRequest from '../parseUpdateMeAgentRequest'; + +const payload = { + attributes: {name: 'Budget assistant'}, + description: 'Budgets', + grantTypes: ['authorization_code'], + redirectUris: ['https://assistant.example.com/callback'], +}; + +describe('parseUpdateMeAgentRequest', () => { + it('keeps only the fields an owner may change', () => { + expect(parseUpdateMeAgentRequest({...payload, clientSecret: 'stolen', owner: {id: 'someone'}})).toEqual(payload); + }); + + it('accepts an update without a description', () => { + expect(parseUpdateMeAgentRequest({...payload, description: undefined})).toEqual({ + ...payload, + description: undefined, + }); + }); + + it.each([ + ['no body', null], + ['a body that is not an object', 'name=x'], + ['no attributes', {...payload, attributes: undefined}], + ['attributes that are a list', {...payload, attributes: ['name']}], + ['a description that is not text', {...payload, description: 7}], + ['grant types that are not text', {...payload, grantTypes: [1]}], + ['no redirect URIs', {...payload, redirectUris: undefined}], + ])('refuses %s', (_name: string, body: unknown) => { + expect(parseUpdateMeAgentRequest(body)).toBeUndefined(); + }); +}); diff --git a/packages/node/src/utils/parseUpdateMeAgentRequest.ts b/packages/node/src/utils/parseUpdateMeAgentRequest.ts new file mode 100644 index 00000000..658f616c --- /dev/null +++ b/packages/node/src/utils/parseUpdateMeAgentRequest.ts @@ -0,0 +1,38 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import type {UpdateMeAgentRequest} from '@thunderid/javascript'; + +const isStringList = (value: unknown): value is string[] => + Array.isArray(value) && value.every((item: unknown) => typeof item === 'string'); + +/** + * Reads a personal agent update sent from the browser to a server that holds the session, such as a Next.js server + * action or a Nuxt server route. It keeps only the fields an owner may change, so nothing else the browser sends + * reaches ThunderID, and refuses a body of the wrong shape. + * + * @param payload - The body as received. + * @returns The update to send, or `undefined` when the body is not one. + */ +const parseUpdateMeAgentRequest = (payload: unknown): UpdateMeAgentRequest | undefined => { + if (typeof payload !== 'object' || payload === null) { + return undefined; + } + + const {attributes, description, grantTypes, redirectUris} = payload as Record; + + if ( + typeof attributes !== 'object' || + attributes === null || + Array.isArray(attributes) || + (description !== undefined && typeof description !== 'string') || + !isStringList(grantTypes) || + !isStringList(redirectUris) + ) { + return undefined; + } + + return {attributes: attributes as Record, description, grantTypes, redirectUris}; +}; + +export default parseUpdateMeAgentRequest; diff --git a/packages/nuxt/src/module.ts b/packages/nuxt/src/module.ts index f54fc2cf..10f8e5b9 100644 --- a/packages/nuxt/src/module.ts +++ b/packages/nuxt/src/module.ts @@ -38,7 +38,7 @@ const defu: ReturnType = createDefu( interface ServerRoute { handler: string; - method?: 'patch' | 'post'; + method?: 'delete' | 'get' | 'patch' | 'post' | 'put'; route: string; } @@ -220,6 +220,41 @@ export default defineNuxtModule({ handler: resolve('./runtime/server/routes/auth/user/organization-units.get'), route: NuxtAPIRoutes.USER_ORGANIZATION_UNITS, }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agents.get'), + method: 'get' as const, + route: NuxtAPIRoutes.USER_AGENTS, + }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agents-suspend.post'), + method: 'post' as const, + route: `${NuxtAPIRoutes.USER_AGENTS}/suspend`, + }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agent.get'), + method: 'get' as const, + route: `${NuxtAPIRoutes.USER_AGENTS}/:id`, + }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agent.put'), + method: 'put' as const, + route: `${NuxtAPIRoutes.USER_AGENTS}/:id`, + }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agent.delete'), + method: 'delete' as const, + route: `${NuxtAPIRoutes.USER_AGENTS}/:id`, + }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agent-suspend.post'), + method: 'post' as const, + route: `${NuxtAPIRoutes.USER_AGENTS}/:id/suspend`, + }, + { + handler: resolve('./runtime/server/routes/auth/user/agents/agent-unsuspend.post'), + method: 'post' as const, + route: `${NuxtAPIRoutes.USER_AGENTS}/:id/unsuspend`, + }, ]; // Opt-in: the route accepts unauthenticated requests, so it is served only when asked for. @@ -314,6 +349,13 @@ export default defineNuxtModule({ name: 'BaseOrganizationUnitSwitcher', }); addComponent({filePath: resolve('./runtime/components/account/VerifyAttribute'), name: 'VerifyAttribute'}); + addComponent({filePath: resolve('./runtime/components/account/PersonalAgentList'), name: 'PersonalAgentList'}); + addComponent({export: 'BasePersonalAgentList', filePath: '@thunderid/vue', name: 'BasePersonalAgentList'}); + addComponent({ + filePath: resolve('./runtime/components/account/PersonalAgentDetails'), + name: 'PersonalAgentDetails', + }); + addComponent({export: 'BasePersonalAgentDetails', filePath: '@thunderid/vue', name: 'BasePersonalAgentDetails'}); // ── Management pickers ────────────────────────────────────────────────── // Opt-in: each picker's route lists a management resource with the signed-in user's session, so the route and its diff --git a/packages/nuxt/src/runtime/components/account/PersonalAgentDetails.ts b/packages/nuxt/src/runtime/components/account/PersonalAgentDetails.ts new file mode 100644 index 00000000..1af2a0cc --- /dev/null +++ b/packages/nuxt/src/runtime/components/account/PersonalAgentDetails.ts @@ -0,0 +1,107 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + type Agent, + AgentQueryKeys, + type Preferences, + type ResourceQueryKey, + type UpdateMeAgentRequest, + toManagementErrorMessage, +} from '@thunderid/browser'; +import { + BasePersonalAgentDetails, + type ResourceMutationResult, + type ResourceQueryResult, + useI18n, + useResourceMutation, + useResourceQuery, +} from '@thunderid/vue'; +import {type Component, type PropType, type SetupContext, type VNode, defineComponent, h} from 'vue'; +import NuxtAPIRoutes from '../../constants/NuxtAPIRoutes'; +import loadMeAgentFromRoute from '../../utils/loadMeAgentFromRoute'; + +type PersonalAgentDetailsProps = Readonly<{ + agentId: string; + className: string; + deletable: boolean; + editable: boolean; + preferences: Preferences | undefined; + suspendable: boolean; +}>; + +/** + * Nuxt-specific PersonalAgentDetails container. + * + * Reads and changes one of the signed-in user's personal agents through `/api/auth/user/agents/{id}` + * (`NuxtAPIRoutes.USER_AGENTS`) with the server-held session, so the access token never reaches the browser. Emits + * `deleted` after the agent has been deleted. + * + * Renders `BasePersonalAgentDetails` from `@thunderid/vue`, with the same props, events and slots as the Vue SDK's + * `PersonalAgentDetails`. + */ +const PersonalAgentDetails: Component = defineComponent({ + name: 'PersonalAgentDetails', + props: { + agentId: {required: true, type: String}, + className: {default: '', type: String}, + deletable: {default: false, type: Boolean}, + editable: {default: false, type: Boolean}, + preferences: {default: undefined, type: Object as PropType}, + suspendable: {default: false, type: Boolean}, + }, + emits: ['deleted'], + setup(props: PersonalAgentDetailsProps, {emit, slots}: SetupContext): () => VNode { + const {t} = useI18n(); + const agentUrl = (): string => `${NuxtAPIRoutes.USER_AGENTS}/${encodeURIComponent(props.agentId)}`; + const changed = (): ResourceQueryKey[] => [[AgentQueryKeys.ME_AGENT, props.agentId], [AgentQueryKeys.ME_AGENTS]]; + + const agent: ResourceQueryResult = useResourceQuery( + () => [AgentQueryKeys.ME_AGENT, props.agentId], + () => loadMeAgentFromRoute($fetch(agentUrl())), + {enabled: () => Boolean(props.agentId)}, + ); + const update: ResourceMutationResult = useResourceMutation( + (payload: UpdateMeAgentRequest) => + loadMeAgentFromRoute($fetch(agentUrl(), {body: payload, method: 'PUT'})), + changed, + ); + const deletion: ResourceMutationResult = useResourceMutation( + () => loadMeAgentFromRoute($fetch(agentUrl(), {method: 'DELETE'})), + () => [[AgentQueryKeys.ME_AGENTS]], + {onSuccess: () => emit('deleted')}, + ); + const suspension: ResourceMutationResult = useResourceMutation( + (action: 'suspend' | 'unsuspend') => loadMeAgentFromRoute($fetch(`${agentUrl()}/${action}`, {method: 'POST'})), + changed, + ); + + return (): VNode => + h( + BasePersonalAgentDetails, + { + agent: agent.data.value, + className: props.className, + error: + toManagementErrorMessage(t, agent.error.value, 'user.agents.details.error') ?? + toManagementErrorMessage( + t, + update.error.value ?? deletion.error.value ?? suspension.error.value, + 'user.agents.action.error', + ), + isChangingSuspension: suspension.isLoading.value, + isDeleting: deletion.isLoading.value, + isLoading: agent.isLoading.value, + isUpdating: update.isLoading.value, + onDelete: props.deletable ? (): void => void deletion.mutate(undefined) : undefined, + onSuspend: props.suspendable ? (): void => void suspension.mutate('suspend') : undefined, + onUnsuspend: props.suspendable ? (): void => void suspension.mutate('unsuspend') : undefined, + onUpdate: props.editable ? (changes: UpdateMeAgentRequest): void => void update.mutate(changes) : undefined, + preferences: props.preferences, + }, + {...slots}, + ); + }, +}); + +export default PersonalAgentDetails; diff --git a/packages/nuxt/src/runtime/components/account/PersonalAgentList.ts b/packages/nuxt/src/runtime/components/account/PersonalAgentList.ts new file mode 100644 index 00000000..64d18332 --- /dev/null +++ b/packages/nuxt/src/runtime/components/account/PersonalAgentList.ts @@ -0,0 +1,112 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + type AgentListResponse, + AgentQueryKeys, + type BasicAgent, + type Preferences, + type SuspendAllMeAgentsResponse, + toManagementErrorMessage, +} from '@thunderid/browser'; +import { + BasePersonalAgentList, + type ResourceMutationResult, + type ResourceQueryResult, + useI18n, + useResourceMutation, + useResourceQuery, +} from '@thunderid/vue'; +import {type Component, type PropType, type Ref, type SetupContext, type VNode, defineComponent, h, ref} from 'vue'; +import NuxtAPIRoutes from '../../constants/NuxtAPIRoutes'; +import loadMeAgentFromRoute from '../../utils/loadMeAgentFromRoute'; + +type PersonalAgentListProps = Readonly<{ + className: string; + description: string | undefined; + limit: number; + onSelect: ((agent: BasicAgent) => void) | undefined; + preferences: Preferences | undefined; + selectedAgentId: string | undefined; + suspendable: boolean; + title: string | undefined; +}>; + +/** + * Nuxt-specific PersonalAgentList container. + * + * Lists the signed-in user's personal agents through `GET /api/auth/user/agents` (`NuxtAPIRoutes.USER_AGENTS`), and + * suspends them all through `POST /api/auth/user/agents/suspend`, with the server-held session, so the access token + * never reaches the browser. + * + * Renders `BasePersonalAgentList` from `@thunderid/vue`, with the same props, events and slots as the Vue SDK's + * `PersonalAgentList`. + */ +const PersonalAgentList: Component = defineComponent({ + name: 'PersonalAgentList', + props: { + className: {default: '', type: String}, + description: {default: undefined, type: String}, + limit: {default: 20, type: Number}, + onSelect: {default: undefined, type: Function as PropType<(agent: BasicAgent) => void>}, + preferences: {default: undefined, type: Object as PropType}, + selectedAgentId: {default: undefined, type: String}, + suspendable: {default: false, type: Boolean}, + title: {default: undefined, type: String}, + }, + setup(props: PersonalAgentListProps, {slots}: SetupContext): () => VNode { + const {t} = useI18n(); + const offset: Ref = ref(0); + const suspendedCount: Ref = ref(null); + + const list: ResourceQueryResult = useResourceQuery( + () => [AgentQueryKeys.ME_AGENTS, {limit: props.limit, offset: offset.value}], + () => + loadMeAgentFromRoute( + $fetch(NuxtAPIRoutes.USER_AGENTS, {query: {limit: props.limit, offset: offset.value}}), + ), + ); + const suspendAll: ResourceMutationResult = useResourceMutation( + () => + loadMeAgentFromRoute( + $fetch(`${NuxtAPIRoutes.USER_AGENTS}/suspend`, {method: 'POST'}), + ), + () => [[AgentQueryKeys.ME_AGENT], [AgentQueryKeys.ME_AGENTS]], + { + onSuccess: (result: SuspendAllMeAgentsResponse) => { + suspendedCount.value = result.suspendedCount; + }, + }, + ); + + return (): VNode => + h( + BasePersonalAgentList, + { + actionError: toManagementErrorMessage(t, suspendAll.error.value, 'user.agents.action.error'), + agents: list.data.value?.agents ?? [], + className: props.className, + description: props.description, + error: toManagementErrorMessage(t, list.error.value, 'user.agents.list.error'), + isLoading: list.isLoading.value, + isSuspendingAll: suspendAll.isLoading.value, + limit: props.limit, + offset: offset.value, + onPageChange: (next: number): void => { + offset.value = next; + suspendedCount.value = null; + }, + onSelect: props.onSelect, + onSuspendAll: props.suspendable ? (): void => void suspendAll.mutate(undefined) : undefined, + preferences: props.preferences, + selectedAgentId: props.selectedAgentId, + suspendedCount: suspendedCount.value, + title: props.title, + totalResults: list.data.value?.totalResults, + }, + {...slots}, + ); + }, +}); + +export default PersonalAgentList; diff --git a/packages/nuxt/src/runtime/constants/NuxtAPIRoutes.ts b/packages/nuxt/src/runtime/constants/NuxtAPIRoutes.ts index 6e1ac45d..335b5ceb 100644 --- a/packages/nuxt/src/runtime/constants/NuxtAPIRoutes.ts +++ b/packages/nuxt/src/runtime/constants/NuxtAPIRoutes.ts @@ -29,6 +29,7 @@ const NuxtAPIRoutes: { SWITCH: string; TOKEN: string; USER: string; + USER_AGENTS: string; USER_CREDENTIALS: string; USER_ORGANIZATION_UNITS: string; USER_PROFILE: string; @@ -60,6 +61,12 @@ const NuxtAPIRoutes: { TOKEN: '/api/auth/token', /** Returns the current user object. */ USER: '/api/auth/user', + /** + * The signed-in user's personal agents, using the signed-in session: list (GET), suspend all (POST `/suspend`), + * and one agent at `/{id}`: read (GET), update (PUT), delete (DELETE), suspend and unsuspend (POST `/suspend`, + * `/unsuspend`). + */ + USER_AGENTS: '/api/auth/user/agents', /** Updates (PATCH) one of the signed-in user's own credentials, e.g. `password`. */ USER_CREDENTIALS: '/api/auth/user/credentials', /** Lists (GET) the organization units the signed-in user can access, using the signed-in session. */ diff --git a/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts b/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts index 7287cfa8..b46adb40 100644 --- a/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts +++ b/packages/nuxt/src/runtime/server/ThunderIDNuxtClient.ts @@ -222,6 +222,24 @@ class ThunderIDNuxtClient extends ThunderIDNodeClient }); } + /** + * Where the session user's `/users/me/agents` requests go, with the session's access token. The token stays on + * the server. + */ + public async getMeAgentRequestConfig( + sessionId: string, + ): Promise<{baseUrl: string | undefined; headers: Record; url: string | undefined}> { + const configData: ThunderIDNuxtClientConfig = await this.getConfiguration(); + + return { + baseUrl: configData?.baseUrl, + headers: { + Authorization: `Bearer ${await this.getAccessToken(sessionId)}`, + }, + url: resolveResourceEndpoint('usersMeAgents', configData), + }; + } + override getDecodedIdToken(sessionId?: string, idToken?: string): Promise { return super.getDecodedIdToken(sessionId, idToken); } diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-suspend.post.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-suspend.post.ts new file mode 100644 index 00000000..ee8fa2a5 --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-suspend.post.ts @@ -0,0 +1,19 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {suspendMeAgent} from '@thunderid/node'; +import {defineEventHandler} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest, {requireAgentId} from '../../../../utils/meAgentRoute'; + +/** + * POST /api/auth/user/agents/:id/suspend + * + * Places the owner's suspension on one of the signed-in user's agents. + * The server answers only for an agent the user owns. Responds with no content. + */ +export default defineEventHandler(async (event: H3Event): Promise => { + const agentId: string = requireAgentId(event); + + await handleMeAgentRequest(event, (config) => suspendMeAgent({...config, agentId})); +}); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-unsuspend.post.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-unsuspend.post.ts new file mode 100644 index 00000000..751aabad --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent-unsuspend.post.ts @@ -0,0 +1,19 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {unsuspendMeAgent} from '@thunderid/node'; +import {defineEventHandler} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest, {requireAgentId} from '../../../../utils/meAgentRoute'; + +/** + * POST /api/auth/user/agents/:id/unsuspend + * + * Lifts the owner's suspension of one of the signed-in user's agents. + * The server answers only for an agent the user owns. Responds with no content. + */ +export default defineEventHandler(async (event: H3Event): Promise => { + const agentId: string = requireAgentId(event); + + await handleMeAgentRequest(event, (config) => unsuspendMeAgent({...config, agentId})); +}); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.delete.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.delete.ts new file mode 100644 index 00000000..85bbeee1 --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.delete.ts @@ -0,0 +1,19 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {deleteMeAgent} from '@thunderid/node'; +import {defineEventHandler} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest, {requireAgentId} from '../../../../utils/meAgentRoute'; + +/** + * DELETE /api/auth/user/agents/:id + * + * Deletes one of the signed-in user's agents. + * The server answers only for an agent the user owns. Responds with no content. + */ +export default defineEventHandler(async (event: H3Event): Promise => { + const agentId: string = requireAgentId(event); + + await handleMeAgentRequest(event, (config) => deleteMeAgent({...config, agentId})); +}); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.get.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.get.ts new file mode 100644 index 00000000..85020f0c --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.get.ts @@ -0,0 +1,18 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {type Agent, getMeAgent} from '@thunderid/node'; +import {defineEventHandler} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest, {requireAgentId} from '../../../../utils/meAgentRoute'; + +/** + * GET /api/auth/user/agents/:id + * + * Reads one of the signed-in user's agents. The server answers only for an agent the user owns. + */ +export default defineEventHandler(async (event: H3Event): Promise => { + const agentId: string = requireAgentId(event); + + return handleMeAgentRequest(event, (config) => getMeAgent({...config, agentId})); +}); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.put.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.put.ts new file mode 100644 index 00000000..4dd68acf --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agent.put.ts @@ -0,0 +1,32 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {type Agent, type UpdateMeAgentRequest, parseUpdateMeAgentRequest, updateMeAgent} from '@thunderid/node'; +import {createError, defineEventHandler, readBody} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest, {requireAgentId} from '../../../../utils/meAgentRoute'; + +/** + * PUT /api/auth/user/agents/:id + * + * Replaces the part of one of the signed-in user's agents its owner may change. Only `attributes`, `description`, + * `grantTypes` and `redirectUris` are taken from the body; `400` means a body of the wrong shape. + */ +export default defineEventHandler(async (event: H3Event): Promise => { + const agentId: string = requireAgentId(event); + let payload: UpdateMeAgentRequest | undefined; + + try { + payload = parseUpdateMeAgentRequest(await readBody(event)); + } catch { + payload = undefined; + } + + if (!payload) { + throw createError({statusCode: 400, statusMessage: 'Invalid request body.'}); + } + + const update: UpdateMeAgentRequest = payload; + + return handleMeAgentRequest(event, (config) => updateMeAgent({...config, agentId, payload: update})); +}); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agents-suspend.post.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agents-suspend.post.ts new file mode 100644 index 00000000..c9aad0ed --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agents-suspend.post.ts @@ -0,0 +1,19 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {type SuspendAllMeAgentsResponse, suspendAllMeAgents} from '@thunderid/node'; +import {defineEventHandler} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest from '../../../../utils/meAgentRoute'; + +/** + * POST /api/auth/user/agents/suspend + * + * Suspends every personal agent of the signed-in user that the user has not already suspended. Takes no body. + * + * Response: `{suspendedCount}`. + */ +export default defineEventHandler( + (event: H3Event): Promise => + handleMeAgentRequest(event, (config) => suspendAllMeAgents(config)), +); diff --git a/packages/nuxt/src/runtime/server/routes/auth/user/agents/agents.get.ts b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agents.get.ts new file mode 100644 index 00000000..1d6df07d --- /dev/null +++ b/packages/nuxt/src/runtime/server/routes/auth/user/agents/agents.get.ts @@ -0,0 +1,36 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {type AgentListResponse, PERSONAL_AGENT_KIND, getMeAgents} from '@thunderid/node'; +import {createError, defineEventHandler, getQuery} from 'h3'; +import type {H3Event} from 'h3'; +import handleMeAgentRequest from '../../../../utils/meAgentRoute'; + +const toCount = (value: unknown): number | undefined => { + if (value === undefined || value === null || value === '') { + return undefined; + } + + const parsed = Number(value); + + return Number.isInteger(parsed) && parsed >= 0 ? parsed : Number.NaN; +}; + +/** + * GET /api/auth/user/agents + * + * Lists a page of the signed-in user's personal agents (`/users/me/agents?kind=personal-assistant`). + * + * Query: optional `limit` and `offset`. `400` means a malformed page. + */ +export default defineEventHandler(async (event: H3Event): Promise => { + const query: Record = getQuery(event); + const limit: number | undefined = toCount(query.limit); + const offset: number | undefined = toCount(query.offset); + + if (Number.isNaN(limit) || Number.isNaN(offset)) { + throw createError({statusCode: 400, statusMessage: 'Invalid query.'}); + } + + return handleMeAgentRequest(event, (config) => getMeAgents({...config, kind: PERSONAL_AGENT_KIND, limit, offset})); +}); diff --git a/packages/nuxt/src/runtime/server/utils/meAgentRoute.ts b/packages/nuxt/src/runtime/server/utils/meAgentRoute.ts new file mode 100644 index 00000000..70c903e5 --- /dev/null +++ b/packages/nuxt/src/runtime/server/utils/meAgentRoute.ts @@ -0,0 +1,70 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {createError, getRouterParam} from 'h3'; +import type {H3Event} from 'h3'; +import {verifyAndRehydrateSession} from './serverSession'; +import ThunderIDNuxtClient from '../ThunderIDNuxtClient'; +import {useRuntimeConfig} from '#imports'; + +/** + * Where a personal agent request goes, with the session's access token. + */ +export interface MeAgentRequestConfig { + baseUrl: string | undefined; + headers: Record; + url: string | undefined; +} + +/** + * The agent identifier in the route, refused with `400` when absent. + * + * @param event - The request. + * @returns The identifier. + */ +export const requireAgentId = (event: H3Event): string => { + const agentId: string | undefined = getRouterParam(event, 'id', {decode: true}); + + if (!agentId?.trim()) { + throw createError({statusCode: 400, statusMessage: 'Invalid agent identifier.'}); + } + + return agentId; +}; + +/** + * Runs one `/users/me/agents` request for the session's user, with the server-held session. The access token never + * reaches the browser. `401` means an invalid session; a server rejection keeps its status, without its reply. + * + * @param event - The request. + * @param request - Performs the request with the session's token and the configured endpoint. + * @returns The result of the request. + */ +const handleMeAgentRequest = async ( + event: H3Event, + request: (config: MeAgentRequestConfig) => Promise, +): Promise => { + const config: ReturnType = useRuntimeConfig(); + const session: Awaited> = await verifyAndRehydrateSession( + event, + config.thunderid?.sessionSecret, + ); + + if (!session) { + throw createError({statusCode: 401, statusMessage: 'Unauthorized: Invalid or expired session.'}); + } + + try { + return await request(await ThunderIDNuxtClient.getInstance().getMeAgentRequestConfig(session.sessionId)); + } catch (error) { + const {code, statusCode} = (error as {code?: string; statusCode?: number} | null) ?? {}; + + throw createError({ + data: code ? {code} : undefined, + statusCode: statusCode && statusCode >= 400 ? statusCode : 502, + statusMessage: 'The personal agent request failed.', + }); + } +}; + +export default handleMeAgentRequest; diff --git a/packages/nuxt/src/runtime/utils/loadMeAgentFromRoute.ts b/packages/nuxt/src/runtime/utils/loadMeAgentFromRoute.ts new file mode 100644 index 00000000..c4f04d3c --- /dev/null +++ b/packages/nuxt/src/runtime/utils/loadMeAgentFromRoute.ts @@ -0,0 +1,32 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDAPIError} from '@thunderid/browser'; + +/** + * Waits for a request to a personal agent server route and returns its body, or raises its refusal as a + * {@link ThunderIDAPIError} carrying the server's status and code. The Next.js SDK raises the same error from its + * server actions, so a refusal reads the same in both. + * + * @param request - The pending `$fetch` call. + * @returns The response body. + */ +const loadMeAgentFromRoute = async (request: Promise): Promise => { + try { + return await request; + } catch (error) { + const failure: {data?: {data?: {code?: string}}; statusCode?: number} | null = error as { + data?: {data?: {code?: string}}; + statusCode?: number; + } | null; + + throw new ThunderIDAPIError( + 'Personal agent request failed', + failure?.data?.data?.code ?? 'PersonalAgents-ResponseError-001', + 'nuxt', + failure?.statusCode, + ); + } +}; + +export default loadMeAgentFromRoute; diff --git a/packages/nuxt/tests/unit/load-me-agent-from-route.test.ts b/packages/nuxt/tests/unit/load-me-agent-from-route.test.ts new file mode 100644 index 00000000..88264c09 --- /dev/null +++ b/packages/nuxt/tests/unit/load-me-agent-from-route.test.ts @@ -0,0 +1,24 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {ThunderIDAPIError} from '@thunderid/browser'; +import {describe, expect, it} from 'vitest'; +import loadMeAgentFromRoute from '../../src/runtime/utils/loadMeAgentFromRoute'; + +describe('loadMeAgentFromRoute', () => { + it('returns the body of a successful request', async () => { + await expect(loadMeAgentFromRoute(Promise.resolve(3))).resolves.toBe(3); + }); + + it("raises a refusal as an API error with the route's status and the server's code", async () => { + await expect( + loadMeAgentFromRoute( + Promise.reject(Object.assign(new Error('x'), {data: {data: {code: 'X-1'}}, statusCode: 403})), + ), + ).rejects.toMatchObject({code: 'X-1', statusCode: 403}); + await expect(loadMeAgentFromRoute(Promise.reject(new Error('down')))).rejects.toThrow(ThunderIDAPIError); + await expect(loadMeAgentFromRoute(Promise.reject(new Error('down')))).rejects.toMatchObject({ + code: 'PersonalAgents-ResponseError-001', + }); + }); +}); diff --git a/packages/nuxt/tests/unit/personal-agents.test.ts b/packages/nuxt/tests/unit/personal-agents.test.ts new file mode 100644 index 00000000..db329da3 --- /dev/null +++ b/packages/nuxt/tests/unit/personal-agents.test.ts @@ -0,0 +1,190 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/* eslint-disable @typescript-eslint/typedef, @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-function-return-type */ + +import {AgentQueryKeys, ThunderIDAPIError} from '@thunderid/browser'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {effectScope, shallowRef} from 'vue'; + +const fetchMock = vi.fn(); +const mutate = vi.fn(); +const resources: {key: () => unknown; load: () => Promise; options?: {enabled?: () => boolean}}[] = []; +const mutations: { + invalidates: () => unknown; + onSuccess?: (data: unknown) => void; + run: (variables?: unknown) => Promise; +}[] = []; +let resource: {data: unknown; error: Error | null}; +let mutationError: Error | null; + +vi.mock('@thunderid/vue', () => ({ + BasePersonalAgentDetails: {name: 'BasePersonalAgentDetails'}, + BasePersonalAgentList: {name: 'BasePersonalAgentList'}, + useI18n: () => ({t: (key: string) => key}), + useResourceMutation: (run: any, invalidates: any, options?: {onSuccess?: (data: unknown) => void}) => { + mutations.push({invalidates, onSuccess: options?.onSuccess, run}); + + return {error: shallowRef(mutationError), isLoading: shallowRef(false), mutate}; + }, + useResourceQuery: (key: any, load: any, options?: {enabled?: () => boolean}) => { + resources.push({key, load, options}); + + return {data: shallowRef(resource.data), error: shallowRef(resource.error), isLoading: shallowRef(false)}; + }, +})); + +const {default: PersonalAgentList} = await import('../../src/runtime/components/account/PersonalAgentList'); +const {default: PersonalAgentDetails} = await import('../../src/runtime/components/account/PersonalAgentDetails'); + +const setup = (component: any, props: Record) => { + const emit = vi.fn(); + const scope = effectScope(); + const render = scope.run(() => component.setup(props, {attrs: {}, emit, slots: {}} as any)); + + return {emit, props: () => render().props as any, scope}; +}; + +const listProps = { + className: '', + description: undefined, + limit: 20, + onSelect: undefined, + preferences: undefined, + selectedAgentId: undefined, + suspendable: false, + title: undefined, +}; + +const detailsProps = { + agentId: 'a/1', + className: '', + deletable: false, + editable: false, + preferences: undefined, + suspendable: false, +}; + +describe('personal agents (Nuxt)', () => { + beforeEach(() => { + resources.length = 0; + mutations.length = 0; + resource = {data: undefined, error: null}; + mutationError = null; + fetchMock.mockResolvedValue({}); + vi.stubGlobal('$fetch', fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); + }); + + it('lists the agents through the server route, offering suspend-all only when the app allows it', async () => { + resource = {data: {agents: [{id: 'a-1'}], totalResults: 3}, error: null}; + const {props, scope} = setup(PersonalAgentList, listProps); + + expect(props().agents).toEqual([{id: 'a-1'}]); + expect(props().totalResults).toBe(3); + expect(props().onSuspendAll).toBeUndefined(); + expect(resources[0].key()).toEqual([AgentQueryKeys.ME_AGENTS, {limit: 20, offset: 0}]); + + await resources[0].load(); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents', {query: {limit: 20, offset: 0}}); + + props().onPageChange(20); + expect(resources[0].key()).toEqual([AgentQueryKeys.ME_AGENTS, {limit: 20, offset: 20}]); + scope.stop(); + }); + + it('suspends every agent through its route and says how many', async () => { + const {props, scope} = setup(PersonalAgentList, {...listProps, suspendable: true}); + + props().onSuspendAll(); + expect(mutate).toHaveBeenCalled(); + await mutations[0].run(); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents/suspend', {method: 'POST'}); + expect(mutations[0].invalidates()).toEqual([[AgentQueryKeys.ME_AGENT], [AgentQueryKeys.ME_AGENTS]]); + + mutations[0].onSuccess?.({suspendedCount: 2}); + expect(props().suspendedCount).toBe(2); + scope.stop(); + }); + + it('translates a refusal without the server reply', () => { + resource = {data: undefined, error: new ThunderIDAPIError('x', 'y', 'nuxt', 403)}; + const {props, scope} = setup(PersonalAgentList, listProps); + + expect(props().error).toBe('admin.common.errors.forbidden'); + scope.stop(); + }); + + it('reads the agent through its server route and offers nothing by default', async () => { + resource = {data: {id: 'a/1'}, error: null}; + const {props, scope} = setup(PersonalAgentDetails, detailsProps); + + expect(props().agent).toEqual({id: 'a/1'}); + ['onUpdate', 'onDelete', 'onSuspend', 'onUnsuspend'].forEach((name: string) => + expect(props()[name]).toBeUndefined(), + ); + expect(resources[0].key()).toEqual([AgentQueryKeys.ME_AGENT, 'a/1']); + expect(resources[0].options?.enabled?.()).toBe(true); + await resources[0].load(); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents/a%2F1'); + scope.stop(); + }); + + it('runs each change through the route for this agent', async () => { + const {emit, props, scope} = setup(PersonalAgentDetails, { + ...detailsProps, + deletable: true, + editable: true, + suspendable: true, + }); + const [update, deletion, suspension] = mutations; + + props().onUpdate({attributes: {name: 'x'}, grantTypes: [], redirectUris: []}); + props().onDelete(); + props().onSuspend(); + props().onUnsuspend(); + expect(mutate.mock.calls).toEqual([ + [{attributes: {name: 'x'}, grantTypes: [], redirectUris: []}], + [undefined], + ['suspend'], + ['unsuspend'], + ]); + + await update.run({attributes: {name: 'x'}}); + await deletion.run(); + await suspension.run('suspend'); + await suspension.run('unsuspend'); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents/a%2F1', { + body: {attributes: {name: 'x'}}, + method: 'PUT', + }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents/a%2F1', {method: 'DELETE'}); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents/a%2F1/suspend', {method: 'POST'}); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/user/agents/a%2F1/unsuspend', {method: 'POST'}); + expect(suspension.invalidates()).toEqual([[AgentQueryKeys.ME_AGENT, 'a/1'], [AgentQueryKeys.ME_AGENTS]]); + + deletion.onSuccess?.(undefined); + expect(emit).toHaveBeenCalledWith('deleted'); + scope.stop(); + }); + + it('translates a failed change', () => { + resource = {data: {id: 'a/1'}, error: null}; + mutationError = new ThunderIDAPIError('x', 'y', 'nuxt', 500); + const {props, scope} = setup(PersonalAgentDetails, detailsProps); + + expect(props().error).toBe('user.agents.action.error'); + scope.stop(); + }); + + it('reads nothing without an agent identifier', () => { + const {scope} = setup(PersonalAgentDetails, {...detailsProps, agentId: ''}); + + expect(resources[0].options?.enabled?.()).toBe(false); + scope.stop(); + }); +}); diff --git a/packages/nuxt/tests/unit/user-agents-routes.test.ts b/packages/nuxt/tests/unit/user-agents-routes.test.ts new file mode 100644 index 00000000..12b6222b --- /dev/null +++ b/packages/nuxt/tests/unit/user-agents-routes.test.ts @@ -0,0 +1,171 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +/* eslint-disable @typescript-eslint/typedef, sort-keys, @typescript-eslint/explicit-function-return-type */ + +import {getQuery, getRouterParam, readBody} from 'h3'; +import {describe, it, expect, vi, beforeEach} from 'vitest'; + +import agentDelete from '../../src/runtime/server/routes/auth/user/agents/agent.delete'; +import agentGet from '../../src/runtime/server/routes/auth/user/agents/agent.get'; +import agentPut from '../../src/runtime/server/routes/auth/user/agents/agent.put'; +import agentSuspend from '../../src/runtime/server/routes/auth/user/agents/agent-suspend.post'; +import agentUnsuspend from '../../src/runtime/server/routes/auth/user/agents/agent-unsuspend.post'; +import agentsGet from '../../src/runtime/server/routes/auth/user/agents/agents.get'; +import agentsSuspend from '../../src/runtime/server/routes/auth/user/agents/agents-suspend.post'; +import {verifyAndRehydrateSession} from '../../src/runtime/server/utils/serverSession'; + +const mockClientInstance = vi.hoisted(() => ({ + getMeAgentRequestConfig: vi.fn<(...args: any[]) => Promise>(), +})); + +const core = vi.hoisted(() => ({ + deleteMeAgent: vi.fn<(...args: any[]) => Promise>(), + getMeAgent: vi.fn<(...args: any[]) => Promise>(), + getMeAgents: vi.fn<(...args: any[]) => Promise>(), + suspendAllMeAgents: vi.fn<(...args: any[]) => Promise>(), + suspendMeAgent: vi.fn<(...args: any[]) => Promise>(), + unsuspendMeAgent: vi.fn<(...args: any[]) => Promise>(), + updateMeAgent: vi.fn<(...args: any[]) => Promise>(), +})); + +vi.mock('@thunderid/node', async (importOriginal: () => Promise>) => ({ + ...(await importOriginal()), + ...core, +})); + +vi.mock('h3', () => ({ + defineEventHandler: (fn: Function) => fn, + getQuery: vi.fn(), + getRouterParam: vi.fn(), + readBody: vi.fn(), + createError: vi.fn((opts: any) => Object.assign(new Error(opts.statusMessage), opts)), +})); + +vi.mock('#imports', () => ({ + useRuntimeConfig: vi.fn(() => ({thunderid: {sessionSecret: 'test-secret'}})), +})); + +vi.mock('../../src/runtime/server/ThunderIDNuxtClient', () => ({ + default: {getInstance: () => mockClientInstance}, +})); + +vi.mock('../../src/runtime/server/utils/serverSession', () => ({ + verifyAndRehydrateSession: vi.fn(), +})); + +const requestConfig = { + baseUrl: 'https://localhost:8090', + headers: {Authorization: 'Bearer session-token'}, + url: undefined, +}; + +const payload = { + attributes: {name: 'Budget assistant'}, + description: 'Budgets', + grantTypes: ['authorization_code'], + redirectUris: ['https://assistant.example.com/callback'], +}; + +describe('/api/auth/user/agents routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(verifyAndRehydrateSession).mockResolvedValue({sessionId: 'session-1'} as any); + vi.mocked(getQuery).mockReturnValue({}); + vi.mocked(getRouterParam).mockReturnValue('a-1'); + mockClientInstance.getMeAgentRequestConfig.mockResolvedValue(requestConfig); + }); + + it('rejects a missing session with 401 and sends nothing', async () => { + vi.mocked(verifyAndRehydrateSession).mockResolvedValue(null as any); + + await expect((agentsGet as any)({})).rejects.toMatchObject({statusCode: 401}); + await expect((agentSuspend as any)({})).rejects.toMatchObject({statusCode: 401}); + expect(mockClientInstance.getMeAgentRequestConfig).not.toHaveBeenCalled(); + }); + + it("lists the personal agents with the server-held session's token and the paging", async () => { + vi.mocked(getQuery).mockReturnValue({limit: '5', offset: '10'}); + core.getMeAgents.mockResolvedValue({agents: [], totalResults: 0}); + + await expect((agentsGet as any)({})).resolves.toEqual({agents: [], totalResults: 0}); + expect(mockClientInstance.getMeAgentRequestConfig).toHaveBeenCalledWith('session-1'); + expect(core.getMeAgents).toHaveBeenCalledWith({...requestConfig, kind: 'personal-assistant', limit: 5, offset: 10}); + }); + + it('refuses a malformed page', async () => { + vi.mocked(getQuery).mockReturnValue({limit: '-1'}); + + await expect((agentsGet as any)({})).rejects.toMatchObject({statusCode: 400}); + expect(core.getMeAgents).not.toHaveBeenCalled(); + }); + + it('suspends every personal agent', async () => { + core.suspendAllMeAgents.mockResolvedValue({suspendedCount: 2}); + + await expect((agentsSuspend as any)({})).resolves.toEqual({suspendedCount: 2}); + expect(core.suspendAllMeAgents).toHaveBeenCalledWith(requestConfig); + }); + + it.each([ + ['GET', agentGet, core.getMeAgent], + ['DELETE', agentDelete, core.deleteMeAgent], + ['POST suspend', agentSuspend, core.suspendMeAgent], + ['POST unsuspend', agentUnsuspend, core.unsuspendMeAgent], + ])('%s addresses the one agent in the route', async (_name: string, handler: unknown, operation: any) => { + operation.mockResolvedValue(undefined); + + await (handler as any)({}); + + expect(getRouterParam).toHaveBeenCalledWith({}, 'id', {decode: true}); + expect(operation).toHaveBeenCalledWith({...requestConfig, agentId: 'a-1'}); + }); + + it.each([ + ['GET', agentGet], + ['PUT', agentPut], + ['DELETE', agentDelete], + ['POST suspend', agentSuspend], + ['POST unsuspend', agentUnsuspend], + ])('%s refuses a route without an agent identifier', async (_name: string, handler: unknown) => { + vi.mocked(getRouterParam).mockReturnValue(' '); + + await expect((handler as any)({})).rejects.toMatchObject({statusCode: 400}); + expect(mockClientInstance.getMeAgentRequestConfig).not.toHaveBeenCalled(); + }); + + it('sends only the fields an owner may change', async () => { + vi.mocked(readBody).mockResolvedValue({...payload, clientSecret: 'stolen'}); + core.updateMeAgent.mockResolvedValue({id: 'a-1'}); + + await expect((agentPut as any)({})).resolves.toEqual({id: 'a-1'}); + expect(core.updateMeAgent).toHaveBeenCalledWith({...requestConfig, agentId: 'a-1', payload}); + }); + + it('refuses an update body of the wrong shape, or one that cannot be read', async () => { + vi.mocked(readBody).mockResolvedValue({...payload, grantTypes: 'all'}); + await expect((agentPut as any)({})).rejects.toMatchObject({statusCode: 400}); + + vi.mocked(readBody).mockRejectedValue(new Error('not JSON')); + await expect((agentPut as any)({})).rejects.toMatchObject({statusCode: 400}); + expect(core.updateMeAgent).not.toHaveBeenCalled(); + }); + + it('keeps the server status and code without repeating its reply', async () => { + core.suspendMeAgent.mockRejectedValue( + Object.assign(new Error('secret upstream detail'), {code: 'AGT-1003', statusCode: 403}), + ); + + await expect((agentSuspend as any)({})).rejects.toMatchObject({ + data: {code: 'AGT-1003'}, + statusCode: 403, + statusMessage: 'The personal agent request failed.', + }); + }); + + it('answers 502 for a failure that carries no status', async () => { + core.getMeAgent.mockRejectedValue(new Error('network down')); + + await expect((agentGet as any)({})).rejects.toMatchObject({statusCode: 502}); + }); +}); diff --git a/playgrounds/nextjs/src/explorer/PersonalAgentStoryWidgets.tsx b/playgrounds/nextjs/src/explorer/PersonalAgentStoryWidgets.tsx new file mode 100644 index 00000000..29f81b9a --- /dev/null +++ b/playgrounds/nextjs/src/explorer/PersonalAgentStoryWidgets.tsx @@ -0,0 +1,151 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use client'; + +import type {Agent, BasicAgent, SuspensionAppliedBy, UpdateMeAgentRequest} from '@thunderid/browser'; +import {BasePersonalAgentDetails, BasePersonalAgentList} from '@thunderid/react'; +import {ReactElement, useState} from 'react'; +import {bool, str} from './helpers'; +import type {Action, Args} from './types'; + +const oauth = (grantTypes: string[], redirectUris: string[]): Agent['inboundAuthConfig'] => [ + { + config: {grantTypes, redirectUris, responseTypes: grantTypes.includes('authorization_code') ? ['code'] : []}, + type: 'oauth2', + }, +]; + +/** Sample personal agents for the Base stories. Nothing here reaches a server. */ +const SAMPLE_PERSONAL_AGENTS: Agent[] = [ + { + attributes: {name: 'Spending assistant', software: 'Budget Buddy 2.1'}, + clientId: 'pa_7f3e9c2a', + description: 'Answers questions about my spending', + id: 'pa-1', + inboundAuthConfig: oauth(['authorization_code', 'refresh_token'], ['https://assistant.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', + }, + { + attributes: {name: 'Travel planner'}, + clientId: 'pa_41b0d7e5', + id: 'pa-2', + inboundAuthConfig: oauth(['authorization_code'], ['https://travel.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, + { + attributes: {name: 'Inbox triage'}, + clientId: 'pa_9c2d11aa', + id: 'pa-3', + inboundAuthConfig: oauth(['authorization_code'], ['https://inbox.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['organization'], reason: 'ADMINISTRATIVE_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, +]; + +const othersThan = (agent: Agent): SuspensionAppliedBy[] => + (agent.status?.details?.appliedBy ?? []).filter((party: SuspensionAppliedBy) => party !== 'owner'); + +const suspendedByOwner = (agent: Agent): Agent['status'] => ({ + details: {appliedBy: [...othersThan(agent), 'owner']}, + value: 'SUSPENDED', +}); + +const liftedByOwner = (agent: Agent): Agent['status'] => + othersThan(agent).length ? {details: {appliedBy: othersThan(agent)}, value: 'SUSPENDED'} : {value: 'ACTIVE'}; + +/** The Base list with the sample agents, suspended locally. */ +export const SamplePersonalAgentList = ({action, args}: {action: Action; args: Args}): ReactElement => { + const [agents, setAgents] = useState(SAMPLE_PERSONAL_AGENTS); + const [selectedId, setSelectedId] = useState(undefined); + const [suspendedCount, setSuspendedCount] = useState(null); + + return ( + { + action('onSelect', agent.id); + setSelectedId(agent.id); + }} + onSuspendAll={ + bool(args, 'suspendable') + ? (): void => { + const count: number = agents.filter( + (agent: Agent) => !agent.status?.details?.appliedBy?.includes('owner'), + ).length; + action('onSuspendAll', String(count)); + setAgents((current: Agent[]) => + current.map((agent: Agent) => ({...agent, status: suspendedByOwner(agent)})), + ); + setSuspendedCount(count); + } + : undefined + } + /> + ); +}; + +/** The Base details with one sample agent, edited and suspended locally. */ +export const SamplePersonalAgentDetails = ({action, args}: {action: Action; args: Args}): ReactElement => { + const initial: Agent = + SAMPLE_PERSONAL_AGENTS.find((agent: Agent) => agent.id === str(args, 'sample')) ?? SAMPLE_PERSONAL_AGENTS[0]; + const [agent, setAgent] = useState(initial); + const change = (next: (current: Agent) => Agent): void => + setAgent((current: Agent | undefined) => current && next(current)); + + return ( + { + action('onUpdate', JSON.stringify(changes)); + change((current: Agent) => ({ + ...current, + attributes: changes.attributes, + description: changes.description, + inboundAuthConfig: oauth(changes.grantTypes, changes.redirectUris), + })); + } + : undefined + } + onDelete={ + bool(args, 'deletable') + ? (): void => { + action('onDelete', initial.id); + setAgent(undefined); + } + : undefined + } + onSuspend={ + bool(args, 'suspendable') + ? (): void => { + action('onSuspend', initial.id); + change((current: Agent) => ({...current, status: suspendedByOwner(current)})); + } + : undefined + } + onUnsuspend={ + bool(args, 'suspendable') + ? (): void => { + action('onUnsuspend', initial.id); + change((current: Agent) => ({...current, status: liftedByOwner(current)})); + } + : undefined + } + /> + ); +}; diff --git a/playgrounds/nextjs/src/explorer/personalAgentStories.tsx b/playgrounds/nextjs/src/explorer/personalAgentStories.tsx new file mode 100644 index 00000000..3222d745 --- /dev/null +++ b/playgrounds/nextjs/src/explorer/personalAgentStories.tsx @@ -0,0 +1,169 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +'use client'; + +import type {BasicAgent} from '@thunderid/browser'; +import {PersonalAgentDetails, PersonalAgentList} from '@thunderid/nextjs'; +import {NeedsId} from './AdminParts'; +import {bool, fromReact, isLive, jsx, omit, str} from './helpers'; +import Narrow from './Narrow'; +import {SamplePersonalAgentDetails, SamplePersonalAgentList} from './PersonalAgentStoryWidgets'; +import type {Action, Args, ComponentDef, PropControl} from './types'; + +const SOURCE: PropControl = { + control: ['base', 'live'], + description: + "base renders the Base component from @thunderid/react with sample agents; live manages the signed-in user's personal agents through server actions.", + name: 'source', + type: "'base' | 'live' (playground only)", +}; + +const SUSPENDABLE: PropControl = { + control: 'bool', + description: 'Lets the user suspend agents and lift their own suspension.', + name: 'suspendable', + type: 'boolean', +}; + +export const PERSONAL_AGENT_LIST_STORY: ComponentDef = { + code: (args: Args) => + isLive(args) + ? { + imports: ['PersonalAgentList'], + jsx: jsx('PersonalAgentList', omit(args, 'source', 'empty'), { + extra: ['onSelect={(agent) => setAgentId(agent.id)}'], + }), + } + : fromReact({ + imports: ['BasePersonalAgentList'], + jsx: jsx('BasePersonalAgentList', omit(args, 'source', 'empty', 'suspendable'), { + extra: [ + 'agents={agents}', + 'onSelect={select}', + ...(bool(args, 'suspendable') ? ['onSuspendAll={suspendAll}'] : []), + ], + }), + }), + controls: [ + SOURCE, + SUSPENDABLE, + { + control: 'bool', + description: 'Base only: shows the empty list.', + name: 'empty', + type: 'boolean (playground only)', + }, + {control: 'text', description: 'Heading. Leave empty for the default.', name: 'title', type: 'string'}, + ], + defaults: {empty: false, source: 'base', suspendable: false, title: ''}, + group: 'User', + id: 'personalagentlist', + live: true, + name: 'PersonalAgentList', + render: (args: Args, action: Action) => ( + + {isLive(args) ? ( + action('onSelect', agent.id)} + /> + ) : ( + + )} + + ), + stories: [ + {args: {suspendable: true}, id: 'base', name: 'Sample agents'}, + {args: {empty: true}, id: 'empty', name: 'No agents'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user'}, + ], +}; + +export const PERSONAL_AGENT_DETAILS_STORY: ComponentDef = { + code: (args: Args) => + isLive(args) + ? { + imports: ['PersonalAgentDetails'], + jsx: jsx('PersonalAgentDetails', omit(args, 'source', 'sample', 'isLoading', 'error'), { + extra: ['onDeleted={backToList}'], + }), + } + : fromReact({ + imports: ['BasePersonalAgentDetails'], + jsx: jsx( + 'BasePersonalAgentDetails', + {}, + { + extra: [ + 'agent={agent}', + ...(bool(args, 'editable') ? ['onUpdate={update}'] : []), + ...(bool(args, 'deletable') ? ['onDelete={remove}'] : []), + ...(bool(args, 'suspendable') ? ['onSuspend={suspend}', 'onUnsuspend={unsuspend}'] : []), + ], + }, + ), + }), + controls: [ + SOURCE, + { + control: 'text', + description: 'Live only: the ID of one of your personal agents.', + name: 'agentId', + type: 'string', + }, + { + control: ['pa-1', 'pa-2', 'pa-3'], + description: 'Base only: pa-1 is active, pa-2 is suspended by its owner, pa-3 by the organization.', + name: 'sample', + type: 'string (playground only)', + }, + {control: 'bool', description: 'Lets the user edit the agent.', name: 'editable', type: 'boolean'}, + {control: 'bool', description: 'Lets the user delete the agent.', name: 'deletable', type: 'boolean'}, + SUSPENDABLE, + {control: 'bool', description: 'Base only: shows the loading state.', name: 'isLoading', type: 'boolean'}, + {control: 'text', description: 'Base only: an error message to show.', name: 'error', type: 'string'}, + ], + defaults: { + agentId: '', + deletable: false, + editable: false, + error: '', + isLoading: false, + sample: 'pa-1', + source: 'base', + suspendable: false, + }, + group: 'User', + id: 'personalagentdetails', + live: true, + name: 'PersonalAgentDetails', + render: (args: Args, action: Action) => { + if (isLive(args) && !str(args, 'agentId')) { + return ; + } + + return ( + + {isLive(args) ? ( + action('onDeleted')} + /> + ) : ( + + )} + + ); + }, + stories: [ + {args: {deletable: true, editable: true, suspendable: true}, id: 'base', name: 'Sample agent'}, + {args: {sample: 'pa-2', suspendable: true}, id: 'owner-suspended', name: 'Suspended by its owner'}, + {args: {sample: 'pa-3', suspendable: true}, id: 'org-suspended', name: 'Suspended by the organization'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user (needs agentId)'}, + ], +}; diff --git a/playgrounds/nextjs/src/explorer/stories.tsx b/playgrounds/nextjs/src/explorer/stories.tsx index 00c5ebee..6060e575 100644 --- a/playgrounds/nextjs/src/explorer/stories.tsx +++ b/playgrounds/nextjs/src/explorer/stories.tsx @@ -43,6 +43,7 @@ import {bool, fromReact, isLive, jsx, num, omit, str} from './helpers'; import Narrow from './Narrow'; import {ORGANIZATION_UNIT_ADMIN_STORIES} from './organizationUnitAdminStories'; import {ORGANIZATION_UNIT_SWITCHER_STORY} from './organizationUnitStories'; +import {PERSONAL_AGENT_DETAILS_STORY, PERSONAL_AGENT_LIST_STORY} from './personalAgentStories'; import {PROJECT_STORIES} from './projectStories'; import {SHARING_STORIES} from './sharingStories'; import type {Action, Args, ComponentDef, PropControl} from './types'; @@ -612,6 +613,8 @@ export const COMPONENTS: ComponentDef[] = [ selectComponent('usertypeselect', 'UserTypeSelect', UserTypeSelect, 'User type', 'user types'), selectComponent('authflowselect', 'AuthFlowSelect', AuthFlowSelect, 'Sign-in flow', 'flows'), ORGANIZATION_UNIT_SWITCHER_STORY, + PERSONAL_AGENT_LIST_STORY, + PERSONAL_AGENT_DETAILS_STORY, ...ADMIN_COMPONENTS, ...PROJECT_STORIES, ...ORGANIZATION_UNIT_ADMIN_STORIES, diff --git a/playgrounds/nuxt/lib/personalAgentSamples.ts b/playgrounds/nuxt/lib/personalAgentSamples.ts new file mode 100644 index 00000000..38fc730e --- /dev/null +++ b/playgrounds/nuxt/lib/personalAgentSamples.ts @@ -0,0 +1,164 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import type {Agent, BasicAgent, SuspensionAppliedBy, UpdateMeAgentRequest} from '@thunderid/browser'; +import {BasePersonalAgentDetails, BasePersonalAgentList} from '@thunderid/vue'; +import {defineComponent, h, ref, type Component, type PropType, type Ref, type VNode} from 'vue'; +import type {Action} from './storyTypes'; + +const oauth = (grantTypes: string[], redirectUris: string[]): Agent['inboundAuthConfig'] => [ + { + config: {grantTypes, redirectUris, responseTypes: grantTypes.includes('authorization_code') ? ['code'] : []}, + type: 'oauth2', + }, +]; + +/** Sample personal agents for the Base stories. Nothing here reaches a server. */ +const SAMPLE_PERSONAL_AGENTS: Agent[] = [ + { + attributes: {name: 'Spending assistant', software: 'Budget Buddy 2.1'}, + clientId: 'pa_7f3e9c2a', + description: 'Answers questions about my spending', + id: 'pa-1', + inboundAuthConfig: oauth(['authorization_code', 'refresh_token'], ['https://assistant.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {value: 'ACTIVE'}, + type: 'default', + }, + { + attributes: {name: 'Travel planner'}, + clientId: 'pa_41b0d7e5', + id: 'pa-2', + inboundAuthConfig: oauth(['authorization_code'], ['https://travel.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['owner'], reason: 'OWNER_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, + { + attributes: {name: 'Inbox triage'}, + clientId: 'pa_9c2d11aa', + id: 'pa-3', + inboundAuthConfig: oauth(['authorization_code'], ['https://inbox.example.com/callback']), + kind: 'personal-assistant', + ouId: 'ou-1', + status: {details: {appliedBy: ['organization'], reason: 'ADMINISTRATIVE_SUSPENSION'}, value: 'SUSPENDED'}, + type: 'default', + }, +]; + +const othersThan = (agent: Agent): SuspensionAppliedBy[] => + (agent.status?.details?.appliedBy ?? []).filter((party: SuspensionAppliedBy) => party !== 'owner'); + +const suspendedByOwner = (agent: Agent): Agent['status'] => ({ + details: {appliedBy: [...othersThan(agent), 'owner']}, + value: 'SUSPENDED', +}); + +const liftedByOwner = (agent: Agent): Agent['status'] => + othersThan(agent).length ? {details: {appliedBy: othersThan(agent)}, value: 'SUSPENDED'} : {value: 'ACTIVE'}; + +/** The Base list with the sample agents, suspended locally. */ +export const SamplePersonalAgentList: Component = defineComponent({ + name: 'SamplePersonalAgentList', + props: { + action: {required: true, type: Function as PropType}, + empty: {default: false, type: Boolean}, + suspendable: {default: false, type: Boolean}, + title: {default: undefined, type: String}, + }, + setup(props: {action: Action; empty: boolean; suspendable: boolean; title?: string}): () => VNode { + const agents: Ref = ref(SAMPLE_PERSONAL_AGENTS); + const selectedId: Ref = ref(undefined); + const suspendedCount: Ref = ref(null); + + return (): VNode => + h(BasePersonalAgentList, { + agents: props.empty ? [] : agents.value, + onSelect: (agent: BasicAgent): void => { + selectedId.value = agent.id; + props.action('select', `"${agent.id}"`); + }, + onSuspendAll: props.suspendable + ? (): void => { + const count: number = agents.value.filter( + (agent: Agent) => !agent.status?.details?.appliedBy?.includes('owner'), + ).length; + agents.value = agents.value.map((agent: Agent) => ({...agent, status: suspendedByOwner(agent)})); + suspendedCount.value = count; + props.action('suspend-all', String(count)); + } + : undefined, + selectedAgentId: selectedId.value, + suspendedCount: suspendedCount.value, + title: props.title, + }); + }, +}); + +/** The Base details with one sample agent, edited and suspended locally. */ +export const SamplePersonalAgentDetails: Component = defineComponent({ + name: 'SamplePersonalAgentDetails', + props: { + action: {required: true, type: Function as PropType}, + deletable: {default: false, type: Boolean}, + editable: {default: false, type: Boolean}, + error: {default: null, type: String as PropType}, + isLoading: {default: false, type: Boolean}, + sample: {default: 'pa-1', type: String}, + suspendable: {default: false, type: Boolean}, + }, + setup(props: { + action: Action; + deletable: boolean; + editable: boolean; + error: string | null; + isLoading: boolean; + sample: string; + suspendable: boolean; + }): () => VNode { + const initial: Agent = + SAMPLE_PERSONAL_AGENTS.find((agent: Agent) => agent.id === props.sample) ?? SAMPLE_PERSONAL_AGENTS[0]; + const agent: Ref = ref(initial); + const change = (next: (current: Agent) => Agent): void => { + agent.value = agent.value && next(agent.value); + }; + + return (): VNode => + h(BasePersonalAgentDetails, { + agent: agent.value, + error: props.error, + isLoading: props.isLoading, + onDelete: props.deletable + ? (): void => { + props.action('delete', `"${initial.id}"`); + agent.value = undefined; + } + : undefined, + onSuspend: props.suspendable + ? (): void => { + props.action('suspend', `"${initial.id}"`); + change((current: Agent) => ({...current, status: suspendedByOwner(current)})); + } + : undefined, + onUnsuspend: props.suspendable + ? (): void => { + props.action('unsuspend', `"${initial.id}"`); + change((current: Agent) => ({...current, status: liftedByOwner(current)})); + } + : undefined, + onUpdate: props.editable + ? (changes: UpdateMeAgentRequest): void => { + props.action('update', JSON.stringify(changes)); + change((current: Agent) => ({ + ...current, + attributes: changes.attributes, + description: changes.description, + inboundAuthConfig: oauth(changes.grantTypes, changes.redirectUris), + })); + } + : undefined, + }); + }, +}); diff --git a/playgrounds/nuxt/lib/personalAgentStories.ts b/playgrounds/nuxt/lib/personalAgentStories.ts new file mode 100644 index 00000000..22187000 --- /dev/null +++ b/playgrounds/nuxt/lib/personalAgentStories.ts @@ -0,0 +1,165 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import type {BasicAgent} from '@thunderid/browser'; +import {h, type VNode} from 'vue'; +import {SamplePersonalAgentDetails, SamplePersonalAgentList} from './personalAgentSamples'; +import {tag} from './storyCode'; +import type {Action, Args, ArgValue, ComponentDef, PropControl} from './storyTypes'; +import {narrow} from './storyWidgets'; +import {PersonalAgentDetails, PersonalAgentList} from '#components'; + +const str = (args: Args, key: string): string => String(args[key] ?? ''); +const bool = (args: Args, key: string): boolean => args[key] === true; +const isLive = (args: Args): boolean => str(args, 'source') === 'live'; +const omit = (args: Args, ...keys: string[]): Args => + Object.fromEntries(Object.entries(args).filter(([key]: [string, ArgValue]) => !keys.includes(key))); + +const SUSPENDABLE: PropControl = { + control: 'bool', + description: 'Lets the user suspend agents and lift their own suspension.', + name: 'suspendable', + type: 'boolean', +}; + +const notice = (message: string): VNode => h('div', {class: 'pg-warning', role: 'status'}, message); + +export const PERSONAL_AGENT_COMPONENTS: ComponentDef[] = [ + { + code: (args: Args) => ({ + imports: [], + template: tag('PersonalAgentList', omit(args, 'source', 'empty'), { + defaults: {suspendable: false}, + extra: ['@select="handleSelect"'], + }), + }), + controls: [ + { + control: ['base', 'live'], + description: + 'base renders BasePersonalAgentList with sample agents; live lists through GET /api/auth/user/agents and suspends all through POST /api/auth/user/agents/suspend.', + name: 'source', + type: "'base' | 'live' (playground only)", + }, + SUSPENDABLE, + { + control: 'bool', + description: 'Base only: shows the empty list.', + name: 'empty', + type: 'boolean (playground only)', + }, + {control: 'text', description: 'Heading. Leave empty for the default.', name: 'title', type: 'string'}, + ], + defaults: {empty: false, source: 'base', suspendable: false, title: ''}, + group: 'User', + id: 'personalagentlist', + live: true, + name: 'PersonalAgentList', + render: (args: Args, action: Action) => + narrow( + 640, + isLive(args) + ? h(PersonalAgentList, { + onSelect: (agent: BasicAgent) => action('select', `"${agent.id}"`), + suspendable: bool(args, 'suspendable'), + title: str(args, 'title') || undefined, + }) + : h(SamplePersonalAgentList, { + action, + empty: bool(args, 'empty'), + suspendable: bool(args, 'suspendable'), + title: str(args, 'title') || undefined, + }), + ), + stories: [ + {args: {suspendable: true}, id: 'base', name: 'Sample agents'}, + {args: {empty: true}, id: 'empty', name: 'No agents'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user'}, + ], + }, + { + code: (args: Args) => ({ + imports: [], + template: tag('PersonalAgentDetails', omit(args, 'source', 'sample', 'isLoading', 'error'), { + defaults: {deletable: false, editable: false, suspendable: false}, + extra: ['@deleted="handleDeleted"'], + }), + }), + controls: [ + { + control: ['base', 'live'], + description: + 'base renders BasePersonalAgentDetails with a sample agent; live reads and changes the agent through /api/auth/user/agents/{id}.', + name: 'source', + type: "'base' | 'live' (playground only)", + }, + { + control: 'text', + description: 'Live only: the ID of one of your personal agents.', + name: 'agentId', + type: 'string', + }, + { + control: ['pa-1', 'pa-2', 'pa-3'], + description: 'Base only: pa-1 is active, pa-2 is suspended by its owner, pa-3 by the organization.', + name: 'sample', + type: 'string (playground only)', + }, + {control: 'bool', description: 'Lets the user edit the agent.', name: 'editable', type: 'boolean'}, + {control: 'bool', description: 'Lets the user delete the agent.', name: 'deletable', type: 'boolean'}, + SUSPENDABLE, + {control: 'bool', description: 'Base only: shows the loading state.', name: 'isLoading', type: 'boolean'}, + {control: 'text', description: 'Base only: an error message to show.', name: 'error', type: 'string'}, + ], + defaults: { + agentId: '', + deletable: false, + editable: false, + error: '', + isLoading: false, + sample: 'pa-1', + source: 'base', + suspendable: false, + }, + group: 'User', + id: 'personalagentdetails', + live: true, + name: 'PersonalAgentDetails', + render: (args: Args, action: Action) => { + if (isLive(args) && !str(args, 'agentId')) { + return notice( + 'Set agentId in Controls: select a row in PersonalAgentList and copy its id from the Actions panel.', + ); + } + + return narrow( + 640, + isLive(args) + ? h(PersonalAgentDetails, { + agentId: str(args, 'agentId'), + deletable: bool(args, 'deletable'), + editable: bool(args, 'editable'), + key: str(args, 'agentId'), + onDeleted: () => action('deleted', `"${str(args, 'agentId')}"`), + suspendable: bool(args, 'suspendable'), + }) + : h(SamplePersonalAgentDetails, { + action, + deletable: bool(args, 'deletable'), + editable: bool(args, 'editable'), + error: str(args, 'error') || null, + isLoading: bool(args, 'isLoading'), + key: str(args, 'sample'), + sample: str(args, 'sample'), + suspendable: bool(args, 'suspendable'), + }), + ); + }, + stories: [ + {args: {deletable: true, editable: true, suspendable: true}, id: 'base', name: 'Sample agent'}, + {args: {sample: 'pa-2', suspendable: true}, id: 'owner-suspended', name: 'Suspended by its owner'}, + {args: {sample: 'pa-3', suspendable: true}, id: 'org-suspended', name: 'Suspended by the organization'}, + {args: {source: 'live', suspendable: true}, id: 'live', name: 'Signed-in user (needs agentId)'}, + ], + }, +]; diff --git a/playgrounds/nuxt/lib/stories.ts b/playgrounds/nuxt/lib/stories.ts index a83124e4..630a8ebf 100644 --- a/playgrounds/nuxt/lib/stories.ts +++ b/playgrounds/nuxt/lib/stories.ts @@ -26,6 +26,7 @@ import {ADMIN_COMPONENTS} from './adminStories'; import {CUSTOM_RENDER_COMPONENTS, SAMPLE_VERIFICATION_STEP, submitSampleVerification} from './customRenderStories'; import {ORGANIZATION_UNIT_ADMIN_STORIES, PROJECT_STORIES, SHARING_STORIES} from './managementAreaStories'; import {SampleOrganizationUnitSwitcher} from './organizationUnitSamples'; +import {PERSONAL_AGENT_COMPONENTS} from './personalAgentStories'; import {tag} from './storyCode'; import type {Action, Args, ArgValue, ComponentDef, PropControl} from './storyTypes'; import {CheckboxStory, narrow, OtpFieldStory, PasswordFieldStory, SelectStory, TextFieldStory} from './storyWidgets'; @@ -995,6 +996,7 @@ export const COMPONENTS: ComponentDef[] = [ 'GET /api/auth/user-types', 'userTypes', ), + ...PERSONAL_AGENT_COMPONENTS, ...ADMIN_COMPONENTS, ...PROJECT_STORIES, ...ORGANIZATION_UNIT_ADMIN_STORIES,