import { PermissionAction } from '@supabase/shared-types/out/constants' import { useState } from 'react' import { AI_OPT_IN_LEVEL_LABELS } from './AiAssistant.constants' import { AIOptInModal } from './AIOptInModal' import { Confirm } from './Confirm' import type { ConfirmFooterApprovalState } from './Confirm.utils' import { NoPermission } from '@/components/ui/NoPermission' import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions' import { useOrgAiOptInLevel, type AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi' import { contract } from '@/lib/ai/tools/update-opt-in-level' interface OptInRequestProps { /** Omitted when the Assistant is only asking the user to review the setting. */ requiredLevel?: AiOptInLevel /** The org's level when the Assistant asked. Falls back to the live level on older chats. */ levelWhenAsked?: AiOptInLevel output?: unknown confirmState?: ConfirmFooterApprovalState onApprove?: () => void onDeny?: () => void } /** Approval card for `update_opt_in_level`. Saving in the modal approves, Skip denies. */ export const OptInRequest = ({ requiredLevel, levelWhenAsked, output, confirmState, onApprove, onDeny, }: OptInRequestProps) => { const [isModalVisible, setIsModalVisible] = useState(false) const { aiOptInLevel: liveLevel } = useOrgAiOptInLevel() const aiOptInLevel = levelWhenAsked ?? liveLevel const { can: canUpdateOrganization } = useAsyncCheckPermissions( PermissionAction.UPDATE, 'organizations' ) const requiredLabel = requiredLevel && AI_OPT_IN_LEVEL_LABELS[requiredLevel] const result = contract.outputSchema.safeParse(output).data // Saving a lower level still approves the call const isBelowRequest = confirmState === 'success' && result?.sufficient === false const newLevel = result?.levelAfterReview const successMessage = newLevel && newLevel !== aiOptInLevel ? `Opt-in level updated to ${AI_OPT_IN_LEVEL_LABELS[newLevel]}` : `Opt-in level is still ${AI_OPT_IN_LEVEL_LABELS[aiOptInLevel]}` let message = 'Only an owner or administrator can change the opt-in level' if (canUpdateOrganization) message = 'Assistant wants you to review the opt-in level' if (requiredLabel) { message = canUpdateOrganization ? `Assistant wants ${requiredLabel} access` : `The Assistant will answer without ${requiredLabel} access` } return ( <> setIsModalVisible(true)} > {canUpdateOrganization ? (

{requiredLabel ? `${requiredLabel} access needed` : 'Review opt-in level'}

{requiredLabel && ( {`The Assistant needs the ${requiredLabel} opt-in level to answer this. `} )} {`Your organization is set to ${AI_OPT_IN_LEVEL_LABELS[aiOptInLevel]}.`}

) : ( )}
setIsModalVisible(false)} onSaved={() => onApprove?.()} /> ) }