-
Notifications
You must be signed in to change notification settings - Fork 536
feat: extract @hypr/helpchat shared package for Chatwoot integration #4022
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
Closed
devin-ai-integration
wants to merge
3
commits into
main
from
devin/1771298581-helpchat-shared-package
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,91 +1,2 @@ | ||
| import { fetch as tauriFetch } from "@tauri-apps/plugin-http"; | ||
| import { useEffect, useRef } from "react"; | ||
|
|
||
| import { createClient } from "@hypr/api-client/client"; | ||
|
|
||
| import { useAuth } from "../auth"; | ||
| import { env } from "../env"; | ||
|
|
||
| export function useChatwootEvents({ | ||
| pubsubToken, | ||
| conversationId, | ||
| onAgentMessage, | ||
| }: { | ||
| pubsubToken: string | null; | ||
| conversationId: number | null; | ||
| onAgentMessage: (content: string, senderName: string) => void; | ||
| }) { | ||
| const { session } = useAuth(); | ||
| const onAgentMessageRef = useRef(onAgentMessage); | ||
| onAgentMessageRef.current = onAgentMessage; | ||
|
|
||
| useEffect(() => { | ||
| if (!pubsubToken || conversationId == null || !session?.access_token) { | ||
| return; | ||
| } | ||
|
|
||
| const abortController = new AbortController(); | ||
|
|
||
| const client = createClient({ baseUrl: env.VITE_API_URL }); | ||
| const url = client.buildUrl({ | ||
| url: "/support/chatwoot/conversations/{conversation_id}/events", | ||
| path: { conversation_id: conversationId }, | ||
| query: { pubsub_token: pubsubToken }, | ||
| }); | ||
|
|
||
| (async () => { | ||
| try { | ||
| const response = await tauriFetch(url, { | ||
| method: "GET", | ||
| headers: { | ||
| Accept: "text/event-stream", | ||
| Authorization: `Bearer ${session.access_token}`, | ||
| }, | ||
| signal: abortController.signal, | ||
| }); | ||
|
|
||
| if (!response.ok || !response.body) { | ||
| return; | ||
| } | ||
|
|
||
| const reader = response.body.getReader(); | ||
| const decoder = new TextDecoder(); | ||
| let buffer = ""; | ||
|
|
||
| while (true) { | ||
| const { done, value } = await reader.read(); | ||
| if (done) break; | ||
|
|
||
| buffer += decoder.decode(value, { stream: true }); | ||
| const parts = buffer.split("\n\n"); | ||
| buffer = parts.pop() ?? ""; | ||
|
|
||
| for (const part of parts) { | ||
| const dataLine = part | ||
| .split("\n") | ||
| .find((line) => line.startsWith("data: ")); | ||
| if (!dataLine) continue; | ||
|
|
||
| try { | ||
| const payload = JSON.parse(dataLine.slice(6)); | ||
| if (payload.content) { | ||
| onAgentMessageRef.current( | ||
| payload.content, | ||
| payload.senderName ?? "Agent", | ||
| ); | ||
| } | ||
| } catch {} | ||
| } | ||
| } | ||
| } catch (e) { | ||
| if (!abortController.signal.aborted) { | ||
| console.error("Chatwoot events stream error:", e); | ||
| } | ||
| } | ||
| })(); | ||
|
|
||
| return () => { | ||
| abortController.abort(); | ||
| }; | ||
| }, [pubsubToken, conversationId, session?.access_token]); | ||
| } | ||
| export { useAgentEvents } from "@hypr/helpchat"; | ||
| export type { AgentMessage } from "@hypr/helpchat"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,109 +1,35 @@ | ||
| import { useCallback, useEffect, useRef, useState } from "react"; | ||
| import { fetch as tauriFetch } from "@tauri-apps/plugin-http"; | ||
| import { useMemo } from "react"; | ||
|
|
||
| import { | ||
| createContact, | ||
| createConversation, | ||
| sendMessage, | ||
| } from "@hypr/api-client"; | ||
| import { createClient } from "@hypr/api-client/client"; | ||
| import type { AgentMessage, ContactInfo, HelpChatConfig } from "@hypr/helpchat"; | ||
| import { useHelpChat } from "@hypr/helpchat"; | ||
|
|
||
| import { useAuth } from "../auth"; | ||
| import { env } from "../env"; | ||
|
|
||
| function makeClient(accessToken?: string | null) { | ||
| const headers: Record<string, string> = {}; | ||
| if (accessToken) { | ||
| headers.Authorization = `Bearer ${accessToken}`; | ||
| } | ||
| return createClient({ baseUrl: env.VITE_API_URL, headers }); | ||
| } | ||
| export type { AgentMessage } from "@hypr/helpchat"; | ||
|
|
||
| export function useChatwootPersistence( | ||
| userId: string | undefined, | ||
| contactInfo?: { | ||
| email?: string; | ||
| name?: string; | ||
| customAttributes?: Record<string, unknown>; | ||
| }, | ||
| contactInfo?: ContactInfo, | ||
| onHumanAgentMessage?: (message: AgentMessage) => void, | ||
| ) { | ||
| const { session } = useAuth(); | ||
| const [sourceId, setSourceId] = useState<string | null>(null); | ||
| const [pubsubToken, setPubsubToken] = useState<string | null>(null); | ||
| const [conversationId, setConversationId] = useState<number | null>(null); | ||
| const conversationIdRef = useRef<number | null>(null); | ||
| const initRef = useRef(false); | ||
|
|
||
| useEffect(() => { | ||
| if (!userId || initRef.current) { | ||
| return; | ||
| } | ||
| initRef.current = true; | ||
|
|
||
| const client = makeClient(session?.access_token); | ||
|
|
||
| createContact({ | ||
| client, | ||
| body: { | ||
| identifier: userId, | ||
| email: contactInfo?.email, | ||
| name: contactInfo?.name, | ||
| customAttributes: contactInfo?.customAttributes, | ||
| }, | ||
| }).then(({ data }) => { | ||
| if (data) { | ||
| setSourceId(data.sourceId); | ||
| setPubsubToken(data.pubsubToken); | ||
| } | ||
| }); | ||
| }, [userId, session?.access_token]); | ||
|
|
||
| const startConversation = useCallback(async () => { | ||
| if (!sourceId) { | ||
| return null; | ||
| } | ||
|
|
||
| const client = makeClient(session?.access_token); | ||
| const { data } = await createConversation({ | ||
| client, | ||
| body: { sourceId }, | ||
| }); | ||
|
|
||
| if (data) { | ||
| const convId = data.conversationId; | ||
| conversationIdRef.current = convId; | ||
| setConversationId(convId); | ||
| return convId; | ||
| } | ||
| return null; | ||
| }, [sourceId, session?.access_token]); | ||
|
|
||
| const persistMessage = useCallback( | ||
| async (content: string, messageType: "incoming" | "outgoing") => { | ||
| const convId = conversationIdRef.current; | ||
| if (convId == null || !sourceId) { | ||
| return; | ||
| } | ||
|
|
||
| const client = makeClient(session?.access_token); | ||
| await sendMessage({ | ||
| client, | ||
| path: { conversation_id: convId }, | ||
| body: { | ||
| content, | ||
| messageType, | ||
| sourceId, | ||
| }, | ||
| }); | ||
| }, | ||
| [sourceId, session?.access_token], | ||
| const config: HelpChatConfig = useMemo( | ||
| () => ({ | ||
| apiBaseUrl: env.VITE_API_URL, | ||
| accessToken: session?.access_token, | ||
| fetchFn: tauriFetch as HelpChatConfig["fetchFn"], | ||
| }), | ||
| [session?.access_token], | ||
| ); | ||
|
|
||
| return { | ||
| sourceId, | ||
| pubsubToken, | ||
| conversationId, | ||
| startConversation, | ||
| persistMessage, | ||
| isReady: !!sourceId, | ||
| }; | ||
| return useHelpChat({ | ||
| config, | ||
| userId, | ||
| contactInfo, | ||
| autoResume: true, | ||
| onHumanAgentMessage, | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "name": "@hypr/helpchat", | ||
| "exports": { | ||
| ".": "./src/index.ts" | ||
| }, | ||
| "dependencies": { | ||
| "@hypr/api-client": "workspace:*" | ||
| }, | ||
| "peerDependencies": { | ||
| "react": "^19.2.3" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/react": "^19.2.13" | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡
lastPersistedCountRefskips persisting regenerated assistant messagesWhen a user triggers
regenerate(wired toonReloadinChatBody), the last assistant message is removed from themessagesarray and a new streaming response begins. However,lastPersistedCountRefstill holds the old higher count, so the regenerated message is never persisted to Chatwoot.Root Cause and Walkthrough
Consider the following sequence:
messages = [user1, asst1, user2, asst2]→lastPersistedCountRef.current = 4asst2is removed →messages = [user1, asst1, user2](length 3)"streaming"→ the effect at line 192 returns earlymessages = [user1, asst1, user2, asst2_new](length 4), status ="ready"newMessages = messages.slice(4)→[]→ returns early at line 202lastPersistedCountRefis never updated (stays at 4), andasst2_newis never persisted to ChatwootThe ref-based counter assumes messages only grow monotonically. Any operation that shrinks or replaces the array (like
regenerate) permanently desynchronizes the counter. Sincemessages.slice(N)returns[]whenN >= messages.length, all subsequent messages at indices ≤ the old count are silently dropped.Impact: After any message regeneration, the Chatwoot dashboard will be missing the regenerated assistant response, giving support agents an incomplete view of the conversation.
Prompt for agents
Was this helpful? React with 👍 or 👎 to provide feedback.