Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement toggle ai features mutation #10457

Merged
merged 8 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions codegen.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,16 +122,16 @@
"NotifyMentioned": "../../postgres/types/Notification.d#MentionedNotification as MentionedNotificationDB",
"NotifyPaymentRejected": "../../postgres/types/Notification.d#PaymentRejectedNotification as PaymentRejectedNotificationDB",
"NotifyPromoteToOrgLeader": "../../postgres/types/Notification.d#PromoteToBillingLeaderNotification as PromoteToBillingLeaderNotificationDB",
"NotifyPromptToJoinOrg": "../../postgres/types/Notification.d#PromptToJoinOrgNotification as PromptToJoinOrgNotificationDB",
"NotifyRequestToJoinOrg": "../../postgres/types/Notification.d#RequestToJoinOrgNotification as RequestToJoinOrgNotificationDB",
"NotifyResponseMentioned": "../../postgres/types/Notification.d#ResponseMentionedNotification as ResponseMentionedNotificationDB",
"NotifyResponseReplied": "../../postgres/types/Notification.d#ResponseRepliedNotification as ResponseRepliedNotificationDB",
"NotifyTaskInvolves": "../../postgres/types/Notification.d#TaskInvolvesNotification as TaskInvolvesNotificationDB",
"NotifyTeamArchived": "../../postgres/types/Notification.d#TeamArchivedNotification as TeamArchivedNotificationDB",
"NotifyTeamsLimitReminder": "../../postgres/types/Notification.d#TeamsLimitReminderNotification as TeamsLimitReminderNotificationDB",
"NotifyTeamsLimitExceeded": "../../postgres/types/Notification.d#TeamsLimitExceededNotification as TeamsLimitExceededNotificationDB",
"NotifyPromptToJoinOrg": "../../postgres/types/Notification.d#PromptToJoinOrgNotification as PromptToJoinOrgNotificationDB",
"Organization": "../../postgres/types/index#Organization as OrganizationDB",
"NotifyTeamsLimitReminder": "../../postgres/types/Notification.d#TeamsLimitReminderNotification as TeamsLimitReminderNotificationDB",
"OrgIntegrationProviders": "./types/OrgIntegrationProviders#OrgIntegrationProvidersSource",
"Organization": "../../postgres/types/index#Organization as OrganizationDB",
"OrganizationUser": "../../postgres/types/index#OrganizationUser as OrganizationUserDB",
"PokerMeeting": "../../postgres/types/Meeting#PokerMeeting",
"PokerMeetingMember": "../../postgres/types/Meeting.d#PokerMeetingMember as PokerMeetingMemberDB",
Expand Down Expand Up @@ -196,6 +196,7 @@
"TemplateScaleValue": "./types/TemplateScaleValue#TemplateScaleValueSource as TemplateScaleValueSourceDB",
"Threadable": "./types/Threadable#ThreadableSource",
"TimelineEventTeamPromptComplete": "./types/TimelineEventTeamPromptComplete#TimelineEventTeamPromptCompleteSource",
"ToggleAIFeaturesSuccess": "./types/ToggleAIFeaturesSuccess#ToggleAIFeaturesSuccessSource",
"ToggleFavoriteTemplateSuccess": "./types/ToggleFavoriteTemplateSuccess#ToggleFavoriteTemplateSuccessSource",
"ToggleFeatureFlagSuccess": "./types/ToggleFeatureFlagSuccess#ToggleFeatureFlagSuccessSource",
"ToggleSummaryEmailSuccess": "./types/ToggleSummaryEmailSuccess#ToggleSummaryEmailSuccessSource",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ interface Props {
}

const isServer = typeof window === 'undefined'
const hasAI = isServer
const hasAiApiKey = isServer
? !!process.env.OPEN_AI_API_KEY
: !!window.__ACTION__ && !!window.__ACTION__.hasOpenAI

Expand All @@ -25,7 +25,7 @@ const WholeMeetingSummary = (props: Props) => {
summary
organization {
hasStandupAISummaryFlag: featureFlag(featureName: "standupAISummary")
hasNoAISummaryFlag: featureFlag(featureName: "noAISummary")
useAI
}
... on RetrospectiveMeeting {
reflectionGroups(sortBy: voteCount) {
Expand All @@ -47,15 +47,16 @@ const WholeMeetingSummary = (props: Props) => {
const {summary: wholeMeetingSummary, reflectionGroups, organization} = meeting
const reflections = reflectionGroups?.flatMap((group) => group.reflections) // reflectionCount hasn't been calculated yet so check reflections length
const hasMoreThanOneReflection = reflections?.length && reflections.length > 1
if (!hasMoreThanOneReflection || organization.hasNoAISummaryFlag || !hasAI) return null
if (!hasMoreThanOneReflection || !organization.useAI || !hasAiApiKey) return null
if (!wholeMeetingSummary) return <WholeMeetingSummaryLoading />
return <WholeMeetingSummaryResult meetingRef={meeting} />
} else if (meeting.__typename === 'TeamPromptMeeting') {
const {summary: wholeMeetingSummary, responses, organization} = meeting
const {hasStandupAISummaryFlag, useAI} = organization
if (
!organization.hasStandupAISummaryFlag ||
organization.hasNoAISummaryFlag ||
!hasAI ||
!hasStandupAISummaryFlag ||
!useAI ||
!hasAiApiKey ||
!responses ||
responses.length === 0
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ const NewCheckInQuestion = (props: Props) => {
}
team {
organization {
hasNoAISummaryFlag: featureFlag(featureName: "noAISummary")
useAI
}
}
}
Expand All @@ -101,7 +101,7 @@ const NewCheckInQuestion = (props: Props) => {
localPhase,
facilitatorUserId,
team: {
organization: {hasNoAISummaryFlag}
organization: {useAI}
}
} = meeting
const {checkInQuestion} = localPhase
Expand Down Expand Up @@ -226,7 +226,7 @@ const NewCheckInQuestion = (props: Props) => {
}
})
}
const showAiIcebreaker = !hasNoAISummaryFlag && isFacilitating && window.__ACTION__.hasOpenAI
const showAiIcebreaker = useAI && isFacilitating && window.__ACTION__.hasOpenAI

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const OrgDetails = (props: Props) => {
...OrgBillingDangerZone_organization
...EditableOrgName_organization
...OrgFeatureFlags_organization
...OrgFeatures_organization
orgId: id
isBillingLeader
createdAt
Expand Down Expand Up @@ -70,7 +71,7 @@ const OrgDetails = (props: Props) => {
</div>
</div>

<OrgFeatures />
<OrgFeatures organizationRef={organization} />
<OrgFeatureFlags organizationRef={organization} />
<OrgBillingDangerZone organization={organization} isWide />
</Suspense>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ interface Props {
organizationRef: OrgFeatureFlags_organization$key
}

const OrgFeatureFlags = ({organizationRef}: Props) => {
const OrgFeatureFlags = (props: Props) => {
const {organizationRef} = props
const atmosphere = useAtmosphere()
const {onError, onCompleted} = useMutationProps()
const organization = useFragment(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import styled from '@emotion/styled'
import {Info as InfoIcon} from '@mui/icons-material'
import React, {useState} from 'react'
import graphql from 'babel-plugin-relay/macro'
import React from 'react'
import {useFragment} from 'react-relay'
import {OrgFeatures_organization$key} from '../../../../__generated__/OrgFeatures_organization.graphql'
import Panel from '../../../../components/Panel/Panel'
import Toggle from '../../../../components/Toggle/Toggle'
import useAtmosphere from '../../../../hooks/useAtmosphere'
import useMutationProps from '../../../../hooks/useMutationProps'
import ToggleAIFeaturesMutation from '../../../../mutations/ToggleAIFeaturesMutation'
import {PALETTE} from '../../../../styles/paletteV3'
import {ElementWidth, Layout} from '../../../../types/constEnums'
import {Tooltip} from '../../../../ui/Tooltip/Tooltip'
Expand Down Expand Up @@ -34,23 +40,49 @@ const FeatureNameGroup = styled('div')({
}
})

const OrgFeatures = () => {
const [showAIFeatures, setShowAIFeatures] = useState(false)
interface Props {
organizationRef: OrgFeatures_organization$key
}

const OrgFeatures = (props: Props) => {
const {organizationRef} = props
const atmosphere = useAtmosphere()
const {onError, onCompleted} = useMutationProps()
const organization = useFragment(
graphql`
fragment OrgFeatures_organization on Organization {
id
isOrgAdmin
useAI
}
`,
organizationRef
)
const {id: orgId, isOrgAdmin, useAI} = organization

const handleToggle = () => {
const variables = {orgId}
ToggleAIFeaturesMutation(atmosphere, variables, {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 if you use the useMutation pattern instead of the older pattern then you don't need useMutationProps in this component & it'll be a little cleaner

onError,
onCompleted
})
}

if (!isOrgAdmin) return null
return (
<StyledPanel isWide label='AI Features'>
<PanelRow>
<FeatureRow>
<FeatureNameGroup>
<span>Show AI Features</span>
<span>Enable AI Features</span>
<Tooltip>
<TooltipTrigger className='bg-transparent hover:cursor-pointer'>
<InfoIcon className='h-4 w-4 text-slate-600' />
</TooltipTrigger>
<TooltipContent>Enable AI-powered features across your organization</TooltipContent>
</Tooltip>
</FeatureNameGroup>
<Toggle active={showAIFeatures} onClick={() => setShowAIFeatures(!showAIFeatures)} />
<Toggle active={useAI} onClick={handleToggle} />
</FeatureRow>
</PanelRow>
</StyledPanel>
Expand Down
4 changes: 2 additions & 2 deletions packages/client/mutations/EndRetrospectiveMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ graphql`
groupTitle
}
organization {
hasNoAISummaryFlag: featureFlag(featureName: "noAISummary")
useAI
}
reflectionGroups(sortBy: voteCount) {
reflections {
Expand Down Expand Up @@ -125,7 +125,7 @@ export const endRetrospectiveTeamOnNext: OnNextHandler<
const reflections = reflectionGroups.flatMap((group) => group.reflections) // reflectionCount hasn't been calculated yet so check reflections length
const hasMoreThanOneReflection = reflections.length > 1
const hasOpenAISummary =
hasMoreThanOneReflection && !organization.hasNoAISummaryFlag && window.__ACTION__.hasOpenAI
hasMoreThanOneReflection && organization.useAI && window.__ACTION__.hasOpenAI
const hasTeamHealth = phases.some((phase) => phase.phaseType === 'TEAM_HEALTH')
const pathname = `/new-summary/${meetingId}`
const search = new URLSearchParams()
Expand Down
41 changes: 41 additions & 0 deletions packages/client/mutations/ToggleAIFeaturesMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import graphql from 'babel-plugin-relay/macro'
import {commitMutation} from 'react-relay'
import {ToggleAIFeaturesMutation as TToggleAIFeaturesMutation} from '../__generated__/ToggleAIFeaturesMutation.graphql'
import {StandardMutation} from '../types/relayMutations'

graphql`
fragment ToggleAIFeaturesMutation_organization on ToggleAIFeaturesSuccess {
organization {
id
useAI
}
}
`

const mutation = graphql`
mutation ToggleAIFeaturesMutation($orgId: ID!) {
toggleAIFeatures(orgId: $orgId) {
... on ErrorPayload {
error {
message
}
}
...ToggleAIFeaturesMutation_organization @relay(mask: false)
}
}
`

const ToggleAIFeaturesMutation: StandardMutation<TToggleAIFeaturesMutation> = (
atmosphere,
variables,
{onError, onCompleted}
) => {
return commitMutation<TToggleAIFeaturesMutation>(atmosphere, {
mutation,
variables,
onCompleted,
onError
})
}

export default ToggleAIFeaturesMutation
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,15 @@ import {Team} from '../../../postgres/types'
import {DataLoaderWorker} from '../../graphql'
import {getFeatureTier} from '../../types/helpers/getFeatureTier'

const canAccessAISummary = async (
const canAccessAI = async (
team: Team,
userId: string,
meetingType: 'standup' | 'retrospective',
dataLoader: DataLoaderWorker
) => {
const {qualAIMeetingsCount, orgId} = team
const [noAIOrgSummary, noAIUserSummary] = await Promise.all([
dataLoader.get('featureFlagByOwnerId').load({ownerId: orgId, featureName: 'noAISummary'}),
dataLoader.get('featureFlagByOwnerId').load({ownerId: userId, featureName: 'noAISummary'})
])
const org = await dataLoader.get('organizations').loadNonNull(orgId)

if (noAIOrgSummary || noAIUserSummary) return false
if (!org.useAI) return false
if (meetingType === 'standup') {
const hasStandupFlag = await dataLoader
.get('featureFlagByOwnerId')
Expand All @@ -27,4 +23,4 @@ const canAccessAISummary = async (
return qualAIMeetingsCount < Threshold.MAX_QUAL_AI_MEETINGS
}

export default canAccessAISummary
export default canAccessAI
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import getKysely from '../../../postgres/getKysely'
import OpenAIServerManager from '../../../utils/OpenAIServerManager'
import sendToSentry from '../../../utils/sendToSentry'
import {DataLoaderWorker} from '../../graphql'
import canAccessAISummary from './canAccessAISummary'
import canAccessAI from './canAccessAI'

const generateDiscussionPrompt = async (
meetingId: string,
Expand All @@ -14,13 +14,8 @@ const generateDiscussionPrompt = async (
dataLoader.get('users').loadNonNull(facilitatorUserId),
dataLoader.get('teams').loadNonNull(teamId)
])
const isAISummaryAccessible = await canAccessAISummary(
team,
facilitator.id,
'retrospective',
dataLoader
)
if (!isAISummaryAccessible) return
const isAIAvailable = await canAccessAI(team, 'retrospective', dataLoader)
if (!isAIAvailable) return
const [reflections, reflectionGroups] = await Promise.all([
dataLoader.get('retroReflectionsByMeetingId').load(meetingId),
dataLoader.get('retroReflectionGroupsByMeetingId').load(meetingId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,17 @@ import {RetrospectiveMeeting} from '../../../postgres/types/Meeting'
import OpenAIServerManager from '../../../utils/OpenAIServerManager'
import publish from '../../../utils/publish'
import {DataLoaderWorker} from '../../graphql'
import canAccessAISummary from './canAccessAISummary'
import canAccessAI from './canAccessAI'

const generateDiscussionSummary = async (
discussionId: string,
meeting: RetrospectiveMeeting,
dataLoader: DataLoaderWorker
) => {
const {id: meetingId, endedAt, facilitatorUserId, teamId} = meeting
const [facilitator, team] = await Promise.all([
dataLoader.get('users').loadNonNull(facilitatorUserId!),
dataLoader.get('teams').loadNonNull(teamId)
])
const isAISummaryAccessible = await canAccessAISummary(
team,
facilitator.id,
'retrospective',
dataLoader
)
if (!isAISummaryAccessible) return
const {id: meetingId, endedAt, teamId} = meeting
const team = await dataLoader.get('teams').loadNonNull(teamId)
const isAIAvailable = await canAccessAI(team, 'retrospective', dataLoader)
if (!isAIAvailable) return
const [comments, tasks] = await Promise.all([
dataLoader.get('commentsByDiscussionId').load(discussionId),
dataLoader.get('tasksByDiscussionId').load(discussionId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,16 @@ import {getTeamPromptResponsesByMeetingId} from '../../../postgres/queries/getTe
import {TeamPromptMeeting} from '../../../postgres/types/Meeting'
import OpenAIServerManager from '../../../utils/OpenAIServerManager'
import {DataLoaderWorker} from '../../graphql'
import canAccessAISummary from './canAccessAISummary'
import canAccessAI from './canAccessAI'

const generateStandupMeetingSummary = async (
meeting: TeamPromptMeeting,
dataLoader: DataLoaderWorker
) => {
const [facilitator, team] = await Promise.all([
dataLoader.get('users').loadNonNull(meeting.facilitatorUserId!),
dataLoader.get('teams').loadNonNull(meeting.teamId)
])
const isAISummaryAccessible = await canAccessAISummary(
team,
facilitator.id,
'standup',
dataLoader
)
const team = await dataLoader.get('teams').loadNonNull(meeting.teamId)
const isAIAvailable = await canAccessAI(team, 'standup', dataLoader)
if (!isAIAvailable) return

if (!isAISummaryAccessible) return
const responses = await getTeamPromptResponsesByMeetingId(meeting.id)

const contentToSummarize = responses.map((response) => response.plaintextContent)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import {DataLoaderWorker} from '../../graphql'
import canAccessAI from './canAccessAI'

const generateWholeMeetingSentimentScore = async (
meetingId: string,
facilitatorUserId: string,
dataLoader: DataLoaderWorker
) => {
const [facilitator, reflections] = await Promise.all([
dataLoader.get('users').loadNonNull(facilitatorUserId),
const [meeting, reflections] = await Promise.all([
dataLoader.get('newMeetings').loadNonNull(meetingId),
dataLoader.get('retroReflectionsByMeetingId').load(meetingId)
])
const hasNoAISummary = await dataLoader
.get('featureFlagByOwnerId')
.load({ownerId: facilitator.id, featureName: 'noAISummary'})
if (hasNoAISummary || reflections.length === 0) return undefined
const team = await dataLoader.get('teams').loadNonNull(meeting.teamId)
const isAIAvailable = await canAccessAI(team, 'retrospective', dataLoader)
if (!isAIAvailable || reflections.length === 0) return undefined
const reflectionsWithSentimentScores = reflections.filter(
({sentimentScore}) => sentimentScore !== undefined
)
Expand Down
Loading
Loading