From 1081a92f023ec89a5bbc41eb5d607433097b05f2 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:04:04 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=A4=20feat:=20Link=20and=20Revoke=20Pe?= =?UTF-8?q?rsonal=20Channel=20Accounts=20(#17615)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 👤 feat: Link and Revoke Personal Channel Accounts * fix: Own Channel Link Lifetimes and Complete Channel Entry Points * fix(channels): activate trusted link URLs with account page * fix: Preserve Personal Consent for Channel Managers * test: preserve channel fixture in upstream agent selection cases --- api/server/services/ChannelAuthority.js | 1 + api/server/services/ChannelAuthority.spec.js | 30 +- client/src/components/Channels/Link.spec.tsx | 277 ++++++++++++ client/src/components/Channels/Link.tsx | 191 ++++++++ client/src/components/Channels/Links.tsx | 111 +++++ .../src/components/Channels/LinksSettings.tsx | 15 + .../src/components/Nav/Settings/registry.tsx | 9 + .../SidePanel/Agents/AgentConfig.tsx | 13 - .../SidePanel/Agents/AgentPanel.test.tsx | 122 +++++- .../SidePanel/Agents/AgentPanel.tsx | 51 ++- client/src/hooks/useOwnerActionPolicy.tsx | 41 ++ client/src/locales/en/translation.json | 31 +- client/src/routes/ChannelLinkRoute.tsx | 198 +++++++++ client/src/routes/ResponseReviewRoute.tsx | 29 +- .../__tests__/ChannelLinkRoute.spec.tsx | 406 ++++++++++++++++++ client/src/routes/index.tsx | 6 + .../channel-account-lifecycle.spec.ts | 107 +++++ 17 files changed, 1582 insertions(+), 56 deletions(-) create mode 100644 client/src/components/Channels/Link.spec.tsx create mode 100644 client/src/components/Channels/Link.tsx create mode 100644 client/src/components/Channels/Links.tsx create mode 100644 client/src/components/Channels/LinksSettings.tsx create mode 100644 client/src/hooks/useOwnerActionPolicy.tsx create mode 100644 client/src/routes/ChannelLinkRoute.tsx create mode 100644 client/src/routes/__tests__/ChannelLinkRoute.spec.tsx create mode 100644 e2e/specs/mock/scenarios/channel-account-lifecycle.spec.ts diff --git a/api/server/services/ChannelAuthority.js b/api/server/services/ChannelAuthority.js index d07eacc496..f6651654aa 100644 --- a/api/server/services/ChannelAuthority.js +++ b/api/server/services/ChannelAuthority.js @@ -26,6 +26,7 @@ module.exports = createChannelApplicationAuthority({ findUser: (id) => db.findUser({ _id: id }), getRole: db.getRoleByName, isPrincipalActive: db.isAgentTriggerPrincipalActive, + publicBaseUrl: process.env.DOMAIN_CLIENT || 'http://localhost:3080', access: { getAgent: db.getAgent, getEffectivePermissions }, credentials: { encrypt: encryptCredential, diff --git a/api/server/services/ChannelAuthority.spec.js b/api/server/services/ChannelAuthority.spec.js index de2ebc549e..044d86383e 100644 --- a/api/server/services/ChannelAuthority.spec.js +++ b/api/server/services/ChannelAuthority.spec.js @@ -61,7 +61,7 @@ it('loads effective current-principal policy without bypassing database override }); }); -it('does not persist a browser ticket before the link page is installed', async () => { +it('refuses an unsafe origin at actual ticket issuance before persisting a ticket', async () => { const leaf = require('./ChannelAuthority'); mockGetChannelMetadata.mockResolvedValue({ channelId: 'channel', @@ -79,6 +79,32 @@ it('does not persist a browser ticket before the link page is installed', async teamId: 'T1', externalUserId: 'U1', }), - ).resolves.toEqual({ ok: false, error: { code: 'unavailable' } }); + ).rejects.toThrow('HTTPS'); + expect(mockGetChannelMetadata).toHaveBeenCalledWith('channel'); expect(mockIdentityStorage.saveChannelIdentity).not.toHaveBeenCalled(); }); + +it('issues a ticket to the installed link page using the trusted deployment origin', async () => { + process.env.DOMAIN_CLIENT = 'https://chat.example.test'; + const leaf = require('./ChannelAuthority'); + mockGetChannelMetadata.mockResolvedValue({ + channelId: 'channel', + agentId: 'agent', + revision: 'v1', + status: 'active', + slack: { teamId: 'T1' }, + }); + mockIdentityStorage.saveChannelIdentity.mockResolvedValue(true); + const result = await leaf.authority.identity.issue({ + tenantId: '_', + channelId: 'channel', + agentId: 'agent', + channelRevision: 'v1', + teamId: 'T1', + externalUserId: 'U1', + }); + expect(result.ok).toBe(true); + expect(new URL(result.value.url).origin).toBe('https://chat.example.test'); + expect(new URL(result.value.url).pathname).toBe('/channels/link'); + expect(mockIdentityStorage.saveChannelIdentity).toHaveBeenCalledTimes(1); +}); diff --git a/client/src/components/Channels/Link.spec.tsx b/client/src/components/Channels/Link.spec.tsx new file mode 100644 index 0000000000..d5c4dfed46 --- /dev/null +++ b/client/src/components/Channels/Link.spec.tsx @@ -0,0 +1,277 @@ +import React from 'react'; +import userEvent from '@testing-library/user-event'; +import { QueryKeys } from 'librechat-data-provider'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, render, screen, waitFor, within } from '@testing-library/react'; +import type { ChannelIdentityClient, ChannelLinkView } from 'librechat-data-provider'; +import Links from './Links'; +import Link from './Link'; + +jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key })); +const pending: ChannelLinkView = { + identity: { + tenantId: 'tenant', + channelId: 'channel', + channelRevision: 'c-rev', + teamId: 'T1', + externalUserId: 'U1', + agentId: 'agent', + }, + linkId: 'link', + revision: 'revision', + state: 'pending', + expiresAtMs: Date.now() + 60000, +}; +let api: jest.Mocked; +function renderPage(element: React.ReactElement) { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + logger: { log: () => {}, warn: () => {}, error: () => {} }, + }); + return { + client, + ...render({element}), + }; +} +beforeEach(() => { + window.history.replaceState({}, '', '/channels/link'); + api = { + preview: jest.fn().mockResolvedValue({ ok: true, value: pending }), + accept: jest.fn().mockImplementation(async () => { + const result = { ok: true as const, value: { ...pending, state: 'accepted' as const } }; + api.preview.mockResolvedValue(result); + return result; + }), + list: jest.fn().mockResolvedValue([{ ...pending, state: 'active' }]), + revoke: jest.fn().mockResolvedValue({ ok: true, value: { ...pending, state: 'revoked' } }), + }; +}); + +test('preview is read-only, clears the fragment, and requires explicit acceptance then Slack confirmation', async () => { + const user = userEvent.setup(); + window.history.replaceState({}, '', '/channels/link#private-ticket'); + const { client } = renderPage( + , + ); + await screen.findByText('U1'); + expect(window.location.hash).toBe(''); + expect(api.preview).toHaveBeenCalledWith('private-ticket'); + expect(api.accept).not.toHaveBeenCalled(); + expect( + JSON.stringify( + client + .getQueryCache() + .getAll() + .map((query) => query.queryKey), + ), + ).not.toContain('private-ticket'); + await user.click(screen.getByRole('button', { name: 'com_ui_channel_link_accept' })); + await waitFor(() => + expect(api.accept).toHaveBeenCalledWith({ + ticket: 'private-ticket', + expectedRevision: 'revision', + }), + ); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_confirm_slack'); + expect( + screen.queryByRole('button', { name: 'com_ui_channel_link_accept' }), + ).not.toBeInTheDocument(); +}); + +test('expired or failed tickets cannot activate a link or expose server error text', async () => { + api.preview.mockResolvedValue({ ok: false, error: { code: 'expired' } }); + renderPage( + , + ); + expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_channel_link_expired'); + expect( + screen.queryByRole('button', { name: 'com_ui_channel_link_accept' }), + ).not.toBeInTheDocument(); + expect(api.accept).not.toHaveBeenCalled(); +}); + +test('missing ticket cannot issue any link API calls', () => { + renderPage(); + expect(screen.getByRole('alert')).toHaveTextContent('com_ui_channel_link_invalid'); + expect(api.preview).not.toHaveBeenCalled(); + expect(api.accept).not.toHaveBeenCalled(); +}); + +test('personal revocation requires confirmation and uses exact link revision', async () => { + const user = userEvent.setup(); + renderPage(); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_revoke' })); + expect(api.revoke).not.toHaveBeenCalled(); + const confirmation = screen.getByRole('group', { name: 'com_ui_channel_link_revoke_confirm' }); + api.list.mockResolvedValue([{ ...pending, state: 'revoked' }]); + await user.click( + within(confirmation).getByRole('button', { name: 'com_ui_channel_link_revoke' }), + ); + await waitFor(() => expect(api.revoke).toHaveBeenCalledWith('link', 'revision')); + expect(await screen.findByText('com_ui_channel_link_revoked')).toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'com_ui_channel_link_revoke' }), + ).not.toBeInTheDocument(); +}); + +test.each([ + ['active', 'com_ui_channel_link_active'], + ['expired', 'com_ui_channel_link_expired'], + ['revoked', 'com_ui_channel_link_revoked'], + ['unavailable', 'com_ui_channel_link_unavailable'], +] as const)('a current %s preview replaces an earlier acceptance receipt', async (state, label) => { + const user = userEvent.setup(); + const { client } = renderPage( + , + ); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_confirm_slack'); + api.preview.mockResolvedValue({ ok: true, value: { ...pending, state } }); + await act(async () => { + await client.invalidateQueries([QueryKeys.channelLinkTicket]); + }); + expect(await screen.findByText(label)).toBeInTheDocument(); + expect(screen.queryByText('com_ui_channel_link_confirm_slack')).not.toBeInTheDocument(); + expect(api.accept).toHaveBeenCalledTimes(1); +}); + +test.each(['expired', 'revoked'] as const)( + 'a current %s preview error replaces an earlier acceptance receipt', + async (code) => { + const user = userEvent.setup(); + const { client } = renderPage( + , + ); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + await screen.findByRole('status'); + api.preview.mockResolvedValue({ ok: false, error: { code } }); + await act(async () => { + await client.invalidateQueries([QueryKeys.channelLinkTicket]); + }); + expect(await screen.findByRole('alert')).toHaveTextContent(`com_ui_channel_link_${code}`); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + }, +); + +test('an expired successful preview explains how to recover without offering acceptance', async () => { + api.preview.mockResolvedValue({ ok: true, value: { ...pending, state: 'expired' } }); + renderPage( + , + ); + expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_channel_link_expired'); + expect( + screen.queryByRole('button', { name: 'com_ui_channel_link_accept' }), + ).not.toBeInTheDocument(); +}); + +test('an unavailable personal connection remains explicitly revocable', async () => { + const user = userEvent.setup(); + api.list.mockResolvedValue([{ ...pending, state: 'unavailable' }]); + renderPage(); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_unavailable'); + await user.click(screen.getByRole('button', { name: 'com_ui_channel_link_revoke' })); + api.list.mockResolvedValue([{ ...pending, state: 'revoked' }]); + await user.click( + within(screen.getByRole('group')).getByRole('button', { name: 'com_ui_channel_link_revoke' }), + ); + expect(api.revoke).toHaveBeenCalledWith('link', 'revision'); + expect(await screen.findByText('com_ui_channel_link_revoked')).toBeInTheDocument(); +}); + +test('a late acceptance failure after unmount does not refetch under a new session', async () => { + const user = userEvent.setup(); + let fail!: (error: Error) => void; + api.accept.mockImplementationOnce( + () => + new Promise((_, reject) => { + fail = reject; + }), + ); + const mounted = renderPage( + , + ); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + mounted.unmount(); + await act(async () => { + fail(new Error('late lost acknowledgement')); + }); + expect(api.preview).toHaveBeenCalledTimes(1); +}); + +test('an earlier in-flight preview cannot roll back successful acceptance', async () => { + const user = userEvent.setup(); + let accept!: (value: Awaited>) => void; + let oldPreview!: (value: Awaited>) => void; + api.accept.mockImplementationOnce( + () => + new Promise((resolve) => { + accept = resolve; + }), + ); + const { client } = renderPage( + , + ); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + api.preview.mockImplementationOnce( + () => + new Promise((resolve) => { + oldPreview = resolve; + }), + ); + act(() => { + void client.invalidateQueries([QueryKeys.channelLinkTicket]); + }); + await waitFor(() => expect(api.preview).toHaveBeenCalledTimes(2)); + api.preview.mockResolvedValue({ ok: true, value: { ...pending, state: 'accepted' } }); + await act(async () => { + accept({ ok: true, value: { ...pending, state: 'accepted' } }); + }); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_confirm_slack'); + await act(async () => { + oldPreview({ ok: true, value: pending }); + }); + expect(screen.getByRole('status')).toHaveTextContent('com_ui_channel_link_confirm_slack'); + expect( + screen.queryByRole('button', { name: 'com_ui_channel_link_accept' }), + ).not.toBeInTheDocument(); +}); + +test('a delayed acceptance acknowledgement cannot replace a newer active preview', async () => { + const user = userEvent.setup(); + let accept!: (value: Awaited>) => void; + api.accept.mockImplementationOnce( + () => + new Promise((resolve) => { + accept = resolve; + }), + ); + const { client } = renderPage( + , + ); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + api.preview.mockResolvedValue({ ok: true, value: { ...pending, state: 'active' } }); + await act(async () => { + await client.invalidateQueries([QueryKeys.channelLinkTicket]); + }); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_active'); + await act(async () => { + accept({ ok: true, value: { ...pending, state: 'accepted' } }); + }); + expect(screen.getByRole('status')).toHaveTextContent('com_ui_channel_link_active'); + expect(screen.queryByText('com_ui_channel_link_confirm_slack')).not.toBeInTheDocument(); +}); + +test('a lost acknowledgement reconciles successful acceptance without offering a duplicate retry', async () => { + const user = userEvent.setup(); + api.accept.mockImplementationOnce(async () => { + api.preview.mockResolvedValue({ ok: true, value: { ...pending, state: 'accepted' } }); + throw new Error('lost acknowledgement'); + }); + renderPage( + , + ); + await user.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_confirm_slack'); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument(); +}); diff --git a/client/src/components/Channels/Link.tsx b/client/src/components/Channels/Link.tsx new file mode 100644 index 0000000000..f1dc9963b6 --- /dev/null +++ b/client/src/components/Channels/Link.tsx @@ -0,0 +1,191 @@ +import { useEffect, useId, useState, useRef } from 'react'; +import { Button, Spinner } from '@librechat/client'; +import { MutationKeys, QueryKeys } from 'librechat-data-provider'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import type { + ChannelIdentityClient, + ChannelIdentityError, + ChannelIdentityResult, + ChannelLinkView, +} from 'librechat-data-provider'; +import type { TranslationKeys } from '~/hooks'; +import { useLocalize } from '~/hooks'; + +export const linkErrorKeys: Record = { + invalid_ticket: 'com_ui_channel_link_invalid', + expired: 'com_ui_channel_link_expired', + changed: 'com_ui_channel_link_changed', + forbidden: 'com_ui_channel_link_forbidden', + already_linked: 'com_ui_channel_link_exists', + confirmation_required: 'com_ui_channel_link_confirm_slack', + revoked: 'com_ui_channel_link_revoked', + unavailable: 'com_ui_channel_link_error', +}; + +interface LinkProps { + api: ChannelIdentityClient; + accountLabel: string; + principalKey: string; + ticket?: string; + enabled?: boolean; + onTicketResult?: (result: ChannelIdentityResult) => void; +} +/** The host owns session and policy readiness; tickets never become query-key material. */ +export default function Link(props: LinkProps) { + return ; +} +function OwnedLink({ + api, + accountLabel, + principalKey, + ticket: suppliedTicket, + onTicketResult, + enabled = true, +}: LinkProps) { + const localize = useLocalize(); + const id = useId(); + const queryClient = useQueryClient(); + const inFlight = useRef(false); + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + const key = [QueryKeys.channelLinkTicket, principalKey, id]; + const [ticket] = useState(() => suppliedTicket ?? window.location.hash.slice(1)); + useEffect(() => { + if (suppliedTicket == null && window.location.hash) { + window.history.replaceState( + window.history.state, + '', + `${window.location.pathname}${window.location.search}`, + ); + } + }, [suppliedTicket]); + const preview = useQuery(key, () => api.preview(ticket), { + enabled: ticket.length > 0 && Boolean(principalKey) && enabled, + retry: false, + cacheTime: 0, + }); + const accept = useMutation({ + mutationKey: [MutationKeys.channelLinkTicket, principalKey, id], + cacheTime: 0, + mutationFn: async () => { + if ( + !mounted.current || + !enabled || + inFlight.current || + preview.isFetching || + preview.isError || + !preview.data?.ok || + preview.data.value.state !== 'pending' || + preview.data.value.expiresAtMs <= Date.now() + ) + throw new Error('Channel link preview is unavailable'); + inFlight.current = true; + try { + return await api.accept({ ticket, expectedRevision: preview.data.value.revision }); + } finally { + inFlight.current = false; + } + }, + onSuccess: async (result) => { + if (!mounted.current) return; + await queryClient.cancelQueries(key); + if (!mounted.current) return; + const current = queryClient.getQueryData>(key); + if (result.ok && current?.ok && current.value.state === 'pending') { + queryClient.setQueryData(key, result); + } + await preview.refetch(); + }, + onError: async () => { + if (!mounted.current) return; + await queryClient.cancelQueries(key); + if (!mounted.current) return; + await preview.refetch(); + }, + }); + const result = preview.data; + useEffect(() => { + if (result) onTicketResult?.(result); + }, [result, onTicketResult]); + const data = result?.ok ? result.value : undefined; + const mutationError = + data?.state === 'pending' && accept.data && !accept.data.ok + ? accept.data.error.code + : undefined; + const error = result && !result.ok ? result.error.code : mutationError; + return ( +
+

+ {localize('com_ui_channel_link_title')} +

+

{localize('com_ui_channel_link_signed_in', { 0: accountLabel })}

+

{localize('com_ui_channel_link_boundary')}

+ {ticket && enabled && preview.isLoading && } + {!ticket &&

{localize('com_ui_channel_link_invalid')}

} + {error &&

{localize(linkErrorKeys[error])}

} + {(preview.isError || (accept.isError && data?.state === 'pending')) && ( +

{localize('com_ui_channel_link_error')}

+ )} + {data && ( +
+
{localize('com_ui_channel_link_workspace')}
+
{data.identity.teamId}
+
{localize('com_ui_channel_link_actor')}
+
{data.identity.externalUserId}
+
{localize('com_ui_channel_link_agent')}
+
{data.identity.agentId}
+
+ )} + {data?.state === 'pending' && ( + + )} + {data?.state === 'accepted' && ( +

{localize('com_ui_channel_link_confirm_slack')}

+ )} + {data?.state === 'expired' &&

{localize('com_ui_channel_link_expired')}

} + {data?.state === 'revoked' &&

{localize('com_ui_channel_link_revoked')}

} + {data?.state === 'unavailable' && ( +

{localize('com_ui_channel_link_unavailable')}

+ )} + {data?.state === 'active' &&

{localize('com_ui_channel_link_active')}

} + {(preview.isError || + (accept.isError && data?.state === 'pending') || + Boolean(mutationError) || + error === 'changed') && ( + + )} +
+ ); +} diff --git a/client/src/components/Channels/Links.tsx b/client/src/components/Channels/Links.tsx new file mode 100644 index 0000000000..2bd426436b --- /dev/null +++ b/client/src/components/Channels/Links.tsx @@ -0,0 +1,111 @@ +import { useId, useState } from 'react'; +import { Button, Spinner } from '@librechat/client'; +import { MutationKeys, QueryKeys } from 'librechat-data-provider'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import type { ChannelIdentityClient, ChannelLinkView } from 'librechat-data-provider'; +import type { TranslationKeys } from '~/hooks'; +import { linkErrorKeys } from './Link'; +import { useLocalize } from '~/hooks'; + +const states: Record = { + pending: 'com_ui_channel_link_pending', + accepted: 'com_ui_channel_link_confirm_slack', + active: 'com_ui_channel_link_active', + revoked: 'com_ui_channel_link_revoked', + expired: 'com_ui_channel_link_expired', + unavailable: 'com_ui_channel_link_unavailable', +}; + +interface LinksProps { + api: ChannelIdentityClient; + principalKey: string; +} +export default function Links(props: LinksProps) { + return ; +} +function OwnedLinks({ api, principalKey }: { api: ChannelIdentityClient; principalKey: string }) { + const localize = useLocalize(); + const id = useId(); + const queryClient = useQueryClient(); + const [confirm, setConfirm] = useState(null); + const key = [QueryKeys.channelLinks, principalKey]; + const links = useQuery(key, () => api.list(), { retry: false, cacheTime: 0 }); + const revoke = useMutation({ + mutationKey: [MutationKeys.channelLinks, principalKey], + mutationFn: (link: ChannelLinkView) => api.revoke(link.linkId, link.revision), + onSuccess: async (_result, link) => { + setConfirm((current) => (current === link.linkId ? null : current)); + await queryClient.invalidateQueries(key); + }, + }); + return ( +
+

+ {localize('com_ui_channel_link_personal')} +

+

{localize('com_ui_channel_link_boundary')}

+ {links.isLoading && } + {links.isError && ( +
+

{localize('com_ui_channel_link_error')}

+ +
+ )} + {revoke.isError &&

{localize('com_ui_channel_link_error')}

} + {revoke.data && !revoke.data.ok && ( +

{localize(linkErrorKeys[revoke.data.error.code])}

+ )} + {links.data?.length === 0 &&

{localize('com_ui_channel_link_empty')}

} + {links.data?.map((link) => ( +
+

+ {localize('com_ui_channel_link_binding', { + 0: link.identity.teamId, + 1: link.identity.externalUserId, + 2: link.identity.agentId, + })} +

+

{localize(states[link.state])}

+ {link.state !== 'revoked' && + (confirm === link.linkId ? ( +
+

{localize('com_ui_channel_link_revoke_confirm')}

+
+ + +
+
+ ) : ( + + ))} +
+ ))} +
+ ); +} diff --git a/client/src/components/Channels/LinksSettings.tsx b/client/src/components/Channels/LinksSettings.tsx new file mode 100644 index 0000000000..58287bdda3 --- /dev/null +++ b/client/src/components/Channels/LinksSettings.tsx @@ -0,0 +1,15 @@ +import { dataService } from 'librechat-data-provider'; +import { useAuthContext } from '~/hooks'; +import Links from './Links'; + +/** Remains revocable when the deployment disables new channel execution. */ +export default function LinksSettings() { + const { user } = useAuthContext(); + if (!user) return null; + return ( + + ); +} diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsx index aafd7688aa..2fa4b27f37 100644 --- a/client/src/components/Nav/Settings/registry.tsx +++ b/client/src/components/Nav/Settings/registry.tsx @@ -42,6 +42,7 @@ import DuringRunAction from '../SettingsTabs/Chat/DuringRunAction'; import DeleteAccount from '../SettingsTabs/Account/DeleteAccount'; import StatefulWorkspaceDefault from './StatefulWorkspaceDefault'; import { ForkSettings } from '../SettingsTabs/Chat/ForkSettings'; +import LinksSettings from '~/components/Channels/LinksSettings'; import ChatDirection from '../SettingsTabs/Chat/ChatDirection'; import { DeleteCache } from '../SettingsTabs/Data/DeleteCache'; import { ManageFiles } from '../SettingsTabs/Data/ManageFiles'; @@ -831,6 +832,14 @@ export const registry: SettingEntry[] = [ Component: Passkeys, }, // Account · Connected accounts + { + id: 'channelLinks', + tab: ACCOUNT, + section: 'connections', + labelKey: 'com_ui_channel_link_personal', + keywords: ['slack', 'channel', 'identity', 'link', 'revoke'], + Component: LinksSettings, + }, { id: 'pullRequestAccount', tab: ACCOUNT, diff --git a/client/src/components/SidePanel/Agents/AgentConfig.tsx b/client/src/components/SidePanel/Agents/AgentConfig.tsx index 87e3ac8858..c9e00247b5 100644 --- a/client/src/components/SidePanel/Agents/AgentConfig.tsx +++ b/client/src/components/SidePanel/Agents/AgentConfig.tsx @@ -13,7 +13,6 @@ import { validateEmail, cn } from '~/utils'; import Instructions from './Instructions'; import FileContext from './FileContext'; import AgentAvatar from './AgentAvatar'; -import Channels from './Channels'; import Starters from './Starters'; import { Panel } from '~/common'; @@ -22,17 +21,9 @@ const fieldClass = 'h-9'; export default function AgentConfig({ instructionsPromptStatus, onRetryInstructionsPrompt, - showChannels = false, - channelsAgentId, - channelsUserId, - channelsTenantId, }: { instructionsPromptStatus?: InstructionsPromptStatus; onRetryInstructionsPrompt?: () => void; - showChannels?: boolean; - channelsAgentId?: string; - channelsUserId?: string; - channelsTenantId?: string; }) { const localize = useLocalize(); const methods = useFormContext(); @@ -177,10 +168,6 @@ export default function AgentConfig({ )} - {showChannels && channelsUserId && ( - - )} - {/* CONVERSATION STARTERS */} diff --git a/client/src/components/SidePanel/Agents/AgentPanel.test.tsx b/client/src/components/SidePanel/Agents/AgentPanel.test.tsx index c4046634ad..ae4cfd8f66 100644 --- a/client/src/components/SidePanel/Agents/AgentPanel.test.tsx +++ b/client/src/components/SidePanel/Agents/AgentPanel.test.tsx @@ -2,10 +2,11 @@ * @jest-environment jsdom */ import * as React from 'react'; +import userEvent from '@testing-library/user-event'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { act, render, screen, waitFor, fireEvent } from '@testing-library/react'; +import type { Agent, TAgentsEndpoint } from 'librechat-data-provider'; import type { UseFormReturn } from 'react-hook-form'; -import type { Agent } from 'librechat-data-provider'; import type { useModelCatalog } from '~/data-provider/Endpoints/models'; import type { AgentForm, AgentModelPanelProps } from '~/common'; import type { InstructionsPromptStatus } from './Instructions'; @@ -47,9 +48,19 @@ let mockAgentConfigStatus: InstructionsPromptStatus | undefined; let mockAgentSelectAgentQueryData: Agent | undefined; let mockUserRole = 'USER'; let mockHasPermission = true; +let mockPermissionBits: number | undefined; +let mockRolePermissions: Record = {}; +let mockChannelsProps: unknown; +let mockPersonalApprovalModesEnabled = true; +type AgentConfigFixture = Pick & { + channels?: Pick, 'enabled'>; +}; let mockAgentPanelContext = { activePanel: 'builder', - agentsConfig: { allowedProviders: [] as string[] }, + agentsConfig: { + allowedProviders: [], + channels: undefined, + } as AgentConfigFixture, setActivePanel: jest.fn(), endpointsConfig: {}, setCurrentAgentId: jest.fn(), @@ -77,6 +88,7 @@ jest.mock('librechat-data-provider', () => { dataService: { createAgent: jest.fn(), updateAgent: jest.fn(), + resetToolApprovalGrants: jest.fn(), }, Tools: actualModule.Tools || { execute_code: 'execute_code', @@ -102,11 +114,7 @@ jest.mock('librechat-data-provider', () => { }); jest.mock('@librechat/client', () => ({ - Button: ({ children, onClick, ...props }: any) => ( - - ), + ...jest.requireActual('@librechat/client'), useToastContext: () => ({ get showToast() { return mockShowToast || jest.fn(); @@ -145,13 +153,20 @@ const mockRevealChat = jest.fn(); jest.mock('~/hooks', () => ({ useSelectAgent: () => ({ onSelect: mockSelectAgent }), + useGetAgentsConfig: () => ({ + agentsConfig: { toolApproval: { agentModes: mockPersonalApprovalModesEnabled } }, + }), useLocalize: () => (key: string) => key, + useHasAccess: ({ permissionType }: { permissionType: string }) => + mockRolePermissions[permissionType] !== false, useAuthContext: () => ({ user: { id: 'user-123', role: mockUserRole } }), })); jest.mock('~/hooks/useResourcePermissions', () => ({ useResourcePermissions: () => ({ - hasPermission: jest.fn(() => mockHasPermission), + hasPermission: jest.fn((required: number) => + mockPermissionBits == null ? mockHasPermission : (mockPermissionBits & required) === required, + ), isLoading: false, }), })); @@ -182,6 +197,13 @@ jest.mock('./Advanced/AdvancedPanel', () => ({ default: () =>
{`Advanced Panel`}
, })); +jest.mock('./Channels', () => ({ + __esModule: true, + default: (props: unknown) => { + mockChannelsProps = props; + return
; + }, +})); jest.mock('./AgentConfig', () => ({ __esModule: true, default: (props: { instructionsPromptStatus?: InstructionsPromptStatus }) => { @@ -256,7 +278,7 @@ jest.mock('react-hook-form', () => { }); // Import after mocks -import { Providers, dataService } from 'librechat-data-provider'; +import { Providers, dataService, PermissionTypes, PermissionBits } from 'librechat-data-provider'; import { useGetAgentByIdQuery, useGetExpandedAgentByIdQuery } from '~/data-provider'; import AgentPanel from './AgentPanel'; @@ -354,11 +376,16 @@ describe('AgentPanel - Update Agent Toast Messages', () => { mockAgentSelectAgentQueryData = undefined; mockUserRole = 'USER'; mockHasPermission = true; + mockPermissionBits = undefined; + mockRolePermissions = {}; + mockChannelsProps = undefined; + mockPersonalApprovalModesEnabled = true; + jest.mocked(dataService.resetToolApprovalGrants).mockResolvedValue({ reset: true }); mockFormDefaults = {}; mockModelsQuery = createModelsQuery({ openai: ['gpt-4'] }); mockAgentPanelContext = { activePanel: 'builder', - agentsConfig: { allowedProviders: [] }, + agentsConfig: { allowedProviders: [], channels: undefined }, setActivePanel: jest.fn(), endpointsConfig: { openai: {} }, setCurrentAgentId: jest.fn(), @@ -369,6 +396,79 @@ describe('AgentPanel - Update Agent Toast Messages', () => { }); describe('AgentPanel', () => { + it.each([ + [PermissionBits.SHARE, true, true], + [PermissionBits.SHARE, false, true], + [PermissionBits.SHARE, true, false], + [PermissionBits.VIEW, true, true], + ] as const)( + 'keeps personal consent independent from channels and editing: bits=%s enabled=%s remote=%s', + async (bits, channelsEnabled, remote) => { + const { mockUseGetAgentByIdQuery } = setupMocks(); + mockAgentQuery(mockUseGetAgentByIdQuery, { author: 'other-user' }); + mockPermissionBits = bits; + mockRolePermissions = { [PermissionTypes.REMOTE_AGENTS]: remote }; + mockAgentPanelContext = { + ...mockAgentPanelContext, + agentsConfig: { allowedProviders: [], channels: { enabled: channelsEnabled } }, + }; + const user = userEvent.setup(); + const mounted = render(, { wrapper: createWrapper() }); + const managesChannels = bits === PermissionBits.SHARE && channelsEnabled && remote; + await waitFor(() => + expect(Boolean(mounted.queryByTestId('channel-controls'))).toBe(managesChannels), + ); + expect(mounted.queryByTestId('save-agent-button')).not.toBeInTheDocument(); + expect(mockAgentConfigStatus).toBeUndefined(); + const reset = await mounted.findByRole('button', { name: 'com_ui_tool_approval_reset' }); + expect(reset).toBeEnabled(); + expect(Boolean(mounted.queryByText('com_agents_not_available'))).toBe(!managesChannels); + await user.click(reset); + await user.click(mounted.getByRole('menuitem', { name: 'com_ui_tool_approval_reset' })); + await waitFor(() => + expect(dataService.resetToolApprovalGrants).toHaveBeenCalledWith({ + agentId: 'agent-123', + }), + ); + }, + ); + + it.each([ + ['USER', PermissionBits.EDIT | PermissionBits.SHARE, true, true, true], + ['USER', PermissionBits.EDIT, true, true, false], + ['USER', PermissionBits.SHARE, true, true, true], + ['ADMIN', 0, true, true, true], + ['ADMIN', 0, false, true, false], + ['USER', PermissionBits.EDIT | PermissionBits.SHARE, true, false, false], + ] as const)( + 'matches channel management role/ACL visibility: %s bits=%s', + async (role, bits, remote, agents, visible) => { + const { mockUseGetAgentByIdQuery } = setupMocks(); + mockAgentQuery(mockUseGetAgentByIdQuery, {}); + mockUserRole = role; + mockPermissionBits = bits; + mockRolePermissions = { + [PermissionTypes.REMOTE_AGENTS]: remote, + [PermissionTypes.AGENTS]: agents, + }; + mockAgentPanelContext = { + ...mockAgentPanelContext, + agentsConfig: { allowedProviders: [], channels: { enabled: true } }, + }; + const Wrapper = createWrapper(); + const mounted = render(, { wrapper: Wrapper }); + await waitFor(() => + expect(Boolean(mounted.queryByTestId('channel-controls'))).toBe(visible), + ); + if (visible) + expect(mockChannelsProps).toEqual({ + agentId: 'agent-123', + userId: 'user-123', + tenantId: undefined, + }); + }, + ); + it('restores saved defaults from the current model catalogue', async () => { const { mockUseGetAgentByIdQuery } = setupMocks(); mockAgentQuery(mockUseGetAgentByIdQuery, {}); @@ -1481,7 +1581,7 @@ describe('AgentPanel - Select Agent', () => { mockModelsQuery = createModelsQuery({ openai: ['gpt-4'] }); mockAgentPanelContext = { activePanel: 'builder', - agentsConfig: { allowedProviders: [] }, + agentsConfig: { allowedProviders: [], channels: undefined }, setActivePanel: jest.fn(), endpointsConfig: { openai: {} }, setCurrentAgentId: jest.fn(), diff --git a/client/src/components/SidePanel/Agents/AgentPanel.tsx b/client/src/components/SidePanel/Agents/AgentPanel.tsx index b2d79ac6a2..4ecc2afdac 100644 --- a/client/src/components/SidePanel/Agents/AgentPanel.tsx +++ b/client/src/components/SidePanel/Agents/AgentPanel.tsx @@ -10,6 +10,8 @@ import { EModelEndpoint, LocalStorageKeys, PermissionBits, + PermissionTypes, + Permissions, removeCodeExecutionCaller, resolveModelCatalogKey, resolveStatefulCodeEnvironment, @@ -39,8 +41,8 @@ import { getDefaultAgentFormValues, } from '~/utils'; import { pruneAgentModelParameters, resolveAgentParameterSettings } from './parameters'; +import { useSelectAgent, useLocalize, useAuthContext, useHasAccess } from '~/hooks'; import { useResourcePermissions } from '~/hooks/useResourcePermissions'; -import { useSelectAgent, useLocalize, useAuthContext } from '~/hooks'; import { useAgentPanelContext } from '~/Providers/AgentPanelContext'; import { resolveCapabilityTools } from './Tools/items/capabilities'; import { useModelCatalog } from '~/data-provider/Endpoints/models'; @@ -52,6 +54,7 @@ import AgentConfig from './AgentConfig'; import AgentSelect from './AgentSelect'; import AgentFooter from './AgentFooter'; import ModelPanel from './ModelPanel'; +import Channels from './Channels'; /* Helpers */ function getUpdateToastMessage( @@ -465,6 +468,14 @@ export const mayHavePersistedChange = ( export default function AgentPanel() { const localize = useLocalize(); const { user } = useAuthContext(); + const canUseAgents = useHasAccess({ + permissionType: PermissionTypes.AGENTS, + permission: Permissions.USE, + }); + const canUseRemoteAgents = useHasAccess({ + permissionType: PermissionTypes.REMOTE_AGENTS, + permission: Permissions.USE, + }); const { showToast } = useToastContext(); const { activePanel, @@ -1014,6 +1025,17 @@ export default function AgentPanel() { return hasEditorAccess; }, [agentQuery.data?.id, hasEditorAccess]); + const showChannels = + activePanel === Panel.builder && + !agentQuery.isInitialLoading && + Boolean(user?.id) && + agentsConfig?.channels?.enabled === true && + canUseAgents && + canUseRemoteAgents && + (!isPersistedAgent || + user?.role === SystemRoles.ADMIN || + (!permissionsLoading && hasPermission(PermissionBits.SHARE))); + return (
{agentQuery.isInitialLoading && } {!canEditAgent && !agentQuery.isInitialLoading && ( -
+
-

- {localize('com_agents_not_available')} -

-

{localize('com_agents_no_access')}

+ {!showChannels && ( + <> +

+ {localize('com_agents_not_available')} +

+

{localize('com_agents_no_access')}

+ + )} {agentQuery.data?.id && }
@@ -1111,6 +1143,13 @@ export default function AgentPanel() { onRetryInstructionsPrompt={retryInstructionsPrompt} /> )} + {showChannels && user?.id && ( + + )} {canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.advanced && ( )} diff --git a/client/src/hooks/useOwnerActionPolicy.tsx b/client/src/hooks/useOwnerActionPolicy.tsx new file mode 100644 index 0000000000..9c7eaf8925 --- /dev/null +++ b/client/src/hooks/useOwnerActionPolicy.tsx @@ -0,0 +1,41 @@ +import TermsAndConditionsModal from '~/components/ui/TermsAndConditionsModal'; +import { useUserTermsQuery, useGetStartupConfig } from '~/data-provider'; +import { useAuthContext } from '~/hooks'; + +/** UI readiness for an authenticated owner-scoped host; the server enforces authorization. */ +export function useOwnerActionPolicy() { + const { logout } = useAuthContext(); + const config = useGetStartupConfig({ refetchOnMount: 'always', retry: false }); + const termsConfig = config.data?.interface?.termsOfService; + const requiresTerms = termsConfig?.modalAcceptance === true; + const terms = useUserTermsQuery({ + enabled: requiresTerms && config.isSuccess && !config.isFetching, + refetchOnMount: 'always', + retry: false, + }); + const termsReady = + config.isSuccess && + !config.isFetching && + (!requiresTerms || (terms.isSuccess && !terms.isFetching && terms.data.termsAccepted)); + const policyError = config.isError || (requiresTerms && terms.isError); + return { config, terms, termsConfig, requiresTerms, termsReady, policyError, logout }; +} + +export function OwnerTermsModal({ + policy, + onAccepted, +}: { + policy: ReturnType; + onAccepted?: () => void; +}) { + return ( + undefined} + onAccept={onAccepted ?? (() => undefined)} + onDecline={() => policy.logout('/login?redirect=false')} + title={policy.termsConfig?.modalTitle} + modalContent={policy.termsConfig?.modalContent} + /> + ); +} diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index ff21797b15..dca1a15fa8 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -30,6 +30,28 @@ "com_ui_channel_link_mode_confirm": "Change identity mode? Existing links and pending requests will no longer authorize execution. Activate the channel again after the change.", "com_ui_channel_link_switch_per_user": "Switch to per-user accounts", "com_ui_channel_link_switch_shared": "Switch to channel owner only", + "com_ui_channel_link_title": "Link your Slack identity", + "com_ui_channel_link_signed_in": "Signed in as {{0}}", + "com_ui_channel_link_boundary": "Linked requests use your account and permissions. Linking does not authorize new tools or grant offline access to connected services. You can revoke the link at any time.", + "com_ui_channel_link_invalid": "This link is invalid. Request a new link from the Slack agent.", + "com_ui_channel_link_expired": "This link has expired. Request a new link from the Slack agent.", + "com_ui_channel_link_changed": "The link or channel changed. Reload before continuing.", + "com_ui_channel_link_forbidden": "You cannot link this account to this channel. Check your organization and agent access.", + "com_ui_channel_link_exists": "This Slack identity is already linked or awaiting confirmation.", + "com_ui_channel_link_confirm_slack": "Accepted here. Return to Slack and confirm from the same Slack account to activate the link. Send the agent another message if you need the confirmation prompt.", + "com_ui_channel_link_revoked": "Revoked", + "com_ui_channel_link_error": "Couldn't update the account link. Try again.", + "com_ui_channel_link_workspace": "Slack workspace", + "com_ui_channel_link_actor": "Slack account ID", + "com_ui_channel_link_agent": "Agent", + "com_ui_channel_link_accept": "Accept this account link", + "com_ui_channel_link_active": "Active", + "com_ui_channel_link_pending": "Pending acceptance", + "com_ui_channel_link_personal": "Your channel account links", + "com_ui_channel_link_empty": "You have no linked channel accounts.", + "com_ui_channel_link_binding": "Workspace {{0}} · Slack account {{1}} · Agent {{2}}", + "com_ui_channel_link_revoke": "Revoke link", + "com_ui_channel_link_revoke_confirm": "Revoke this link? New requests and continuations must link again. Actions already completed are not undone.", "com_ui_channels_title": "Channels", "com_ui_channels_slack": "Slack", "com_ui_channels_shared_notice": "Owner-only mode: the Slack sender must link and confirm the channel creator's account. Other Slack users cannot inherit that account's permissions by joining a thread. Use per-user mode for multiple users.", @@ -37,19 +59,24 @@ "com_ui_channels_active": "Active", "com_ui_channels_disabled": "Disabled", "com_ui_channels_deleting": "Deleting", + "com_ui_channels_workspace": "Workspace: {{0}}", "com_ui_channels_action_error": "Couldn't update this channel. Check the configuration and try again.", "com_ui_channels_setup": "Continue setup", "com_ui_channels_manage": "Manage connection", "com_ui_channels_setup_title": "Connect to Slack", "com_ui_channels_install_step": "1. Install the Slack app", "com_ui_channels_credentials_step": "Add Credentials", + "com_ui_channels_download_manifest": "Download manifest", "com_ui_channels_description": "Connect this Agent to messaging apps through a compatible gateway.", "com_ui_channels_save_first": "Save this Agent to configure channels.", + "com_ui_channels_gateway_required": "Your administrator must run a compatible channel gateway.", "com_ui_channels_per_user_help": "Each person uses their own account and permissions.", "com_ui_channels_owner_help": "Only you can use this connection, with your account and permissions.", "com_ui_channels_connection_type": "Connection type:", "com_ui_channels_connection_id_label": "Connection ID", "com_ui_channels_workspace_label": "Workspace", + "com_ui_channels_connection_id": "Connection ID: {{0}}", + "com_ui_channels_replace_notice": "Disable this connection before replacing credentials or changing account access.", "com_ui_channels_disable": "Disable", "com_ui_channels_delete_confirm": "Delete this channel and its stored credentials? The Slack app is not uninstalled.", "com_ui_channels_instructions": "Create a Slack app from this manifest, install it in your workspace, then enter its app ID and bot token. Activation validates the credentials with Slack.", @@ -57,6 +84,7 @@ "com_ui_channels_manifest_error": "Couldn't load the app manifest.", "com_ui_channels_retry": "Try again", "com_ui_channels_manifest": "Slack app manifest", + "com_ui_channels_manifest_reset": "Reset to generated manifest", "com_ui_channels_app_id": "Slack app ID", "com_ui_channels_bot_token": "Bot token", "com_ui_channels_signing_secret": "Signing secret", @@ -3864,5 +3892,6 @@ "com_ui_code_setup_deny": "Deny setup", "com_ui_code_setup_saving": "Saving your decision…", "com_ui_terms_accept_failed": "Could not accept the terms. Please try again.", - "com_ui_channels_read_only": "Managed by another account" + "com_ui_channels_read_only": "Managed by another account", + "com_ui_channel_link_unavailable": "This connection is unavailable. You can still disconnect this account." } diff --git a/client/src/routes/ChannelLinkRoute.tsx b/client/src/routes/ChannelLinkRoute.tsx new file mode 100644 index 0000000000..2a5be9ba0a --- /dev/null +++ b/client/src/routes/ChannelLinkRoute.tsx @@ -0,0 +1,198 @@ +import { useCallback, useEffect, useState } from 'react'; +import { Button, Spinner } from '@librechat/client'; +import { Navigate, useLocation, useNavigate } from 'react-router-dom'; +import { buildLoginRedirectUrl, channelConfigSchema, dataService } from 'librechat-data-provider'; +import type { ChannelIdentityResult, ChannelLinkView } from 'librechat-data-provider'; +import { useOwnerActionPolicy, OwnerTermsModal } from '~/hooks/useOwnerActionPolicy'; +import { AuthContextProvider } from '~/hooks/AuthContext'; +import { useAuthContext, useLocalize } from '~/hooks'; +import Link from '~/components/Channels/Link'; + +const storageKey = 'channel_link_pending_ticket'; +const maxAgeMs = channelConfigSchema.shape.ticketLifetimeMs.removeDefault().maxValue ?? 0; +interface PendingTicket { + ticket: string; + savedAt: number; + expiresAtMs: number; +} + +function fromFragment(fragment: string): PendingTicket | undefined { + if (!/^[A-Za-z0-9_-]{43}$/.test(fragment)) return undefined; + const savedAt = Date.now(); + return { ticket: fragment, savedAt, expiresAtMs: savedAt + maxAgeMs }; +} + +function initialTicket(): PendingTicket | undefined { + const fragment = window.location.hash.slice(1); + if (fragment) return fromFragment(fragment); + try { + const saved = JSON.parse(window.sessionStorage.getItem(storageKey) ?? 'null'); + if ( + saved && + typeof saved.ticket === 'string' && + /^[A-Za-z0-9_-]{43}$/.test(saved.ticket) && + Number.isSafeInteger(saved.savedAt) && + saved.savedAt <= Date.now() && + Date.now() - saved.savedAt < maxAgeMs + ) { + const expiresAtMs = saved.expiresAtMs ?? saved.savedAt + maxAgeMs; + if (Number.isSafeInteger(expiresAtMs) && expiresAtMs > Date.now()) + return { + ticket: saved.ticket, + savedAt: saved.savedAt, + expiresAtMs: Math.min(expiresAtMs, saved.savedAt + maxAgeMs), + }; + } + window.sessionStorage.removeItem(storageKey); + } catch { + /* Invalid or blocked tab storage is treated as an absent ticket. */ + } + return undefined; +} + +function AuthenticatedLink({ + ticket, + onResult, +}: { + ticket: string; + onResult: (result: ChannelIdentityResult) => void; +}) { + const { user, isAuthenticated, isAuthReady } = useAuthContext(); + const location = useLocation(); + if (!isAuthReady) return ; + if (!isAuthenticated) + return ( + + ); + if (!user?.id) return ; + const principalKey = JSON.stringify([user.tenantId ?? '_', user.id]); + return ( + + ); +} + +function OwnedLink({ + principalKey, + accountLabel, + ticket, + onResult, +}: { + principalKey: string; + accountLabel: string; + ticket: string; + onResult: (result: ChannelIdentityResult) => void; +}) { + const localize = useLocalize(); + const policy = useOwnerActionPolicy(); + const { config, terms, requiresTerms, termsReady, policyError } = policy; + return ( + <> + {policyError && ( +
+

{localize('com_ui_channel_link_error')}

+ +
+ )} + {!policyError && !termsReady && !(requiresTerms && terms.data?.termsAccepted === false) && ( + + )} + + + + ); +} + +/** Clears the fragment before AuthContext can turn the return path into a login query. */ +export default function ChannelLinkRoute() { + const [pending, setPending] = useState(initialTicket); + const location = useLocation(); + const navigate = useNavigate(); + useEffect(() => { + if (!location.hash) return; + const next = fromFragment(location.hash.slice(1)); + setPending(next); + try { + if (next) window.sessionStorage.setItem(storageKey, JSON.stringify(next)); + else window.sessionStorage.removeItem(storageKey); + } catch { + /* Sign-in remains possible; blocked storage requires requesting another ticket. */ + } + // Update both native history and router location before any auth redirect can read it. + navigate({ pathname: location.pathname, search: location.search, hash: '' }, { replace: true }); + }, [location.hash, location.pathname, location.search, navigate]); + useEffect(() => { + if (!pending) return; + const timer = window.setTimeout( + () => { + setPending((current) => (current?.ticket === pending.ticket ? undefined : current)); + try { + const saved = JSON.parse(window.sessionStorage.getItem(storageKey) ?? 'null'); + if (saved?.ticket === pending.ticket) window.sessionStorage.removeItem(storageKey); + } catch { + /* Tab storage may be unavailable. */ + } + }, + Math.max(0, pending.expiresAtMs - Date.now()), + ); + return () => window.clearTimeout(timer); + }, [pending]); + const onResult = useCallback( + (result: ChannelIdentityResult) => { + if (!pending) return; + const terminal = result.ok + ? result.value.state !== 'pending' || result.value.expiresAtMs <= Date.now() + : ['invalid_ticket', 'revoked', 'expired'].includes(result.error.code); + const expiry = result.ok ? result.value.expiresAtMs : undefined; + const next = + !terminal && expiry != null && Number.isSafeInteger(expiry) + ? { ...pending, expiresAtMs: Math.min(pending.expiresAtMs, expiry) } + : pending; + try { + const saved = JSON.parse(window.sessionStorage.getItem(storageKey) ?? 'null'); + if (saved?.ticket === pending.ticket) { + if (terminal) window.sessionStorage.removeItem(storageKey); + else window.sessionStorage.setItem(storageKey, JSON.stringify(next)); + } + } catch { + /* An in-memory ticket remains usable without exporting it to a URL. */ + } + if (next.expiresAtMs !== pending.expiresAtMs) + setPending((current) => (current?.ticket === pending.ticket ? next : current)); + }, + [pending], + ); + if (location.hash) return ; + return ( + + + + ); +} diff --git a/client/src/routes/ResponseReviewRoute.tsx b/client/src/routes/ResponseReviewRoute.tsx index 2eff571684..fcb6cd2fcf 100644 --- a/client/src/routes/ResponseReviewRoute.tsx +++ b/client/src/routes/ResponseReviewRoute.tsx @@ -1,8 +1,7 @@ import { Button, Spinner } from '@librechat/client'; import { buildLoginRedirectUrl } from 'librechat-data-provider'; import { Navigate, useLocation, useParams } from 'react-router-dom'; -import TermsAndConditionsModal from '~/components/ui/TermsAndConditionsModal'; -import { useUserTermsQuery, useGetStartupConfig } from '~/data-provider'; +import { useOwnerActionPolicy, OwnerTermsModal } from '~/hooks/useOwnerActionPolicy'; import { useResponseReview } from '~/data-provider/Responses'; import { AuthContextProvider } from '~/hooks/AuthContext'; import Controls from '~/components/Responses/Controls'; @@ -20,20 +19,8 @@ function OwnedReview({ tenantId?: string; }) { const localize = useLocalize(); - const { logout } = useAuthContext(); - const config = useGetStartupConfig({ refetchOnMount: 'always', retry: false }); - const termsConfig = config.data?.interface?.termsOfService; - const requiresTerms = termsConfig?.modalAcceptance === true; - const terms = useUserTermsQuery({ - enabled: requiresTerms && config.isSuccess && !config.isFetching, - refetchOnMount: 'always', - retry: false, - }); - const termsReady = - config.isSuccess && - !config.isFetching && - (!requiresTerms || (terms.isSuccess && !terms.isFetching && terms.data.termsAccepted)); - const policyError = config.isError || (requiresTerms && terms.isError); + const policy = useOwnerActionPolicy(); + const { config, terms, requiresTerms, termsReady, policyError } = policy; const query = useResponseReview(responseId, userId, tenantId); const review = query.data; const readError = query.isError || (!query.isLoading && !review); @@ -105,15 +92,11 @@ function OwnedReview({

{localize('com_ui_response_review_return')}

)} - undefined} - onAccept={() => { + { void query.refetch(); }} - onDecline={() => logout('/login?redirect=false')} - title={termsConfig?.modalTitle} - modalContent={termsConfig?.modalContent} /> ); diff --git a/client/src/routes/__tests__/ChannelLinkRoute.spec.tsx b/client/src/routes/__tests__/ChannelLinkRoute.spec.tsx new file mode 100644 index 0000000000..95921c3a28 --- /dev/null +++ b/client/src/routes/__tests__/ChannelLinkRoute.spec.tsx @@ -0,0 +1,406 @@ +import React from 'react'; +import { RecoilRoot } from 'recoil'; +import { ToastProvider } from '@librechat/client'; +import userEvent from '@testing-library/user-event'; +import { BrowserRouter, Routes, Route } from 'react-router-dom'; +import { act, render, screen, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { request, channelConfigSchema, dataService } from 'librechat-data-provider'; +import type { ChannelLinkView } from 'librechat-data-provider'; +import ChannelLinkRoute from '../ChannelLinkRoute'; +import { useAuthContext } from '~/hooks'; +import store from '~/store'; + +jest.mock('librechat-data-provider', () => { + const actual = jest.requireActual('librechat-data-provider'); + return { + ...actual, + dataService: { + ...actual.dataService, + getStartupConfig: jest.fn(), + getUserTerms: jest.fn(), + acceptTerms: jest.fn(), + }, + }; +}); +jest.mock( + '~/components/Chat/Messages/Content/MarkdownLite', + () => + ({ content }: { content: string }) =>

{content}

, +); +const mockAuthUrls: string[] = []; +jest.mock('~/hooks', () => ({ + useAuthContext: jest.fn(), + useLocalize: () => (key: string) => key, +})); +jest.mock('~/hooks/AuthContext', () => ({ + AuthContextProvider: ({ children }: { children: React.ReactNode }) => { + mockAuthUrls.push(globalThis.window.location.href); + return <>{children}; + }, +})); +const ticket = 'Ab_-09'.repeat(8).slice(0, 43); +const nextTicket = 'Zy_-87'.repeat(8).slice(0, 43); +const storageKey = 'channel_link_pending_ticket'; +const maxAgeMs = channelConfigSchema.shape.ticketLifetimeMs.removeDefault().maxValue!; +let pending: ChannelLinkView; +let post: jest.SpyInstance; +function authenticated(value = true) { + jest.mocked(useAuthContext).mockReturnValue({ + user: value ? { id: 'user-a', tenantId: 'tenant', email: 'account@example.com' } : undefined, + isAuthenticated: value, + isAuthReady: true, + logout: jest.fn(), + } as unknown as ReturnType); +} +function savedTicket() { + return JSON.parse(sessionStorage.getItem(storageKey) ?? 'null'); +} +function renderRoute() { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + logger: { log: () => {}, warn: () => {}, error: () => {} }, + }); + const tree = () => ( + + { + set(store.queriesEnabled, true); + set(store.user, jest.mocked(useAuthContext)().user as never); + }} + > + + + + } /> + } /> + + + + + + ); + const mounted = render(tree()); + return { ...mounted, client, rerenderRoute: () => mounted.rerender(tree()) }; +} + +beforeEach(() => { + mockAuthUrls.length = 0; + sessionStorage.clear(); + window.history.replaceState({}, '', '/channels/link'); + authenticated(false); + jest + .mocked(dataService.getStartupConfig) + .mockReset() + .mockResolvedValue({ interface: {} } as never); + jest + .mocked(dataService.getUserTerms) + .mockReset() + .mockResolvedValue({ termsAccepted: true, termsAcceptedAt: '2030-01-01' }); + jest + .mocked(dataService.acceptTerms) + .mockReset() + .mockResolvedValue({ message: 'Accepted', termsAcceptedAt: '2030-01-01' }); + pending = { + identity: { + tenantId: 'tenant', + channelId: 'channel', + channelRevision: 'c-rev', + teamId: 'T1', + externalUserId: 'U1', + agentId: 'agent', + }, + linkId: 'link', + revision: 'revision', + state: 'pending', + expiresAtMs: Date.now() + 60_000, + }; + post = jest.spyOn(request, 'post').mockImplementation(async (url) => { + if (String(url).endsWith('/accept')) pending = { ...pending, state: 'accepted' }; + return { ok: true, value: pending }; + }); +}); +afterEach(() => { + jest.restoreAllMocks(); + jest.useRealTimers(); +}); + +test('preserves mixed-case tickets across login and sends exact POST bodies, never redirect URLs', async () => { + window.history.replaceState({}, '', `/channels/link#${ticket}`); + const first = renderRoute(); + await screen.findByTestId('login'); + expect(mockAuthUrls.length).toBeGreaterThan(0); + expect(mockAuthUrls.every((url) => !url.includes(ticket))).toBe(true); + expect(window.location.href).not.toContain(ticket); + expect(new URLSearchParams(window.location.search).get('redirect_to')).toBe('/channels/link'); + expect(savedTicket().ticket).toBe(ticket); + expect(post).not.toHaveBeenCalled(); + first.unmount(); + window.history.replaceState({}, '', '/channels/link'); + authenticated(); + renderRoute(); + await screen.findByText('U1'); + expect(post).toHaveBeenCalledWith('/api/channels/links/preview', { ticket }); + expect(savedTicket()).toMatchObject({ ticket, expiresAtMs: pending.expiresAtMs }); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_channel_link_accept' })); + expect(await screen.findByRole('status')).toHaveTextContent('com_ui_channel_link_confirm_slack'); + expect(post).toHaveBeenCalledWith('/api/channels/links/accept', { ticket, revision: 'revision' }); + expect(post.mock.calls.every(([url]) => !String(url).includes(ticket))).toBe(true); + await waitFor(() => expect(savedTicket()).toBeNull()); +}); + +test('a ticket older than the default lifetime can still reach authoritative preview', async () => { + sessionStorage.setItem( + storageKey, + JSON.stringify({ ticket, savedAt: Date.now() - 11 * 60 * 1000 }), + ); + authenticated(); + renderRoute(); + await screen.findByText('U1'); + expect(post).toHaveBeenCalledWith('/api/channels/links/preview', { ticket }); +}); + +test('authenticated reload retains an unconsumed ticket and authoritative expiry', async () => { + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + const first = renderRoute(); + await screen.findByText('U1'); + await waitFor(() => expect(savedTicket().expiresAtMs).toBe(pending.expiresAtMs)); + first.unmount(); + renderRoute(); + await screen.findByText('U1'); + expect(post).toHaveBeenCalledTimes(2); + expect(savedTicket().ticket).toBe(ticket); +}); + +test('transient preview 401 retains the ticket for sign-in and retry', async () => { + authenticated(); + post.mockRejectedValueOnce({ response: { status: 401 } }); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + const first = renderRoute(); + expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_channel_link_error'); + expect(savedTicket().ticket).toBe(ticket); + first.unmount(); + authenticated(false); + const login = renderRoute(); + await screen.findByTestId('login'); + expect(window.location.href).not.toContain(ticket); + login.unmount(); + window.history.replaceState({}, '', '/channels/link'); + authenticated(); + renderRoute(); + await screen.findByText('U1'); + expect(post).toHaveBeenLastCalledWith('/api/channels/links/preview', { ticket }); +}); + +test('same-route fragment replacement uses only the new exact ticket', async () => { + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + renderRoute(); + await screen.findByText('U1'); + act(() => { + window.history.pushState({}, '', `/channels/link#${nextTicket}`); + window.dispatchEvent(new PopStateEvent('popstate')); + }); + await waitFor(() => + expect(post).toHaveBeenLastCalledWith('/api/channels/links/preview', { ticket: nextTicket }), + ); + expect(window.location.hash).toBe(''); + expect(savedTicket().ticket).toBe(nextTicket); + await userEvent.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + await waitFor(() => + expect(post).toHaveBeenCalledWith('/api/channels/links/accept', { + ticket: nextTicket, + revision: 'revision', + }), + ); + expect(mockAuthUrls.every((url) => !url.includes('#'))).toBe(true); +}); + +test('a late preview for the replaced ticket cannot alter the new tab entry', async () => { + authenticated(); + let resolveOld: (value: { ok: true; value: ChannelLinkView }) => void = () => {}; + post.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveOld = resolve; + }), + ); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + renderRoute(); + await waitFor(() => expect(post).toHaveBeenCalledTimes(1)); + act(() => { + window.history.pushState({}, '', `/channels/link#${nextTicket}`); + window.dispatchEvent(new PopStateEvent('popstate')); + }); + await screen.findByText('U1'); + await act(async () => resolveOld({ ok: true, value: { ...pending, state: 'accepted' } })); + expect(savedTicket().ticket).toBe(nextTicket); +}); + +test('authoritative expiry clears an unconsumed ticket while the page stays open', async () => { + jest.useFakeTimers(); + authenticated(); + pending.expiresAtMs = Date.now() + 1000; + window.history.replaceState({}, '', `/channels/link#${ticket}`); + renderRoute(); + await waitFor(() => expect(savedTicket().expiresAtMs).toBe(pending.expiresAtMs)); + expect(screen.getByRole('button', { name: 'com_ui_channel_link_accept' })).toBeInTheDocument(); + await act(async () => { + await jest.advanceTimersByTimeAsync(1000); + }); + expect(savedTicket()).toBeNull(); + expect( + screen.queryByRole('button', { name: 'com_ui_channel_link_accept' }), + ).not.toBeInTheDocument(); +}); + +test.each(['maximum', 'authoritative'])('expired %s tab ticket cannot be reused', async (kind) => { + sessionStorage.setItem( + storageKey, + JSON.stringify({ + ticket, + savedAt: Date.now() - (kind === 'maximum' ? maxAgeMs + 1 : 100), + ...(kind === 'authoritative' ? { expiresAtMs: Date.now() - 1 } : {}), + }), + ); + authenticated(); + renderRoute(); + expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_channel_link_invalid'); + expect(savedTicket()).toBeNull(); + expect(post).not.toHaveBeenCalled(); +}); + +test.each(['expired', 'revoked', 'invalid_ticket'] as const)( + 'server %s clears persisted ticket', + async (code) => { + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + post.mockResolvedValueOnce({ ok: false, error: { code } }); + renderRoute(); + await screen.findByRole('alert'); + await waitFor(() => expect(savedTicket()).toBeNull()); + }, +); + +test('blocked storage never puts the ticket into the login URL', async () => { + jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('Blocked', 'SecurityError'); + }); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + const first = renderRoute(); + await screen.findByTestId('login'); + expect(window.location.href).not.toContain(ticket); + expect(mockAuthUrls.every((url) => !url.includes(ticket))).toBe(true); + expect(post).not.toHaveBeenCalled(); + first.unmount(); + window.history.replaceState({}, '', '/channels/link'); + authenticated(); + renderRoute(); + expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_channel_link_invalid'); +}); + +test('blocked storage permits an already-authenticated in-memory ticket', async () => { + jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('Blocked', 'SecurityError'); + }); + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + renderRoute(); + await screen.findByText('U1'); + expect(post).toHaveBeenCalledWith('/api/channels/links/preview', { ticket }); + expect(window.location.hash).toBe(''); +}); + +test('waits beyond the old redirect timeout for a restored session while keeping the ticket private', async () => { + window.history.replaceState({}, '', `/channels/link#${ticket}`); + jest.mocked(useAuthContext).mockReturnValue({ + user: undefined, + isAuthenticated: false, + isAuthReady: false, + logout: jest.fn(), + } as unknown as ReturnType); + const mounted = renderRoute(); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 350)); + }); + expect(screen.queryByTestId('login')).not.toBeInTheDocument(); + expect(post).not.toHaveBeenCalled(); + expect(window.location.href).not.toContain(ticket); + authenticated(); + mounted.rerenderRoute(); + expect(await screen.findByText('U1')).toBeInTheDocument(); + expect(post).toHaveBeenCalledWith('/api/channels/links/preview', { ticket }); +}); + +test('uses the actual terms modal before preview or acceptance can send a POST', async () => { + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + jest.mocked(dataService.getStartupConfig).mockResolvedValue({ + interface: { termsOfService: { modalAcceptance: true, modalContent: 'Current terms' } }, + } as never); + jest + .mocked(dataService.getUserTerms) + .mockResolvedValue({ termsAccepted: false, termsAcceptedAt: null }); + renderRoute(); + const accept = await screen.findByRole('button', { name: 'com_ui_accept' }); + expect(post).not.toHaveBeenCalled(); + await userEvent.click(accept); + expect(dataService.acceptTerms).toHaveBeenCalledTimes(1); + await screen.findByText('U1'); + expect(post).toHaveBeenCalledTimes(1); + expect(post).toHaveBeenCalledWith('/api/channels/links/preview', { ticket }); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_channel_link_accept' })); + expect(post).toHaveBeenCalledWith('/api/channels/links/accept', { ticket, revision: 'revision' }); +}); + +test.each(['config', 'terms'] as const)( + 'blocks private POSTs until a failed %s read succeeds', + async (failed) => { + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + jest + .mocked(dataService.getStartupConfig) + .mockResolvedValue({ interface: { termsOfService: { modalAcceptance: true } } } as never); + if (failed === 'config') + jest.mocked(dataService.getStartupConfig).mockRejectedValueOnce(new Error('private failure')); + else jest.mocked(dataService.getUserTerms).mockRejectedValueOnce(new Error('private failure')); + renderRoute(); + expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_channel_link_error'); + expect(post).not.toHaveBeenCalled(); + expect(document.body.textContent).not.toContain('private failure'); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_retry' })); + expect(await screen.findByText('U1')).toBeInTheDocument(); + }, +); + +test('an old owner acknowledgement cannot replace the new owner preview or consume its tab ticket', async () => { + authenticated(); + window.history.replaceState({}, '', `/channels/link#${ticket}`); + let finish!: (value: { ok: true; value: ChannelLinkView }) => void; + post.mockImplementation(async (url) => + String(url).endsWith('/accept') + ? new Promise((resolve) => { + finish = resolve; + }) + : { ok: true, value: pending }, + ); + const mounted = renderRoute(); + await userEvent.click(await screen.findByRole('button', { name: 'com_ui_channel_link_accept' })); + jest.mocked(useAuthContext).mockReturnValue({ + user: { id: 'user-b', tenantId: 'other-tenant', email: 'b@example.com' }, + isAuthenticated: true, + isAuthReady: true, + logout: jest.fn(), + } as unknown as ReturnType); + mounted.rerenderRoute(); + await waitFor(() => + expect(screen.getByRole('button', { name: 'com_ui_channel_link_accept' })).toBeEnabled(), + ); + await act(async () => { + finish({ ok: true, value: { ...pending, state: 'accepted' } }); + }); + expect(screen.queryByText('com_ui_channel_link_confirm_slack')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'com_ui_channel_link_accept' })).toBeEnabled(); + expect(savedTicket().ticket).toBe(ticket); +}); diff --git a/client/src/routes/index.tsx b/client/src/routes/index.tsx index 4f9bfce4a7..b3c0a5002a 100644 --- a/client/src/routes/index.tsx +++ b/client/src/routes/index.tsx @@ -13,6 +13,7 @@ import { AuthContextProvider } from '~/hooks/AuthContext'; import ResponseReviewRoute from './ResponseReviewRoute'; import { importWithRecovery } from '~/lib/assets/lazy'; import RouteErrorBoundary from './RouteErrorBoundary'; +import ChannelLinkRoute from './ChannelLinkRoute'; import StartupLayout from './Layouts/Startup'; import MarketplaceRoute from './Marketplace'; import { codeSetupRoute } from './CodeSetup'; @@ -67,6 +68,11 @@ export const router = createBrowserRouter( element: , errorElement: , }, + { + path: 'channels/link', + element: , + errorElement: , + }, { path: 'share/:shareId', element: , diff --git a/e2e/specs/mock/scenarios/channel-account-lifecycle.spec.ts b/e2e/specs/mock/scenarios/channel-account-lifecycle.spec.ts new file mode 100644 index 0000000000..5a4a9e4c4e --- /dev/null +++ b/e2e/specs/mock/scenarios/channel-account-lifecycle.spec.ts @@ -0,0 +1,107 @@ +import { expect, test } from '@playwright/test'; +import type { ChannelLinkView } from 'librechat-data-provider'; +import { openAgentBuilder } from '../agents.helpers'; +import { openSidebar } from './sidebar'; + +test.use({ viewport: { width: 1280, height: 860 }, hasTouch: false, isMobile: false }); + +for (const mode of ['light', 'dark']) { + test(`channel confirmation and personal withdrawal use current state (${mode})`, async ({ + page, + }) => { + const ticket = 'Ab_-09'.repeat(8).slice(0, 43); + let state: ChannelLinkView['state'] = 'pending'; + let accepts = 0; + let revokes = 0; + const view = () => ({ + identity: { + tenantId: '_', + channelId: 'channel-browser', + channelRevision: 'channel-revision', + teamId: 'Workspace T1', + externalUserId: 'U1', + agentId: 'Agent browser', + }, + linkId: 'link-browser', + revision: 'revision-browser', + state, + expiresAtMs: Date.now() + 600_000, + }); + await page.addInitScript((theme) => localStorage.setItem('color-theme', theme), mode); + await page.route('**/api/auth/refresh', async (route) => { + await new Promise((resolve) => setTimeout(resolve, 700)); + await route.continue(); + }); + await page.route('**/api/channels/links**', async (route) => { + const url = new URL(route.request().url()); + if (url.pathname.endsWith('/accept')) { + expect(route.request().postDataJSON()).toEqual({ ticket, revision: 'revision-browser' }); + accepts++; + state = 'accepted'; + } + if (route.request().method() === 'DELETE') { + revokes++; + state = 'revoked'; + } + await route.fulfill({ + json: url.pathname === '/api/channels/links' ? [view()] : { ok: true, value: view() }, + }); + }); + await page.goto(`/channels/link#${ticket}`); + await page.waitForTimeout(400); + expect(new URL(page.url()).pathname).toBe('/channels/link'); + expect(page.url()).not.toContain(ticket); + await page.getByRole('button', { name: 'Accept this account link', exact: true }).click(); + await expect(page.getByRole('status')).toContainText('Return to Slack and confirm'); + state = 'active'; + // A real focus transition refetches the active query without remounting the route. + await page.evaluate(() => window.dispatchEvent(new Event('blur'))); + await page.evaluate(() => window.dispatchEvent(new Event('focus'))); + await expect(page.getByRole('status')).toHaveText('Active'); + expect(accepts).toBe(1); + if (process.env.E2E_CHANNEL_VISUAL_PREFIX) { + await page.screenshot({ path: `${process.env.E2E_CHANNEL_VISUAL_PREFIX}-link-${mode}.png` }); + } + state = 'unavailable'; + await page.goto('/c/new'); + await openSidebar(page); + await page.getByTestId('nav-user').filter({ visible: true }).first().click(); + await page.getByRole('menuitem', { name: 'Settings', exact: true }).click(); + const settings = page.getByRole('dialog'); + await settings.getByRole('tab', { name: 'Account', exact: true }).click(); + await expect( + settings.getByText('This connection is unavailable. You can still disconnect this account.'), + ).toBeVisible(); + if (process.env.E2E_CHANNEL_VISUAL_PREFIX) { + await page.screenshot({ + path: `${process.env.E2E_CHANNEL_VISUAL_PREFIX}-settings-${mode}.png`, + }); + } + await settings.getByRole('button', { name: 'Revoke link', exact: true }).click(); + expect(revokes).toBe(0); + await settings + .getByRole('group') + .getByRole('button', { name: 'Revoke link', exact: true }) + .click(); + await expect(settings.getByRole('status')).toHaveText('Revoked'); + expect(revokes).toBe(1); + await page.keyboard.press('Escape'); + await page.route('**/api/endpoints', async (route) => { + const response = await route.fetch(); + const config = await response.json(); + config.agents = { ...config.agents, channels: { enabled: true } }; + await route.fulfill({ response, json: config }); + }); + await page.reload(); + const form = await openAgentBuilder(page, { navigate: false }); + await expect(form.getByRole('heading', { name: 'Channels', exact: true })).toBeVisible(); + await expect(form.getByText('Save this Agent to configure channels.')).toBeVisible(); + await form.getByText('Save this Agent to configure channels.').scrollIntoViewIfNeeded(); + await form.getByRole('heading', { name: 'Channels', exact: true }).scrollIntoViewIfNeeded(); + if (process.env.E2E_CHANNEL_VISUAL_PREFIX) { + await page.screenshot({ + path: `${process.env.E2E_CHANNEL_VISUAL_PREFIX}-builder-${mode}.png`, + }); + } + }); +}