👥 fix: Let Members Connect Agents to Slack Workspaces (#17835)

* 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
This commit is contained in:
Dustin Healy 2026-11-10 21:04:11 -08:00 • committed by GitHub
parent 567aeefe93
commit 3e19ef42fe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 847 additions and 236 deletions

View file

@ -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,

View file

@ -16,12 +16,18 @@ const statusColors: Record<AgentChannel['status'], string> = {
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 (
<span className="text-text-secondary inline-flex shrink-0 items-center gap-1.5 text-xs">
<span aria-hidden="true" className={`size-1.5 rounded-full ${statusColors[status]}`} />
{localize(statusLabels[status])}
{localize(status === 'pending_install' ? pendingLabel : statusLabels[status])}
</span>
);
}

View file

@ -30,6 +30,12 @@ const actionLabels: Record<AgentChannel['status'], TranslationKeys> = {
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<HTMLButtonElement | null>(null);
const [dialog, setDialog] = useState<string | null>(null);
const [newWorkspaceConnection, setNewWorkspaceConnection] = useState<string | null>(null);
const [credentialMode, setCredentialMode] = useState<AgentChannel['credentialMode']>('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) {
<div key={channel.channelId} className="flex items-center justify-between gap-2 text-sm">
<div className="flex min-w-0 items-center gap-2">
{localize('com_ui_channels_slack')}
<ChannelStatus status={channel.status} />
<ChannelStatus
status={channel.status}
pendingLabel={
channel.workspaceId ? 'com_ui_channels_workspace_not_assigned' : undefined
}
/>
</div>
<Button
type="button"
@ -542,14 +553,11 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) {
}
onClick={(event) => {
triggerRef.current = event.currentTarget;
setNewWorkspaceConnection(null);
setDialog(channel.channelId);
}}
>
{localize(
channel.createdBy !== userId
? 'com_ui_channels_read_only'
: actionLabels[channel.status],
)}
{localize(channelActionLabel(channel, userId))}
</Button>
</div>
))}
@ -629,47 +637,40 @@ function OwnedChannels({ agentId, userId, tenantId }: ChannelsProps) {
<p className="text-text-secondary text-sm">
{localize('com_ui_channels_workspace_identity')}
</p>
{!workspaceStatus?.canManage && (
<p>{localize('com_ui_slack_workspaces_admin')}</p>
<h4 className="text-sm font-medium">
{localize('com_ui_channels_workspace_choose')}
</h4>
{availableWorkspaces.length === 0 && (
<p>{localize('com_ui_channels_workspace_connect_first')}</p>
)}
{workspaceStatus?.canManage && (
<>
<h4 className="text-sm font-medium">
{localize('com_ui_channels_workspace_choose')}
</h4>
{availableWorkspaces.length === 0 && (
<p>{localize('com_ui_channels_workspace_connect_first')}</p>
)}
<div
role="group"
aria-label={localize('com_ui_channels_workspace_choose')}
className="flex max-h-52 flex-col gap-2 overflow-y-auto"
<div
role="group"
aria-label={localize('com_ui_channels_workspace_choose')}
className="flex max-h-52 flex-col gap-2 overflow-y-auto"
>
{availableWorkspaces.map((workspace) => (
<Button
key={workspace.workspaceId}
type="button"
variant="outline-toggle"
className="justify-start text-left break-words whitespace-normal"
aria-pressed={workspaceId === workspace.workspaceId}
disabled={create.isLoading}
onClick={() => setWorkspaceId(workspace.workspaceId)}
>
{availableWorkspaces.map((workspace) => (
<Button
key={workspace.workspaceId}
type="button"
variant="outline-toggle"
className="justify-start text-left break-words whitespace-normal"
aria-pressed={workspaceId === workspace.workspaceId}
disabled={create.isLoading}
onClick={() => setWorkspaceId(workspace.workspaceId)}
>
{workspace.teamName}
</Button>
))}
</div>
{workspaces.hasNextPage && (
<Button
type="button"
variant="outline"
disabled={workspaces.isFetchingNextPage}
onClick={() => void workspaces.fetchNextPage()}
>
{localize('com_ui_slack_workspaces_more')}
</Button>
)}
</>
{workspace.teamName}
</Button>
))}
</div>
{workspaces.hasNextPage && (
<Button
type="button"
variant="outline"
disabled={workspaces.isFetchingNextPage}
onClick={() => void workspaces.fetchNextPage()}
>
{localize('com_ui_slack_workspaces_more')}
</Button>
)}
</div>
)}
@ -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) {
<WorkspaceChannel
key={selected.channelId}
agentId={agentId}
initialSetup={newWorkspaceConnection === selected.channelId}
channel={selected}
userId={userId}
tenantId={tenantId}

View file

@ -1,20 +1,34 @@
import { useEffect, useId, useRef, useState } from 'react';
import { ExternalLink, Plus } from 'lucide-react';
import { dataService, QueryKeys, MutationKeys } from 'librechat-data-provider';
import { Button, Checkbox, Input, Label, OGDialogFooter, Separator } from '@librechat/client';
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Alert,
Button,
Input,
Label,
OGDialog,
OGDialogTemplate,
OGDialogFooter,
Separator,
Tag,
} from '@librechat/client';
import type { AgentChannel, SlackWorkspaceRouteTarget } from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
import { channelErrorLabel } from '~/utils/channelErrors';
import { useLocalize, useDebounce } from '~/hooks';
import ChannelStatus from './ChannelStatus';
type Action =
| { kind: 'assign' }
| { kind: 'assign'; replacementRevision?: string }
| { kind: 'remove'; target: SlackWorkspaceRouteTarget }
| { kind: 'disable' | 'delete' };
| { kind: 'disable' }
| { kind: 'delete' };
/** Installation credentials never enter Agent Builder; only routing and personal-link consent do. */
export default function WorkspaceChannel({
agentId,
initialSetup,
channel,
userId,
tenantId,
@ -22,6 +36,7 @@ export default function WorkspaceChannel({
onClose,
}: {
agentId: string;
initialSetup: boolean;
channel: AgentChannel;
userId: string;
tenantId?: string;
@ -47,26 +62,31 @@ export default function WorkspaceChannel({
];
const [specific, setSpecific] = useState(false);
const [externalChannel, setExternalChannel] = useState('');
const [replace, setReplace] = useState(false);
const [editing, setEditing] = useState(initialSetup);
const actionRef = useRef<HTMLButtonElement | null>(null);
const addRef = useRef<HTMLButtonElement | null>(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 (
<>
<div className="min-h-0 space-y-4 overflow-y-auto px-6 pb-6 text-sm">
@ -158,9 +208,23 @@ export default function WorkspaceChannel({
<span className="min-w-0 flex-1 font-medium break-words">
{workspace.data?.workspace.teamName ?? localize('com_ui_channels_org_workspace')}
</span>
<ChannelStatus status={channel.status} />
<ChannelStatus
status={channel.status}
pendingLabel="com_ui_channels_workspace_not_assigned"
/>
</div>
<p className="text-text-secondary">{localize('com_ui_channels_workspace_identity')}</p>
{workspace.data && (
<a
href={`https://slack.com/app_redirect?app=${encodeURIComponent(workspace.data.workspace.appId)}&team=${encodeURIComponent(workspace.data.workspace.teamId)}`}
target="_blank"
rel="noopener noreferrer"
className="text-text-secondary hover:text-text-primary inline-flex items-center gap-1 underline underline-offset-2"
>
{localize('com_ui_channels_workspace_open_bot')}
<ExternalLink className="size-3" aria-hidden="true" />
</a>
)}
{workspace.isLoading && <p role="status">{localize('com_ui_channels_loading')}</p>}
{workspace.isError && (
<div role="alert">
@ -173,17 +237,27 @@ export default function WorkspaceChannel({
{workspace.data && !available && (
<p role="status">{localize('com_ui_channels_workspace_unavailable')}</p>
)}
{workspace.data && !canManage && <p>{localize('com_ui_slack_workspaces_admin')}</p>}
{!ownsChannel && <p>{localize('com_ui_channels_read_only')}</p>}
{mutation.isError && (
<p role="alert">
{localize(channelErrorLabel(mutation.error, 'com_ui_channels_workspace_route_error'))}
</p>
)}
{canManage && (
<section className="space-y-2" aria-labelledby={`${id}-routes`}>
<h4 id={`${id}-routes`} className="font-medium">
{localize('com_ui_channels_workspace_routes')}
</h4>
{!editing && ownsChannel && (
<section
className="space-y-2"
aria-labelledby={entries.length > 0 ? `${id}-routes` : undefined}
aria-label={
entries.length === 0
? localize('com_ui_channels_workspace_add_assignment')
: undefined
}
>
{entries.length > 0 && (
<h4 id={`${id}-routes`} className="font-medium">
{localize('com_ui_channels_workspace_routes')}
</h4>
)}
{routes.isLoading && <p role="status">{localize('com_ui_channels_loading')}</p>}
{routes.isError && (
<div role="alert">
@ -193,11 +267,6 @@ export default function WorkspaceChannel({
</Button>
</div>
)}
{routes.isSuccess && entries.length === 0 && (
<p className="text-text-secondary">
{localize('com_ui_channels_workspace_no_routes')}
</p>
)}
{entries.map((entry) => (
<div
key={entry.externalChannelId ?? 'default'}
@ -211,7 +280,10 @@ export default function WorkspaceChannel({
variant="section-action"
size="compact"
disabled={busy}
onClick={() => setConfirm({ kind: 'remove', target: entry })}
onClick={(event) => {
actionRef.current = event.currentTarget;
setConfirm({ kind: 'remove', target: entry });
}}
>
{localize('com_ui_channels_workspace_remove_route')}
</Button>
@ -227,13 +299,38 @@ export default function WorkspaceChannel({
{localize('com_ui_channels_workspace_more_routes')}
</Button>
)}
<Button
type="button"
variant="outline"
disabled={busy || !mayRoute || !routes.isSuccess}
ref={addRef}
onClick={() => {
mutation.reset();
setSpecific(entries.some((entry) => !entry.externalChannelId));
setExternalChannel('');
setEditing(true);
}}
>
<Plus className="size-4" aria-hidden="true" />
{localize('com_ui_channels_workspace_add_assignment')}
</Button>
</section>
)}
{mayRoute && (
{editing && mayRoute && (
<section className="space-y-3" aria-labelledby={`${id}-target`}>
<h4 id={`${id}-target`} className="font-medium">
{localize('com_ui_channels_workspace_target')}
</h4>
<div className="flex items-center justify-between gap-2">
<h4 id={`${id}-target`} className="min-w-0 font-medium">
{localize('com_ui_channels_workspace_target')}
</h4>
{alreadyAssigned && (
<Tag
role="status"
className="shrink-0"
variant="success"
label={localize('com_ui_channels_workspace_assigned')}
/>
)}
</div>
<div
role="group"
aria-label={localize('com_ui_channels_workspace_target')}
@ -246,7 +343,6 @@ export default function WorkspaceChannel({
disabled={busy}
onClick={() => {
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);
}}
/>
</div>
@ -301,99 +395,145 @@ export default function WorkspaceChannel({
</Button>
</div>
)}
{replacesOther && (
<div className="border-border-medium space-y-2 rounded-lg border p-3">
<p>{localize('com_ui_channels_workspace_replace_help')}</p>
<div className="flex items-center gap-2">
<Checkbox
aria-label={localize('com_ui_channels_workspace_replace')}
id={`${id}-replace`}
checked={replace}
disabled={busy}
onCheckedChange={(value) => setReplace(value === true)}
/>
<Label htmlFor={`${id}-replace`}>
{localize('com_ui_channels_workspace_replace')}
</Label>
</div>
</div>
{blocked && (
<Alert variant="warning">{localize('com_ui_channels_workspace_route_owned')}</Alert>
)}
<Button
type="button"
disabled={
busy ||
!validTarget ||
!settledInput ||
!target.isSuccess ||
target.isFetching ||
Boolean(alreadyAssigned) ||
Boolean(replacesOther && !replace)
}
onClick={() => mutation.mutate({ kind: 'assign' })}
>
{localize(
channel.status === 'active'
? 'com_ui_channels_workspace_assign'
: 'com_ui_channels_activate',
)}
</Button>
</section>
)}
{confirm && (
<div
role="group"
aria-label={localize('com_ui_channels_workspace_confirm_title')}
className="border-border-medium space-y-3 rounded-lg border p-3"
>
<p>
{localize(
confirm.kind === 'delete'
? 'com_ui_channels_workspace_delete_confirm'
: 'com_ui_channels_workspace_remove_confirm',
)}
{replacesOther && !blocked && (
<Alert variant="warning">
{target.data?.assignedAgentName
? localize('com_ui_channels_workspace_occupied_named', {
0: target.data.assignedAgentName,
})
: localize('com_ui_channels_workspace_occupied')}
</Alert>
)}
<p className="text-text-secondary text-xs">
{localize('com_ui_channels_workspace_identity')}
</p>
<div className="flex gap-2">
<Button
type="button"
variant="destructive"
disabled={busy}
onClick={() => mutation.mutate(confirm)}
>
{localize('com_ui_confirm')}
</Button>
<Button
type="button"
variant="outline"
disabled={busy}
onClick={() => setConfirm(null)}
>
{localize('com_ui_cancel')}
</Button>
</div>
</div>
</section>
)}
</div>
<Separator />
<OGDialogFooter className="flex-wrap gap-2 px-6 py-4 sm:justify-between">
<Button
type="button"
variant="destructive-soft"
disabled={busy}
onClick={() => setConfirm({ kind: 'delete' })}
>
{localize('com_ui_delete')}
</Button>
{channel.status === 'active' && (
<Button
type="button"
variant="outline"
disabled={busy}
onClick={() => mutation.mutate({ kind: 'disable' })}
>
{localize('com_ui_channels_disable')}
</Button>
{editing ? (
<>
<Button
type="button"
variant="outline"
disabled={mutation.isLoading}
onClick={() => {
mutation.reset();
if (initialSetup) onClose();
else setEditing(false);
}}
>
{localize('com_ui_cancel')}
</Button>
{!alreadyAssigned && (
<Button
type="button"
disabled={assignmentDisabled}
aria-busy={mutation.isLoading}
onClick={(event) => {
if (replacesOther && target.data?.revision) {
actionRef.current = event.currentTarget;
setConfirm({ kind: 'assign', replacementRevision: target.data.revision });
} else mutation.mutate({ kind: 'assign' });
}}
>
{localize(
replacesOther ? replaceAssignmentLabel : 'com_ui_channels_workspace_assign',
)}
</Button>
)}
</>
) : (
<>
<Button
type="button"
variant="destructive-soft"
disabled={busy}
onClick={(event) => {
actionRef.current = event.currentTarget;
setConfirm({ kind: 'delete' });
}}
>
{localize('com_ui_channels_workspace_delete_connection')}
</Button>
{channel.status === 'active' && (
<Button
type="button"
variant="outline"
disabled={busy}
onClick={() => mutation.mutate({ kind: 'disable' })}
>
{localize('com_ui_channels_disable')}
</Button>
)}
</>
)}
</OGDialogFooter>
<OGDialog
open={confirm !== null}
onOpenChange={(open) => {
if (!open && !mutation.isLoading) setConfirm(null);
}}
>
<OGDialogTemplate
className="max-w-md"
footerClassName="sm:justify-between"
title={
confirm?.kind === 'assign' && target.data?.assignedAgentName
? localize('com_ui_channels_workspace_replace_named', {
0: target.data.assignedAgentName,
})
: localize(confirmationTitle)
}
description={workspace.data?.workspace.teamName}
cancelDisabled={mutation.isLoading}
onCloseAutoFocus={(event) => {
event.preventDefault();
if (actionRef.current?.isConnected) actionRef.current.focus();
else addRef.current?.focus();
}}
main={
<div className="space-y-3 text-sm">
<p className="text-text-secondary">{localize(confirmationHelp)}</p>
{confirm?.kind === 'assign' &&
target.data?.revision !== confirm.replacementRevision && (
<Alert variant="warning">
{localize('com_ui_channels_workspace_replacement_changed')}
</Alert>
)}
{mutation.isError && (
<Alert variant="error">
{localize(
channelErrorLabel(mutation.error, 'com_ui_channels_workspace_route_error'),
)}
</Alert>
)}
</div>
}
selection={
<Button
type="button"
variant={confirm?.kind === 'assign' ? 'default' : 'destructive'}
disabled={
busy ||
!confirm ||
(confirm.kind === 'assign' &&
(assignmentDisabled || target.data?.revision !== confirm.replacementRevision))
}
aria-busy={mutation.isLoading}
onClick={() => {
if (confirm) mutation.mutate(confirm);
}}
>
{localize(confirmationTitle)}
</Button>
}
/>
</OGDialog>
</>
);
}

View file

@ -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',

View file

@ -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.",

View file

@ -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;
}

View file

@ -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 }),

View file

@ -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<typeof channels.getAgentName>) =>
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')

View file

@ -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<boolean>;
isPrincipalActive: (id: string) => Promise<boolean>;
getAgentName: (
id: string,
tenantId: string | undefined,
viewer: { userId: string },
) => Promise<string | undefined>;
readSettings: ReturnType<typeof createSlackWorkspaceSettingsReader>;
logError: (metadata: ReturnType<typeof getSafeErrorMetadata>) => 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) {

View file

@ -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;

View file

@ -1079,7 +1079,11 @@ export function createAgentMethods(
): {
findAgentIdentity: (agentId: string) => Promise<{ _id: string } | null>;
getAgent: GetAgent;
getAgentName: (id: string, tenantId?: string) => Promise<string | undefined>;
getAgentName: (
id: string,
tenantId?: string,
viewer?: { userId: string },
) => Promise<string | undefined>;
getAgentVersions: (searchParameter: FilterQuery<IAgent>) => Promise<IAgent['versions'] | null>;
getAgentWithVersionCount: (
searchParameter: FilterQuery<IAgent>,
@ -1306,14 +1310,28 @@ export function createAgentMethods(
return await Agent.findOne(searchParameter, projection).lean<IAgent>();
};
/** Storage-neutral display-name lookup for a known execution subject. */
async function getAgentName(id: string, tenantId?: string): Promise<string | undefined> {
/** 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<string | undefined> {
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;
}
/**

View file

@ -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();

View file

@ -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<RouteResult>;
@ -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,