From 3e19ef42fe4924eecb40c526b94ae0c9711d45f2 Mon Sep 17 00:00:00 2001 From: Dustin Healy <54083382+dustinhealy@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:04:11 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=A5=20fix:=20Let=20Members=20Connect?= =?UTF-8?q?=20Agents=20to=20Slack=20Workspaces=20(#17835)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: allow members to connect agents to installed Slack workspaces * fix: clarify Slack destination assignment actions * fix: align Slack assignment status with destination heading * fix: explain Slack agent assignments in terms of the connected bot * fix: separate Slack connection setup, management and confirmation * fix: name replaced agents only when the member can view them * perf: avoid redundant Slack assignment identity lookups --- api/server/services/SlackWorkspaceBindings.js | 2 + .../SidePanel/Agents/ChannelStatus.tsx | 10 +- .../components/SidePanel/Agents/Channels.tsx | 109 ++--- .../SidePanel/Agents/WorkspaceChannel.tsx | 378 ++++++++++++------ .../Agents/__tests__/Channels.spec.tsx | 211 +++++++++- client/src/locales/en/translation.json | 39 +- client/src/utils/channelErrors.ts | 1 + .../mock/scenarios/slack-workspaces.spec.ts | 80 +++- .../api/src/channels/slackDispatch.spec.ts | 162 +++++++- .../api/src/channels/workspaceBindings.ts | 25 +- packages/data-provider/src/types/channels.ts | 3 + packages/data-schemas/src/methods/agent.ts | 30 +- .../src/methods/slackRoute.spec.ts | 20 + .../data-schemas/src/methods/slackRoute.ts | 13 +- 14 files changed, 847 insertions(+), 236 deletions(-) diff --git a/api/server/services/SlackWorkspaceBindings.js b/api/server/services/SlackWorkspaceBindings.js index 450cc8b17c..5b2a431522 100644 --- a/api/server/services/SlackWorkspaceBindings.js +++ b/api/server/services/SlackWorkspaceBindings.js @@ -25,6 +25,8 @@ module.exports = createSlackWorkspaceBindingHandlers({ workspaces: createSlackWorkspaceStorage(mongoose), routes: createSlackRouteStorage(mongoose, async () => (await readSettings()).channels), readSettings, + isPrincipalActive: db.isAgentTriggerPrincipalActive, + getAgentName: db.getAgentName, canManage: createSlackWorkspaceAdminGuard({ findUser: (id) => db.findUser({ _id: id }), isPrincipalActive: db.isAgentTriggerPrincipalActive, diff --git a/client/src/components/SidePanel/Agents/ChannelStatus.tsx b/client/src/components/SidePanel/Agents/ChannelStatus.tsx index d2d1b1b198..aae867c599 100644 --- a/client/src/components/SidePanel/Agents/ChannelStatus.tsx +++ b/client/src/components/SidePanel/Agents/ChannelStatus.tsx @@ -16,12 +16,18 @@ const statusColors: Record = { deleting: 'bg-status-info', }; -export default function ChannelStatus({ status }: { status: AgentChannel['status'] }) { +export default function ChannelStatus({ + status, + pendingLabel = 'com_ui_channels_pending', +}: { + status: AgentChannel['status']; + pendingLabel?: TranslationKeys; +}) { const localize = useLocalize(); return ( ); } diff --git a/client/src/components/SidePanel/Agents/Channels.tsx b/client/src/components/SidePanel/Agents/Channels.tsx index 9d14caa580..8503f784f5 100644 --- a/client/src/components/SidePanel/Agents/Channels.tsx +++ b/client/src/components/SidePanel/Agents/Channels.tsx @@ -30,6 +30,12 @@ const actionLabels: Record = { deleting: 'com_ui_channels_manage', }; +function channelActionLabel(channel: AgentChannel, userId: string): TranslationKeys { + if (channel.createdBy !== userId) return 'com_ui_channels_read_only'; + if (channel.workspaceId) return 'com_ui_channels_manage'; + return actionLabels[channel.status]; +} + function Channel({ agentId, channel, @@ -410,6 +416,7 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) { const id = useId(); const triggerRef = useRef(null); const [dialog, setDialog] = useState(null); + const [newWorkspaceConnection, setNewWorkspaceConnection] = useState(null); const [credentialMode, setCredentialMode] = useState('per_user'); const [source, setSource] = useState<'workspace' | 'manual'>('workspace'); const [workspaceId, setWorkspaceId] = useState(''); @@ -442,10 +449,7 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) { mutationFn: () => { if (!agentId || !userId || !channels.isSuccess) throw new Error('Channel owner unavailable'); if (useWorkspace) { - if ( - !workspaceStatus?.canManage || - !availableWorkspaces.some((workspace) => workspace.workspaceId === workspaceId) - ) + if (!availableWorkspaces.some((workspace) => workspace.workspaceId === workspaceId)) throw new Error('Workspace unavailable'); return dataService.createWorkspaceAgentChannel(agentId, workspaceId); } @@ -459,13 +463,15 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) { channel, ], ); + setNewWorkspaceConnection(channel.workspaceId ? channel.channelId : null); setDialog(channel.channelId); await queryClient.invalidateQueries([QueryKeys.agentChannels, userId, tenantId, agentId]); }, }); const selected = channels.data?.find((channel) => channel.channelId === dialog); const connectionTitle = - selected?.status === 'pending_install' + selected?.status === 'pending_install' && + (!selected.workspaceId || newWorkspaceConnection === selected.channelId) ? 'com_ui_channels_setup_title' : 'com_ui_channels_manage'; return ( @@ -531,7 +537,12 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) {
{localize('com_ui_channels_slack')} - +
))} @@ -629,47 +637,40 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) {

{localize('com_ui_channels_workspace_identity')}

- {!workspaceStatus?.canManage && ( -

{localize('com_ui_slack_workspaces_admin')}

+

+ {localize('com_ui_channels_workspace_choose')} +

+ {availableWorkspaces.length === 0 && ( +

{localize('com_ui_channels_workspace_connect_first')}

)} - {workspaceStatus?.canManage && ( - <> -

- {localize('com_ui_channels_workspace_choose')} -

- {availableWorkspaces.length === 0 && ( -

{localize('com_ui_channels_workspace_connect_first')}

- )} -
+ {availableWorkspaces.map((workspace) => ( + - ))} -
- {workspaces.hasNextPage && ( - - )} - + {workspace.teamName} + + ))} + + {workspaces.hasNextPage && ( + )} )} @@ -735,10 +736,9 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) { workspaces.isLoading || !channels.isSuccess || (useWorkspace && - (!workspaceStatus?.canManage || - !availableWorkspaces.some( - (workspace) => workspace.workspaceId === workspaceId, - ))) + !availableWorkspaces.some( + (workspace) => workspace.workspaceId === workspaceId, + )) } onClick={() => create.mutate()} > @@ -754,6 +754,7 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) { (null); + const addRef = useRef(null); const [confirm, setConfirm] = useState< - { kind: 'delete' } | { kind: 'remove'; target: SlackWorkspaceRouteTarget } | null + | { kind: 'delete' } + | { kind: 'remove'; target: SlackWorkspaceRouteTarget } + | { kind: 'assign'; replacementRevision: string } + | null >(null); const workspace = useQuery( [QueryKeys.slackWorkspaces, principalKey, channel.workspaceId], () => dataService.getSlackWorkspace(channel.workspaceId!), { retry: false }, ); - const canManage = Boolean(workspace.data?.canManage); + const ownsChannel = channel.createdBy === userId; const available = Boolean( workspace.data?.configured && workspace.data.workspace.status === 'active', ); - const mayRoute = enabled && canManage && available && channel.status !== 'deleting'; + const mayRoute = enabled && ownsChannel && available && channel.status !== 'deleting'; const routes = useInfiniteQuery( routesKey, ({ pageParam }: { pageParam?: string }) => dataService.getAgentChannelWorkspaceRoutes(agentId, channel.channelId, pageParam), { - enabled: enabled && canManage, + enabled: enabled && ownsChannel, retry: false, getNextPageParam: (page) => page.next, }, @@ -85,9 +105,8 @@ export default function WorkspaceChannel({ const target = useQuery( targetKey, () => dataService.getAgentChannelWorkspaceTarget(agentId, channel.channelId, targetId), - { enabled: mayRoute && validTarget && settledInput, retry: false }, + { enabled: editing && mayRoute && validTarget && settledInput, retry: false }, ); - useEffect(() => setReplace(false), [target.data?.revision, targetId]); const mutation = useMutation({ mutationKey: [ MutationKeys.agentChannelWorkspaceRoutes, @@ -102,7 +121,6 @@ export default function WorkspaceChannel({ return dataService.disableAgentChannel(agentId, channel.channelId); if (action.kind === 'delete') return dataService.deleteAgentChannel(agentId, channel.channelId); - if (!canManage) throw new Error('Workspace administration required'); if (action.kind === 'remove') return dataService.removeAgentChannelWorkspaceRoute(agentId, channel.channelId, { externalChannelId: action.target.externalChannelId, @@ -114,7 +132,9 @@ export default function WorkspaceChannel({ !settledInput || !target.isSuccess || target.isFetching || - (target.data.occupied && !target.data.assignedToThisChannel && !replace) + (target.data.occupied && + !target.data.assignedToThisChannel && + (!target.data.canReplace || action.replacementRevision !== target.data.revision)) ) throw new Error('Route changed'); return dataService.setAgentChannelWorkspaceRoute(agentId, channel.channelId, { @@ -125,6 +145,7 @@ export default function WorkspaceChannel({ }, onSuccess: (_result, action) => { if (mounted.current) { + if (action.kind === 'remove') actionRef.current = addRef.current; setConfirm(null); if (action.kind !== 'remove') onClose(); } @@ -150,7 +171,36 @@ export default function WorkspaceChannel({ const busy = !enabled || mutation.isLoading || channel.status === 'deleting'; const entries = routes.data?.pages.flatMap((page) => page.routes) ?? []; const replacesOther = settledInput && target.data?.occupied && !target.data.assignedToThisChannel; - const alreadyAssigned = target.data?.assignedToThisChannel && channel.status === 'active'; + const blocked = replacesOther && target.data?.canReplace !== true; + const replaceAssignmentLabel = specific + ? 'com_ui_channels_workspace_replace_channel_assignment' + : 'com_ui_channels_workspace_replace_assignment'; + const alreadyAssigned = + settledInput && + target.isSuccess && + !target.isFetching && + target.data.assignedToThisChannel && + channel.status === 'active'; + const assignmentDisabled = + busy || + !mayRoute || + !validTarget || + !settledInput || + !target.isSuccess || + target.isFetching || + Boolean(blocked) || + Boolean(replacesOther && !target.data?.revision); + let confirmationTitle: TranslationKeys = 'com_ui_channels_workspace_delete_connection'; + let confirmationHelp: TranslationKeys = 'com_ui_channels_workspace_delete_confirm'; + if (confirm?.kind === 'remove') { + confirmationTitle = 'com_ui_channels_workspace_remove_assignment'; + confirmationHelp = 'com_ui_channels_workspace_remove_confirm'; + } else if (confirm?.kind === 'assign') { + confirmationTitle = replaceAssignmentLabel; + confirmationHelp = specific + ? 'com_ui_channels_workspace_replace_channel_help' + : 'com_ui_channels_workspace_replace_help'; + } return ( <>
@@ -158,9 +208,23 @@ export default function WorkspaceChannel({ {workspace.data?.workspace.teamName ?? localize('com_ui_channels_org_workspace')} - +
-

{localize('com_ui_channels_workspace_identity')}

+ {workspace.data && ( + + {localize('com_ui_channels_workspace_open_bot')} + + )} + {workspace.isLoading &&

{localize('com_ui_channels_loading')}

} {workspace.isError && (
@@ -173,17 +237,27 @@ export default function WorkspaceChannel({ {workspace.data && !available && (

{localize('com_ui_channels_workspace_unavailable')}

)} - {workspace.data && !canManage &&

{localize('com_ui_slack_workspaces_admin')}

} + {!ownsChannel &&

{localize('com_ui_channels_read_only')}

} {mutation.isError && (

{localize(channelErrorLabel(mutation.error, 'com_ui_channels_workspace_route_error'))}

)} - {canManage && ( -
-

- {localize('com_ui_channels_workspace_routes')} -

+ {!editing && ownsChannel && ( +
0 ? `${id}-routes` : undefined} + aria-label={ + entries.length === 0 + ? localize('com_ui_channels_workspace_add_assignment') + : undefined + } + > + {entries.length > 0 && ( +

+ {localize('com_ui_channels_workspace_routes')} +

+ )} {routes.isLoading &&

{localize('com_ui_channels_loading')}

} {routes.isError && (
@@ -193,11 +267,6 @@ export default function WorkspaceChannel({
)} - {routes.isSuccess && entries.length === 0 && ( -

- {localize('com_ui_channels_workspace_no_routes')} -

- )} {entries.map((entry) => (
setConfirm({ kind: 'remove', target: entry })} + onClick={(event) => { + actionRef.current = event.currentTarget; + setConfirm({ kind: 'remove', target: entry }); + }} > {localize('com_ui_channels_workspace_remove_route')} @@ -227,13 +299,38 @@ export default function WorkspaceChannel({ {localize('com_ui_channels_workspace_more_routes')} )} +
)} - {mayRoute && ( + {editing && mayRoute && (
-

- {localize('com_ui_channels_workspace_target')} -

+
+

+ {localize('com_ui_channels_workspace_target')} +

+ {alreadyAssigned && ( + + )} +
{ setSpecific(false); - setReplace(false); }} > {localize('com_ui_channels_workspace_default')} @@ -258,7 +354,6 @@ export default function WorkspaceChannel({ disabled={busy} onClick={() => { setSpecific(true); - setReplace(false); }} > {localize('com_ui_channels_workspace_specific')} @@ -285,7 +380,6 @@ export default function WorkspaceChannel({ disabled={busy} onChange={(event) => { setExternalChannel(event.target.value); - setReplace(false); }} />
@@ -301,99 +395,145 @@ export default function WorkspaceChannel({
)} - {replacesOther && ( -
-

{localize('com_ui_channels_workspace_replace_help')}

-
- setReplace(value === true)} - /> - -
-
+ {blocked && ( + {localize('com_ui_channels_workspace_route_owned')} )} - - - )} - {confirm && ( -
-

- {localize( - confirm.kind === 'delete' - ? 'com_ui_channels_workspace_delete_confirm' - : 'com_ui_channels_workspace_remove_confirm', - )} + {replacesOther && !blocked && ( + + {target.data?.assignedAgentName + ? localize('com_ui_channels_workspace_occupied_named', { + 0: target.data.assignedAgentName, + }) + : localize('com_ui_channels_workspace_occupied')} + + )} +

+ {localize('com_ui_channels_workspace_identity')}

-
- - -
-
+ )} - - {channel.status === 'active' && ( - + {editing ? ( + <> + + {!alreadyAssigned && ( + + )} + + ) : ( + <> + + {channel.status === 'active' && ( + + )} + )} + { + if (!open && !mutation.isLoading) setConfirm(null); + }} + > + { + event.preventDefault(); + if (actionRef.current?.isConnected) actionRef.current.focus(); + else addRef.current?.focus(); + }} + main={ +
+

{localize(confirmationHelp)}

+ {confirm?.kind === 'assign' && + target.data?.revision !== confirm.replacementRevision && ( + + {localize('com_ui_channels_workspace_replacement_changed')} + + )} + {mutation.isError && ( + + {localize( + channelErrorLabel(mutation.error, 'com_ui_channels_workspace_route_error'), + )} + + )} +
+ } + selection={ + + } + /> +
); } diff --git a/client/src/components/SidePanel/Agents/__tests__/Channels.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/Channels.spec.tsx index 69909cac2d..31e49689e1 100644 --- a/client/src/components/SidePanel/Agents/__tests__/Channels.spec.tsx +++ b/client/src/components/SidePanel/Agents/__tests__/Channels.spec.tsx @@ -838,7 +838,7 @@ describe('organization workspace connections', () => { jest .mocked(dataService.getAgentChannelWorkspaceTarget) .mockReset() - .mockResolvedValue({ occupied: false, assignedToThisChannel: false }); + .mockResolvedValue({ canReplace: true, occupied: false, assignedToThisChannel: false }); jest .mocked(dataService.setAgentChannelWorkspaceRoute) .mockReset() @@ -859,6 +859,7 @@ describe('organization workspace connections', () => { test('chooses a saved workspace and requires explicit confirmation before replacing another agent', async () => { const user = userEvent.setup(); jest.mocked(dataService.getAgentChannelWorkspaceTarget).mockResolvedValue({ + canReplace: true, occupied: true, assignedToThisChannel: false, revision: 'observed-route', @@ -867,14 +868,30 @@ describe('organization workspace connections', () => { await openAdd(user); await user.click(await screen.findByRole('button', { name: 'Engineering' })); await user.click(screen.getByRole('button', { name: 'com_ui_continue' })); - const activate = await screen.findByRole('button', { name: 'com_ui_channels_activate' }); - expect(activate).toBeDisabled(); - await user.click( - await screen.findByRole('checkbox', { name: 'com_ui_channels_workspace_replace' }), - ); + const activate = await screen.findByRole('button', { + name: 'com_ui_channels_workspace_replace_assignment', + }); + expect( + screen.getByRole('link', { name: 'com_ui_channels_workspace_open_bot' }), + ).toHaveAttribute('href', 'https://slack.com/app_redirect?app=A123&team=T123'); + expect(screen.getAllByText('com_ui_channels_workspace_not_assigned').length).toBeGreaterThan(0); + expect(screen.queryByText('com_ui_channels_pending')).not.toBeInTheDocument(); await waitFor(() => expect(activate).toBeEnabled()); - expect(screen.queryByLabelText('com_ui_channels_bot_token')).not.toBeInTheDocument(); + expect(screen.queryByText('com_ui_channels_workspace_routes')).not.toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'com_ui_channels_workspace_delete_connection' }), + ).not.toBeInTheDocument(); await user.click(activate); + expect(dataService.setAgentChannelWorkspaceRoute).not.toHaveBeenCalled(); + const confirmation = screen.getByRole('dialog', { + name: 'com_ui_channels_workspace_replace_assignment', + }); + expect(screen.queryByLabelText('com_ui_channels_bot_token')).not.toBeInTheDocument(); + await user.click( + within(confirmation).getByRole('button', { + name: 'com_ui_channels_workspace_replace_assignment', + }), + ); await screen.findByText('com_ui_channels_active'); expect(dataService.createWorkspaceAgentChannel).toHaveBeenCalledWith('agent-1', 'workspace-1'); expect(dataService.setAgentChannelWorkspaceRoute).toHaveBeenCalledWith('agent-1', 'channel-1', { @@ -886,6 +903,126 @@ describe('organization workspace connections', () => { expect(dataService.activateAgentChannel).not.toHaveBeenCalled(); expect(submit).not.toHaveBeenCalled(); }); + test('cancelling setup leaves a manageable draft with no empty assignment section', async () => { + const user = userEvent.setup(); + renderChannels(); + await openAdd(user); + await user.click(await screen.findByRole('button', { name: 'Engineering' })); + await user.click(screen.getByRole('button', { name: 'com_ui_continue' })); + await screen.findByRole('button', { name: 'com_ui_channels_workspace_assign' }); + await user.click(screen.getByRole('button', { name: 'com_ui_cancel' })); + await openConnection(user, 'active'); + await screen.findByRole('button', { name: 'com_ui_channels_workspace_add_assignment' }); + expect(screen.queryByText('com_ui_channels_workspace_routes')).not.toBeInTheDocument(); + expect( + screen.queryByRole('group', { name: 'com_ui_channels_workspace_target' }), + ).not.toBeInTheDocument(); + const remove = screen.getByRole('button', { + name: 'com_ui_channels_workspace_delete_connection', + }); + await user.click(remove); + const confirmation = screen.getByRole('dialog', { + name: 'com_ui_channels_workspace_delete_connection', + }); + await user.click(within(confirmation).getByRole('button', { name: /Cancel/i })); + expect(remove).toHaveFocus(); + expect(dataService.deleteAgentChannel).not.toHaveBeenCalled(); + jest.mocked(dataService.deleteAgentChannel).mockImplementationOnce(async () => { + rows = []; + }); + await user.click(remove); + await user.click( + within( + screen.getByRole('dialog', { name: 'com_ui_channels_workspace_delete_connection' }), + ).getByRole('button', { name: 'com_ui_channels_workspace_delete_connection' }), + ); + await waitFor(() => + expect( + screen.queryByRole('button', { name: 'com_ui_channels_manage' }), + ).not.toBeInTheDocument(), + ); + expect(dataService.deleteAgentChannel).toHaveBeenCalledWith('agent-1', 'channel-1'); + }); + + test('requires fresh confirmation if an assignment changes while the replacement dialog is open', async () => { + let revision = 'observed-route'; + jest.mocked(dataService.getAgentChannelWorkspaceTarget).mockImplementation(async () => ({ + canReplace: true, + occupied: true, + assignedToThisChannel: false, + revision, + })); + const user = userEvent.setup(); + const { client } = renderChannels(); + await openAdd(user); + await user.click(await screen.findByRole('button', { name: 'Engineering' })); + await user.click(screen.getByRole('button', { name: 'com_ui_continue' })); + await user.click( + await screen.findByRole('button', { name: 'com_ui_channels_workspace_replace_assignment' }), + ); + revision = 'newer-route'; + await act(async () => { + await client.invalidateQueries([QueryKeys.agentChannelWorkspaceTarget]); + }); + const confirmation = screen.getByRole('dialog', { + name: 'com_ui_channels_workspace_replace_assignment', + }); + expect( + await within(confirmation).findByText('com_ui_channels_workspace_replacement_changed'), + ).toBeVisible(); + expect( + within(confirmation).getByRole('button', { + name: 'com_ui_channels_workspace_replace_assignment', + }), + ).toBeDisabled(); + expect(dataService.setAgentChannelWorkspaceRoute).not.toHaveBeenCalled(); + await user.click(within(confirmation).getByRole('button', { name: /Cancel/i })); + await user.click( + screen.getByRole('button', { name: 'com_ui_channels_workspace_replace_assignment' }), + ); + await user.click( + within( + screen.getByRole('dialog', { name: 'com_ui_channels_workspace_replace_assignment' }), + ).getByRole('button', { name: 'com_ui_channels_workspace_replace_assignment' }), + ); + await waitFor(() => + expect(dataService.setAgentChannelWorkspaceRoute).toHaveBeenCalledWith( + 'agent-1', + 'channel-1', + expect.objectContaining({ expectedRevision: 'newer-route' }), + ), + ); + }); + + test('members can choose an installed workspace while another user’s route stays protected', async () => { + jest + .mocked(dataService.getSlackWorkspaces) + .mockResolvedValue({ configured: true, canManage: false, workspaces: [workspace] }); + jest + .mocked(dataService.getSlackWorkspace) + .mockResolvedValue({ configured: true, canManage: false, workspace }); + jest.mocked(dataService.getAgentChannelWorkspaceTarget).mockResolvedValue({ + occupied: true, + assignedToThisChannel: false, + canReplace: false, + revision: 'other-route', + }); + const user = userEvent.setup(); + renderChannels(); + await openAdd(user); + await user.click(await screen.findByRole('button', { name: 'Engineering' })); + await user.click(screen.getByRole('button', { name: 'com_ui_continue' })); + await screen.findByText('com_ui_channels_workspace_route_owned'); + expect( + screen.getByRole('button', { name: 'com_ui_channels_workspace_replace_assignment' }), + ).toBeDisabled(); + expect( + screen.queryByRole('checkbox', { name: 'com_ui_channels_workspace_replace' }), + ).not.toBeInTheDocument(); + expect(dataService.createWorkspaceAgentChannel).toHaveBeenCalledWith('agent-1', 'workspace-1'); + expect(dataService.setAgentChannelWorkspaceRoute).not.toHaveBeenCalled(); + }); + test('refreshes a committed channel revision when an assignment response is lost', async () => { jest.mocked(dataService.setAgentChannelWorkspaceRoute).mockImplementationOnce(async () => { rows = [{ ...configured, status: 'active', revision: 'committed-revision' }]; @@ -896,7 +1033,9 @@ describe('organization workspace connections', () => { await openAdd(user); await user.click(await screen.findByRole('button', { name: 'Engineering' })); await user.click(screen.getByRole('button', { name: 'com_ui_continue' })); - await user.click(await screen.findByRole('button', { name: 'com_ui_channels_activate' })); + await user.click( + await screen.findByRole('button', { name: 'com_ui_channels_workspace_assign' }), + ); await screen.findByRole('alert'); await screen.findAllByText('com_ui_channels_active'); await user.click(screen.getByRole('button', { name: 'com_ui_channels_workspace_assign' })); @@ -914,6 +1053,9 @@ describe('organization workspace connections', () => { const user = userEvent.setup(); renderChannels(); await openConnection(user, 'active'); + await user.click( + await screen.findByRole('button', { name: 'com_ui_channels_workspace_add_assignment' }), + ); await user.click( await screen.findByRole('button', { name: 'com_ui_channels_workspace_specific' }), ); @@ -928,7 +1070,7 @@ describe('organization workspace connections', () => { expect.objectContaining({ externalChannelId: 'C999' }), ); }); - test('does not expose route management when integration administration is unavailable', async () => { + test('lets members manage their own routes without installation administration', async () => { rows = [{ ...configured, status: 'active' }]; jest .mocked(dataService.getSlackWorkspace) @@ -936,14 +1078,46 @@ describe('organization workspace connections', () => { const user = userEvent.setup(); renderChannels(); await openConnection(user, 'active'); - await screen.findByText('com_ui_slack_workspaces_admin'); - expect(dataService.getAgentChannelWorkspaceRoutes).not.toHaveBeenCalled(); - expect(dataService.getAgentChannelWorkspaceTarget).not.toHaveBeenCalled(); + await user.click( + await screen.findByRole('button', { name: 'com_ui_channels_workspace_add_assignment' }), + ); + await screen.findByRole('button', { name: 'com_ui_channels_workspace_assign' }); + expect(dataService.getAgentChannelWorkspaceRoutes).toHaveBeenCalled(); + expect(dataService.getAgentChannelWorkspaceTarget).toHaveBeenCalled(); + expect(screen.queryByText('com_ui_slack_workspaces_admin')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toBeEnabled(); + }); + test('shows assignment status instead of a disabled action for the selected destination', async () => { + rows = [{ ...configured, status: 'active' }]; + jest + .mocked(dataService.getAgentChannelWorkspaceTarget) + .mockImplementation(async (_agent, _channel, destination) => ({ + canReplace: true, + occupied: destination === undefined, + assignedToThisChannel: destination === undefined, + revision: destination === undefined ? 'owned-route' : undefined, + })); + const user = userEvent.setup(); + renderChannels(); + await openConnection(user, 'active'); + await user.click( + await screen.findByRole('button', { name: 'com_ui_channels_workspace_add_assignment' }), + ); + await screen.findByText('com_ui_channels_workspace_assigned'); expect( screen.queryByRole('button', { name: 'com_ui_channels_workspace_assign' }), ).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'com_ui_delete' })).toBeEnabled(); + await user.click(screen.getByRole('button', { name: 'com_ui_channels_workspace_specific' })); + await user.type(screen.getByLabelText('com_ui_channels_workspace_channel_id'), 'C999'); + await waitFor(() => + expect( + screen.getByRole('button', { name: 'com_ui_channels_workspace_assign' }), + ).toBeEnabled(), + ); + expect(screen.queryByText('com_ui_channels_workspace_assigned')).not.toBeInTheDocument(); + expect(dataService.setAgentChannelWorkspaceRoute).not.toHaveBeenCalled(); }); + test('removes a selected route only after confirmation and keeps the connection active', async () => { rows = [{ ...configured, status: 'active' }]; let routes = [{ externalChannelId: 'C123', revision: 'route-1' }]; @@ -962,10 +1136,15 @@ describe('organization workspace connections', () => { expect(dataService.removeAgentChannelWorkspaceRoute).not.toHaveBeenCalled(); await user.click( within( - screen.getByRole('group', { name: 'com_ui_channels_workspace_confirm_title' }), - ).getByRole('button', { name: 'com_ui_confirm' }), + screen.getByRole('dialog', { name: 'com_ui_channels_workspace_remove_assignment' }), + ).getByRole('button', { name: 'com_ui_channels_workspace_remove_assignment' }), ); - await screen.findByText('com_ui_channels_workspace_no_routes'); + await waitFor(() => + expect( + screen.queryByRole('button', { name: 'com_ui_channels_workspace_remove_route' }), + ).not.toBeInTheDocument(), + ); + expect(screen.queryByText('com_ui_channels_workspace_routes')).not.toBeInTheDocument(); expect(dataService.removeAgentChannelWorkspaceRoute).toHaveBeenCalledWith( 'agent-1', 'channel-1', diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 3517152847..14f0e688d2 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -3931,27 +3931,38 @@ "com_ui_channels_manual_app": "Manual Slack app", "com_ui_channels_manual_help": "Use a separate Slack app configured for this agent. A deployment administrator must run its gateway connection.", "com_ui_channels_org_workspace": "Organization workspace", - "com_ui_channels_workspace_assign": "Use this agent here", - "com_ui_channels_workspace_channel_help": "Copy the channel ID from its details in Slack. Invite the app to the channel before sending it a message.", + "com_ui_channels_workspace_not_assigned": "Not assigned", + "com_ui_channels_workspace_open_bot": "Open this bot in Slack", + "com_ui_channels_workspace_replace_channel_assignment": "Replace channel agent", + "com_ui_channels_workspace_replace_channel_help": "This agent will replace the bot’s current agent for new conversations in this Slack channel. Existing conversations and other channels won’t change.", + "com_ui_channels_workspace_add_assignment": "Add assignment", + "com_ui_channels_workspace_replacement_changed": "The assignment changed. Cancel and review the latest assignment before replacing it.", + "com_ui_channels_workspace_replace_named": "Replace {{0}}?", + "com_ui_channels_workspace_occupied_named": "{{0}} is assigned here. Continue to replace it.", + "com_ui_channels_workspace_occupied": "Another agent is assigned here. Continuing will ask you to confirm replacement.", + "com_ui_channels_workspace_delete_connection": "Delete connection", + "com_ui_channels_workspace_remove_assignment": "Remove assignment", + "com_ui_channels_workspace_assign": "Assign agent", + "com_ui_channels_workspace_replace_assignment": "Replace default agent", + "com_ui_channels_workspace_assigned": "Assigned to this agent", + "com_ui_channels_workspace_channel_help": "Use this agent for new conversations in one Slack channel. Invite the bot to that channel first.", "com_ui_channels_workspace_channel_id": "Slack channel ID", "com_ui_channels_workspace_choose": "Choose a Slack workspace", - "com_ui_channels_workspace_confirm_title": "Confirm connection change", "com_ui_channels_workspace_connect_first": "Connect a workspace in Settings → Account → Organization Slack workspaces first.", - "com_ui_channels_workspace_default": "Workspace default", - "com_ui_channels_workspace_default_help": "Handle direct messages and mentions that do not have a channel-specific agent. Existing conversations keep their original agent.", + "com_ui_channels_workspace_default": "Default for this bot", + "com_ui_channels_workspace_default_help": "Use this agent for new direct messages and mentions, unless a Slack channel has its own assignment.", "com_ui_channels_workspace_delete_confirm": "Remove this agent connection? Its Slack requests will stop. Other agents and the organization’s workspace connection will remain available.", - "com_ui_channels_workspace_identity": "Members link their own LibreChat accounts in Slack. Requests use each member’s existing agent and tool permissions.", - "com_ui_channels_workspace_more_routes": "Show more conversations", - "com_ui_channels_workspace_no_routes": "This agent is not assigned to new conversations.", - "com_ui_channels_workspace_remove_confirm": "Remove this route for new conversations? A channel-specific conversation may use the workspace default instead. Existing conversations keep their agent.", - "com_ui_channels_workspace_replace": "Use this agent instead", - "com_ui_channels_workspace_replace_help": "Another agent is configured for new conversations here. Existing conversations will keep their agent.", + "com_ui_channels_workspace_identity": "Slack users link their LibreChat account and keep their existing permissions.", + "com_ui_channels_workspace_more_routes": "Show more assignments", + "com_ui_channels_workspace_remove_confirm": "Remove this bot’s assignment to this agent for new conversations? A channel-specific assignment may fall back to this bot’s default agent. Existing conversations and other Slack bots won’t change.", + "com_ui_channels_workspace_route_owned": "Another user’s agent is assigned to this bot here. Choose another Slack channel, or ask an administrator to change the assignment.", + "com_ui_channels_workspace_replace_help": "This agent will replace this bot’s default for new direct messages and mentions without a channel-specific assignment. Existing conversations and other bots won’t change.", "com_ui_channels_workspace_route_error": "Could not update the connection. Check its current settings and your permissions, then try again.", "com_ui_channels_workspace_remove_route": "Remove", - "com_ui_channels_workspace_routes": "New conversations", + "com_ui_channels_workspace_routes": "Current assignments", "com_ui_channels_workspace_source": "Slack connection type", - "com_ui_channels_workspace_specific": "Specific Slack channel", - "com_ui_channels_workspace_target": "Where this agent responds", + "com_ui_channels_workspace_specific": "For a specific channel", + "com_ui_channels_workspace_target": "Where this bot uses this agent", "com_ui_channels_workspace_unavailable": "This workspace connection is unavailable. Ask an organization administrator to reconnect it, then add a new agent connection.", "com_ui_slack_apps_title": "Slack apps", "com_ui_slack_apps_description": "Connect your organization’s Slack app. Each app can be installed in multiple workspaces. Credentials are encrypted and never displayed after saving.", diff --git a/client/src/utils/channelErrors.ts b/client/src/utils/channelErrors.ts index af6163efa4..a6d7e85296 100644 --- a/client/src/utils/channelErrors.ts +++ b/client/src/utils/channelErrors.ts @@ -14,5 +14,6 @@ export function channelErrorLabel( const unavailable = code === 'transactions_unavailable' || (error instanceof Error && 'code' in error && error.code === 'transactions_unavailable'); + if (code === 'route_in_use') return 'com_ui_channels_workspace_route_owned'; return unavailable ? 'com_ui_channels_transaction_required' : fallback; } diff --git a/e2e/specs/mock/scenarios/slack-workspaces.spec.ts b/e2e/specs/mock/scenarios/slack-workspaces.spec.ts index 4c85ec0f16..743ef603b7 100644 --- a/e2e/specs/mock/scenarios/slack-workspaces.spec.ts +++ b/e2e/specs/mock/scenarios/slack-workspaces.spec.ts @@ -224,7 +224,7 @@ for (const theme of ['light', 'dark']) { await route.fulfill({ json: { configured: true, - canManage: true, + canManage: false, ...(detail ? { workspace } : { workspaces: [workspace] }), }, }); @@ -302,7 +302,13 @@ for (const theme of ['light', 'dark']) { } await route.fulfill({ json: url.searchParams.has('target') - ? { occupied, assignedToThisChannel: assigned, revision: routeRevision } + ? { + canReplace: true, + assignedAgentName: occupied ? 'Research Assistant' : undefined, + occupied, + assignedToThisChannel: assigned, + revision: routeRevision, + } : { routes }, }); return; @@ -342,25 +348,56 @@ for (const theme of ['light', 'dark']) { await picker.getByRole('button', { name: 'Continue', exact: true }).click(); const setup = page.getByRole('dialog', { name: 'Connect to Slack', exact: true }); await expect( - setup.getByRole('checkbox', { name: 'Use this agent instead', exact: true }), - ).toBeVisible(); + setup.getByRole('button', { name: 'Replace default agent', exact: true }), + ).toBeEnabled(); await expect( - setup.getByRole('button', { name: 'Activate channel', exact: true }), - ).toBeDisabled(); + setup.getByRole('heading', { name: 'Current assignments', exact: true }), + ).toHaveCount(0); + await expect( + setup.getByRole('button', { name: 'Delete connection', exact: true }), + ).toHaveCount(0); await expect(setup.getByLabel('Bot token', { exact: true })).toHaveCount(0); if (process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX) await page.screenshot({ animations: 'disabled', path: `${process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX}-target-${theme}.png`, }); - await setup.getByRole('checkbox', { name: 'Use this agent instead', exact: true }).check(); - await setup.getByRole('button', { name: 'Activate channel', exact: true }).click(); + await setup.getByRole('button', { name: 'Replace default agent', exact: true }).click(); + const replacement = page.getByRole('dialog', { + name: 'Replace Research Assistant?', + exact: true, + }); + expect(activations).toBe(0); + if (process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX) + await page.screenshot({ + animations: 'disabled', + path: `${process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX}-replacement-${theme}.png`, + }); + await replacement.getByRole('button', { name: 'Cancel', exact: true }).click(); + await expect(replacement).toHaveCount(0); + await expect( + setup.getByRole('button', { name: 'Replace default agent', exact: true }), + ).toBeFocused(); + await setup.getByRole('button', { name: 'Replace default agent', exact: true }).click(); + await replacement.getByRole('button', { name: 'Replace default agent', exact: true }).click(); await expect(setup).toHaveCount(0); expect(activations).toBe(1); await expect(form.getByText('Active', { exact: true })).toBeVisible(); await form.getByRole('button', { name: 'Manage connection', exact: true }).click(); const manage = page.getByRole('dialog', { name: 'Manage connection', exact: true }); await expect(manage.getByRole('button', { name: 'Remove', exact: true })).toBeVisible(); + await expect( + manage.getByRole('heading', { name: 'Current assignments', exact: true }), + ).toBeVisible(); + await expect( + manage.getByRole('button', { name: 'Add assignment', exact: true }), + ).toBeVisible(); + await expect( + manage.getByRole('group', { name: 'Where this bot uses this agent', exact: true }), + ).toHaveCount(0); + await expect(manage.getByRole('button', { name: 'Assign agent', exact: true })).toHaveCount( + 0, + ); if (process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX) await page.screenshot({ animations: 'disabled', @@ -368,23 +405,30 @@ for (const theme of ['light', 'dark']) { }); await manage.getByRole('button', { name: 'Remove', exact: true }).click(); expect(removed).toBe(0); - await manage - .getByRole('group', { name: 'Confirm connection change', exact: true }) - .getByRole('button', { name: 'Confirm', exact: true }) - .click(); + const removal = page.getByRole('dialog', { name: 'Remove assignment', exact: true }); + if (process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX) + await page.screenshot({ + animations: 'disabled', + path: `${process.env.E2E_SHARED_WORKSPACE_VISUAL_PREFIX}-remove-${theme}.png`, + }); + await removal.getByRole('button', { name: 'Remove assignment', exact: true }).click(); + await expect(manage.getByRole('button', { name: 'Remove', exact: true })).toHaveCount(0); await expect( - manage.getByText('This agent is not assigned to new conversations.', { exact: true }), - ).toBeVisible(); + manage.getByRole('heading', { name: 'Current assignments', exact: true }), + ).toHaveCount(0); + await expect( + manage.getByRole('button', { name: 'Add assignment', exact: true }), + ).toBeFocused(); expect(removed).toBe(1); await manage.getByRole('button', { name: 'Disable', exact: true }).click(); await expect(form.getByText('Disabled', { exact: true })).toBeVisible(); expect(disabled).toBe(1); await form.getByRole('button', { name: 'Manage connection', exact: true }).click(); - await manage.getByRole('button', { name: 'Delete', exact: true }).click(); + await manage.getByRole('button', { name: 'Delete connection', exact: true }).click(); expect(deleted).toBe(0); - await manage - .getByRole('group', { name: 'Confirm connection change', exact: true }) - .getByRole('button', { name: 'Confirm', exact: true }) + await page + .getByRole('dialog', { name: 'Delete connection', exact: true }) + .getByRole('button', { name: 'Delete connection', exact: true }) .click(); await expect( form.getByRole('button', { name: 'Manage connection', exact: true }), diff --git a/packages/api/src/channels/slackDispatch.spec.ts b/packages/api/src/channels/slackDispatch.spec.ts index 4539d9cf81..a7a1557e7c 100644 --- a/packages/api/src/channels/slackDispatch.spec.ts +++ b/packages/api/src/channels/slackDispatch.spec.ts @@ -3,7 +3,14 @@ import express from 'express'; import mongoose from 'mongoose'; import supertest from 'supertest'; import { MongoMemoryReplSet } from 'mongodb-memory-server'; -import { FileSources, channelConfigSchema } from 'librechat-data-provider'; +import { + FileSources, + channelConfigSchema, + PermissionBits, + PrincipalType, + PrincipalModel, + ResourceType, +} from 'librechat-data-provider'; import { createModels, createMethods, @@ -32,7 +39,11 @@ describe('shared Slack service routing', () => { const serviceToken = 'shared-test-service-token-at-least-32'; let enabled = true; let manageAllowed = true; + let principalActive = true; let sequence = 0; + const readAgentName = jest.fn((...args: Parameters) => + channels.getAgentName(...args), + ); const config = channelConfigSchema.parse({ enabled: true, transport: 'webhook', @@ -110,6 +121,7 @@ describe('shared Slack service routing', () => { workspaceId, channelId, userId: 'admin', + allowReplaceOthers: true, channelRevision: 'consent', }); if (!result.ok) throw new Error(result.code); @@ -166,6 +178,8 @@ describe('shared Slack service routing', () => { routes, readSettings, canManage: async () => manageAllowed, + isPrincipalActive: async () => principalActive, + getAgentName: readAgentName, logError: jest.fn(), }); app.use('/ui', (req, _res, next) => { @@ -187,6 +201,8 @@ describe('shared Slack service routing', () => { beforeEach(async () => { enabled = true; manageAllowed = true; + principalActive = true; + readAgentName.mockClear(); provider .mockReset() .mockImplementation( @@ -194,6 +210,8 @@ describe('shared Slack service routing', () => { ); await runAsSystem(async () => { for (const name of [ + 'Agent', + 'AclEntry', 'AgentChannel', 'SlackWorkspace', 'SlackInstall', @@ -280,6 +298,141 @@ describe('shared Slack service routing', () => { }).expect(400); }); + it('lets an ordinary member connect, route and remove their own agent without installation credentials', async () => { + const workspace = await scoped(() => install()); + manageAllowed = false; + const member = 'member'; + const channel = ( + await request + .post('/ui/member-agent/connections') + .set('x-test-user', member) + .send({ workspaceId: workspace.workspaceId }) + .expect(201) + ).body; + const active = ( + await request + .post(`/ui/member-agent/${channel.channelId}/routes`) + .set('x-test-user', member) + .send({ channelRevision: channel.revision, externalChannelId: 'CMEMBER' }) + .expect(200) + ).body; + expect(active.status).toBe('active'); + expect(JSON.stringify(active)).not.toMatch(/xoxb|encrypted|signing/); + const target = ( + await request + .get(`/ui/member-agent/${channel.channelId}/routes?target=CMEMBER`) + .set('x-test-user', member) + .expect(200) + ).body; + expect(target).toMatchObject({ assignedToThisChannel: true, canReplace: true }); + expect(readAgentName).not.toHaveBeenCalled(); + await request + .delete(`/ui/member-agent/${channel.channelId}/routes`) + .set('x-test-user', member) + .send({ externalChannelId: 'CMEMBER', expectedRevision: target.revision }) + .expect(204); + expect(await scoped(() => routes.read(workspace.workspaceId, 'CMEMBER'))).toBeNull(); + }); + + it('names the assigned agent only with tenant-local VIEW permission, including after permission revocation', async () => { + const viewer = '000000000000000000000003'; + const workspace = await scoped(() => install()); + const original = await pending(workspace.workspaceId); + await browserPost(`agent/${original.channelId}/routes`, { + channelRevision: original.revision, + }).expect(200); + const member = ( + await request + .post('/ui/member-agent/connections') + .set('x-test-user', viewer) + .send({ workspaceId: workspace.workspaceId }) + .expect(201) + ).body; + const agent = await scoped(() => + db.models.Agent.create({ + id: 'agent', + name: 'Research Assistant', + author: new mongoose.Types.ObjectId(), + provider: 'openAI', + model: 'test', + }), + ); + const read = () => + request + .get(`/ui/member-agent/${member.channelId}/routes?target=default`) + .set('x-test-user', viewer) + .expect(200); + expect((await read()).body).not.toHaveProperty('assignedAgentName'); + const acl = await scoped(() => + db.models.AclEntry.create({ + principalType: PrincipalType.USER, + principalId: new mongoose.Types.ObjectId(viewer), + principalModel: PrincipalModel.USER, + resourceType: ResourceType.AGENT, + resourceId: agent._id, + permBits: PermissionBits.VIEW, + grantedBy: new mongoose.Types.ObjectId(viewer), + grantedAt: new Date(), + }), + ); + expect((await read()).body.assignedAgentName).toBe('Research Assistant'); + expect( + await scoped(() => channels.getAgentName('agent', 'org-b', { userId: viewer })), + ).toBeUndefined(); + await scoped(() => db.models.AclEntry.deleteOne({ _id: acl._id })); + expect((await read()).body).not.toHaveProperty('assignedAgentName'); + }); + + it('prevents a member from replacing another creator while permitting a current administrator override', async () => { + const workspace = await scoped(() => install()); + const original = await pending(workspace.workspaceId); + await browserPost(`agent/${original.channelId}/routes`, { + channelRevision: original.revision, + }).expect(200); + manageAllowed = false; + const member = 'member'; + const channel = ( + await request + .post('/ui/member-agent/connections') + .set('x-test-user', member) + .send({ workspaceId: workspace.workspaceId }) + .expect(201) + ).body; + const target = ( + await request + .get(`/ui/member-agent/${channel.channelId}/routes?target=default`) + .set('x-test-user', member) + .expect(200) + ).body; + expect(target).toMatchObject({ occupied: true, canReplace: false }); + const change = () => + request + .post(`/ui/member-agent/${channel.channelId}/routes`) + .set('x-test-user', member) + .send({ channelRevision: channel.revision, expectedRevision: target.revision }); + await change().expect(409, { error: 'route_in_use' }); + expect((await scoped(() => channels.getAgentChannel(channel.channelId)))?.status).toBe( + 'pending_install', + ); + expect((await scoped(() => routes.read(workspace.workspaceId)))?.channelId).toBe( + original.channelId, + ); + await request + .post(`/ui/member-agent/${channel.channelId}/routes`) + .set('x-test-user', member) + .send({ + channelRevision: channel.revision, + expectedRevision: target.revision, + allowReplaceOthers: true, + }) + .expect(400); + manageAllowed = true; + await change().expect(200); + expect((await scoped(() => routes.read(workspace.workspaceId)))?.channelId).toBe( + channel.channelId, + ); + }); + it('leaves a conflicting connection pending until an explicit route revision is supplied', async () => { const workspace = await scoped(() => install()); const first = await pending(workspace.workspaceId); @@ -300,6 +453,7 @@ describe('shared Slack service routing', () => { .expect(200) ).body; expect(observed).toEqual({ + canReplace: true, occupied: true, assignedToThisChannel: false, revision: expect.any(String), @@ -312,18 +466,18 @@ describe('shared Slack service routing', () => { expect((await post('/resolve', query()).expect(200)).body.channelId).toBe(second.channelId); }); - it('checks current administration, creator, tenant and binding revision at management boundaries', async () => { + it('checks current activity, creator, tenant and binding revision at management boundaries', async () => { const workspace = await scoped(() => install()); await request .post('/ui/agent/connections') .send({ workspaceId: workspace.workspaceId }) .expect(401); const channel = await pending(workspace.workspaceId); - manageAllowed = false; + principalActive = false; await browserPost(`agent/${channel.channelId}/routes`, { channelRevision: channel.revision, }).expect(403); - manageAllowed = true; + principalActive = true; await request .get(`/ui/agent/${channel.channelId}/routes`) .set('x-test-user', 'other-admin') diff --git a/packages/api/src/channels/workspaceBindings.ts b/packages/api/src/channels/workspaceBindings.ts index 4183ce8788..73c1a12446 100644 --- a/packages/api/src/channels/workspaceBindings.ts +++ b/packages/api/src/channels/workspaceBindings.ts @@ -46,12 +46,18 @@ const queryInput = z.union([ .strict(), ]); -/** Agent SHARE middleware and fresh tenant administration jointly authorize shared bot routing. */ +/** Agent SHARE middleware and creator ownership authorize bindings; installation management stays separate. */ export function createSlackWorkspaceBindingHandlers(deps: { channels: AgentChannelMethods; workspaces: SlackWorkspaceStorage; routes: SlackRouteStorage; canManage: (principal: SlackWorkspacePrincipal) => Promise; + isPrincipalActive: (id: string) => Promise; + getAgentName: ( + id: string, + tenantId: string | undefined, + viewer: { userId: string }, + ) => Promise; readSettings: ReturnType; logError: (metadata: ReturnType) => void; }): { @@ -83,7 +89,7 @@ export function createSlackWorkspaceBindingHandlers(deps: { return; } try { - if (!(await deps.canManage(principal))) { + if (!(await deps.isPrincipalActive(principal.id))) { res.sendStatus(403); return; } @@ -160,7 +166,21 @@ export function createSlackWorkspaceBindingHandlers(deps: { channel.workspaceId, input.data.target === 'default' ? undefined : input.data.target, ); + const previous = + route && route.channelId !== channel.channelId + ? await deps.channels.getAgentChannelMetadata(route.channelId) + : null; + const [canReplace, assignedAgentName] = await Promise.all([ + !route || route.channelId === channel.channelId || previous?.createdBy === principal.id + ? true + : deps.canManage(principal), + previous + ? deps.getAgentName(previous.agentId, principal.tenantId, { userId: principal.id }) + : undefined, + ]); res.json({ + canReplace, + assignedAgentName, occupied: Boolean(route), assignedToThisChannel: route?.channelId === channel.channelId, revision: route?.revision, @@ -202,6 +222,7 @@ export function createSlackWorkspaceBindingHandlers(deps: { channelRevision: input.data.channelRevision, externalChannelId: input.data.externalChannelId, expectedRevision: input.data.expectedRevision, + allowReplaceOthers: input.data.expectedRevision ? await deps.canManage(principal) : false, activate: channel.status !== 'active', }); if (!result.ok) { diff --git a/packages/data-provider/src/types/channels.ts b/packages/data-provider/src/types/channels.ts index 7e99c3ffea..54d2e603f1 100644 --- a/packages/data-provider/src/types/channels.ts +++ b/packages/data-provider/src/types/channels.ts @@ -80,6 +80,9 @@ export interface SlackWorkspaceRoutePage { next?: string; } export interface SlackWorkspaceRouteStatus { + /** Only present when the requesting user has VIEW access to the assigned agent. */ + assignedAgentName?: string; + canReplace: boolean; occupied: boolean; assignedToThisChannel: boolean; revision?: string; diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts index 51ca6eafba..673bd13baa 100644 --- a/packages/data-schemas/src/methods/agent.ts +++ b/packages/data-schemas/src/methods/agent.ts @@ -1079,7 +1079,11 @@ export function createAgentMethods( ): { findAgentIdentity: (agentId: string) => Promise<{ _id: string } | null>; getAgent: GetAgent; - getAgentName: (id: string, tenantId?: string) => Promise; + getAgentName: ( + id: string, + tenantId?: string, + viewer?: { userId: string }, + ) => Promise; getAgentVersions: (searchParameter: FilterQuery) => Promise; getAgentWithVersionCount: ( searchParameter: FilterQuery, @@ -1306,14 +1310,28 @@ export function createAgentMethods( return await Agent.findOne(searchParameter, projection).lean(); }; - /** Storage-neutral display-name lookup for a known execution subject. */ - async function getAgentName(id: string, tenantId?: string): Promise { + /** Storage-neutral display name; user-facing callers supply a viewer to enforce VIEW ACLs. */ + async function getAgentName( + id: string, + tenantId?: string, + viewer?: { userId: string }, + ): Promise { const agent = await getAgent( { id, tenantId: tenantId ?? null }, - { name: 1, tenantId: 1, _id: 0 }, + { name: 1, tenantId: 1, _id: 1 }, ); - if ((agent?.tenantId ?? undefined) !== tenantId) return undefined; - return agent?.name || undefined; + if (!agent || (agent.tenantId ?? undefined) !== tenantId) return undefined; + if (viewer) { + const principals = await deps.getUserPrincipals(viewer); + const visible = await deps.findAccessibleResources( + principals, + ResourceType.AGENT, + PermissionBits.VIEW, + [agent._id], + ); + if (visible.length === 0) return undefined; + } + return agent.name || undefined; } /** diff --git a/packages/data-schemas/src/methods/slackRoute.spec.ts b/packages/data-schemas/src/methods/slackRoute.spec.ts index bb0dd59305..f1aac19af3 100644 --- a/packages/data-schemas/src/methods/slackRoute.spec.ts +++ b/packages/data-schemas/src/methods/slackRoute.spec.ts @@ -83,6 +83,7 @@ describe('workspace routing and live channel authority', () => { const channel = await channels.getAgentChannel(channelId); return routes.assign({ userId: 'admin', + allowReplaceOthers: true, workspaceId, channelId, externalChannelId, @@ -238,6 +239,25 @@ describe('workspace routing and live channel authority', () => { expect((await channels.getAgentChannelMetadata('binding-a'))?.status).toBe('active'); })); + it('enforces creator ownership inside replacement transactions even with a valid observed revision', async () => + scoped(async () => { + const workspaceId = await install(); + await binding(workspaceId); + await binding(workspaceId, 'binding-b'); + const initial = await assign(workspaceId, 'binding-a'); + if (!initial.ok || !initial.route) throw new Error('Missing route'); + const change = { + userId: 'member', + workspaceId, + channelId: 'binding-b', + channelRevision: 'consent-binding-b', + expectedRevision: initial.route.revision, + }; + expect(await routes.assign(change)).toEqual({ ok: false, code: 'route_in_use' }); + expect((await routes.read(workspaceId))?.channelId).toBe('binding-a'); + expect((await routes.assign({ ...change, userId: 'agent-manager' })).ok).toBe(true); + })); + it('serializes competing initial assignments rather than letting two agents own a default', async () => scoped(async () => { const workspaceId = await install(); diff --git a/packages/data-schemas/src/methods/slackRoute.ts b/packages/data-schemas/src/methods/slackRoute.ts index c03730b181..bcee44255f 100644 --- a/packages/data-schemas/src/methods/slackRoute.ts +++ b/packages/data-schemas/src/methods/slackRoute.ts @@ -21,7 +21,8 @@ type RouteResult = | 'principal_unavailable' | 'workspace_unavailable' | 'channel_unavailable' - | 'route_changed'; + | 'route_changed' + | 'route_in_use'; }; export interface SlackRouteStorage { @@ -42,6 +43,8 @@ export interface SlackRouteStorage { channelId: string; channelRevision: string; expectedRevision?: string; + /** Trusted current administrator authority; never supplied by a browser. */ + allowReplaceOthers?: boolean; /** Activate an existing pending/disabled binding in the same route transaction. */ activate?: boolean; }): Promise; @@ -145,6 +148,14 @@ export function createSlackRouteStorage( const previous = await routes.findOne(filter).session(session).lean(); if ((previous?.revision ?? undefined) !== input.expectedRevision) return { ok: false, code: 'route_changed' }; + if (previous && previous.channelId !== input.channelId && !input.allowReplaceOthers) { + const previousChannel = await channels + .findOne({ channelId: previous.channelId, tenantId: tenantId ?? null }) + .session(session) + .lean(); + if (previousChannel?.createdBy !== input.userId) + return { ok: false, code: 'route_in_use' }; + } const channel = await channels .findOne({ channelId: input.channelId,