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

Setting configureSession results in a broken Chatbot #243

Closed
mobiware opened this issue May 23, 2024 · 6 comments · Fixed by #248
Closed

Setting configureSession results in a broken Chatbot #243

mobiware opened this issue May 23, 2024 · 6 comments · Fixed by #248

Comments

@mobiware
Copy link

I'm trying to use configureSession on <ChatAiWidget /> but I can't get it to work.
I've followed the step-by-step guide in the documentation but when I set the configureSession prop on <ChatAiWidget />, the chatbot window gets empty and transparent (see screenshot below).
Capture d’écran 2024-05-23 à 10 20 55

No console logs are seen even though all session callbacks are issuing logs.

See component code below

export default function SendbirdChatbot({
  userEmail,
}: SendbirdChatbotProps): React.JSX.Element | null {
  const applicationId = import.meta.env.VITE_SENDBIRD_APPLICATION_ID as
    | string
    | undefined
  const botId = import.meta.env.VITE_SENDBIRD_BOT_ID as string | undefined
  const apiHost = import.meta.env.VITE_SENDBIRD_API_HOST as string | undefined

  const issueSessionToken = useCallback(async (userId: string): Promise<string> => {
    const url = `https://api-${applicationId}.sendbird.com/v3/users/${encodeURIComponent(userId)}/token`
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json; charset=utf8',
        'Api-Token': '<API-TOKEN>'
      }
    })

    const data = await response.json()
    if (response.ok) {
      return data['token'] as string
    } else {
      throw new Error(`${data['code']} - ${data['message']}`)
    }
  }, [applicationId])

  const configureSession = useCallback(
    (): SessionHandler => {
      const sessionHandler = new SessionHandler()

      sessionHandler.onSessionTokenRequired = (resolve, reject) => {
        console.log('SessionHandler.onSessionTokenRequired()')
        issueSessionToken(userEmail ?? '').then(token => resolve(token)).catch(error => reject(error))
      }
      sessionHandler.onSessionRefreshed = () => {
        console.log('SessionHandler.onSessionRefreshed()')
      }
      sessionHandler.onSessionError = (error) => console.log(error)
      sessionHandler.onSessionClosed = () => console.log('SessionHandler.onSessionClosed()')

      return sessionHandler
    }, [issueSessionToken, userEmail]
  )

  return applicationId && botId && apiHost ? (
    <ChatAiWidget
      applicationId={applicationId}
      botId={botId}
      apiHost={apiHost}
      userId={userEmail}
      configureSession={configureSession}
    />
  ) : null
}

NOTE: this is only a POC, we are aware that we should not directly use the Api-Token client side. In the production version the session token will be issued from our backend.

@bang9
Copy link
Contributor

bang9 commented May 23, 2024

Hello, could you try like below with v1.5.11?

const configureSession = useCallback(
  (): SessionHandler => ({
    onSessionTokenRequired: (resolve, reject) => {
      console.log("SessionHandler.onSessionTokenRequired()");
      issueSessionToken(userEmail ?? "")
        .then((token) => resolve(token))
        .catch((error) => reject(error));
    },
    onSessionRefreshed: () => {
      console.log("SessionHandler.onSessionRefreshed()");
    },
    onSessionError: (error) => console.log(error),
    onSessionClosed: () => console.log("SessionHandler.onSessionClosed()"),
  }),
  [issueSessionToken, userEmail]
);

We perform instance checks within the SDK, but currently, the widget does not use the SDK as a peer dependency, so instance checks were not working with the same module.

To address this, we have refactored it to allow usage in object form as well.
The documentation will soon be updated with real-world examples. Thank you!

@mobiware
Copy link
Author

@bang9 thanks for the update, however using the latest 1.5.11 version with SessionHandler created as a simple object didn't change anything, we still get the empty, transparent Chat window and nothing gets logged to the console, meaning that none of the SessionHandler methods gets called

@bang9
Copy link
Contributor

bang9 commented May 23, 2024

Oh.. It seems there is a timing issue during the token renewal process while connecting in the Chat SDK.
Let me check and get back to you soon

@bang9
Copy link
Contributor

bang9 commented May 24, 2024

Hi @mobiware I'm currently awaiting PR review. sendbird/sendbird-uikit-react#1107
It looks like it will probably be deployed sometime early next week. Thanks.

bang9 added a commit that referenced this issue May 27, 2024
## Changes
- [UIKit] merge `main` into `ai-widget/experimental` branch and update
HEAD.
- Do not reuse the cached session if the user ID has been changed in
manual strategy.

ticket: [AC-2476]
resolve: #243

[AC-2476]:
https://sendbird.atlassian.net/browse/AC-2476?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
@bang9
Copy link
Contributor

bang9 commented May 28, 2024

@mobiware v1.5.12 has been released!

@mobiware
Copy link
Author

mobiware commented Jun 5, 2024

@bang9 thanks, the bot is not broken anymore on the latest version but most of the time we don't see onSessionTokenRequired being triggered, even in the new sample app you've provided. I've created a detailed ticket about this issue: #266

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants