@tambo-ai/react 0.16.1 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/index.d.ts +8 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +32 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/use-component-state.d.ts +40 -5
- package/dist/hooks/use-component-state.d.ts.map +1 -1
- package/dist/hooks/use-component-state.js +138 -47
- package/dist/hooks/use-component-state.js.map +1 -1
- package/dist/hooks/use-streaming-props.d.ts +25 -0
- package/dist/hooks/use-streaming-props.d.ts.map +1 -0
- package/dist/hooks/use-streaming-props.js +49 -0
- package/dist/hooks/use-streaming-props.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/providers/tambo-thread-provider.d.ts +1 -1
- package/dist/providers/tambo-thread-provider.d.ts.map +1 -1
- package/dist/providers/tambo-thread-provider.js.map +1 -1
- package/esm/hooks/index.d.ts +8 -0
- package/esm/hooks/index.d.ts.map +1 -0
- package/esm/hooks/index.js +9 -0
- package/esm/hooks/index.js.map +1 -0
- package/esm/hooks/use-component-state.d.ts +40 -5
- package/esm/hooks/use-component-state.d.ts.map +1 -1
- package/esm/hooks/use-component-state.js +139 -48
- package/esm/hooks/use-component-state.js.map +1 -1
- package/esm/hooks/use-streaming-props.d.ts +25 -0
- package/esm/hooks/use-streaming-props.d.ts.map +1 -0
- package/esm/hooks/use-streaming-props.js +46 -0
- package/esm/hooks/use-streaming-props.js.map +1 -0
- package/esm/index.d.ts +1 -0
- package/esm/index.d.ts.map +1 -1
- package/esm/index.js +1 -0
- package/esm/index.js.map +1 -1
- package/esm/providers/tambo-thread-provider.d.ts +1 -1
- package/esm/providers/tambo-thread-provider.d.ts.map +1 -1
- package/esm/providers/tambo-thread-provider.js.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tambo-thread-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,6DAAkE;AAClE,+CAQe;AACf,sFAI8C;AAE9C,mEAAwE;AACxE,+CAA4E;AAC5E,qDAAqD;AACrD,mEAAyD;AACzD,uEAA6D;AA8B7D;;;;;GAKG;AACU,QAAA,kBAAkB,GAAgB;IAC7C,EAAE,EAAE,aAAa;IACjB,QAAQ,EAAE,EAAE;IACZ,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;CACb,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAA,qBAAa,EAA0B;IACvE,MAAM,EAAE,0BAAkB;IAC1B,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,gBAAgB,EAAE,GAAG,EAAE;QACrB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IACD,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,UAAU,EAAE,EAAE;IACd,aAAa,EAAE,GAAG,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,iBAAiB,EAAE,GAAG,EAAE;QACtB,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,eAAe,EAAE,6CAAe,CAAC,IAAI;IACrC,uBAAuB,EAAE,EAAE;IAC3B,MAAM,EAAE,IAAI;CACb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AM,cAAc,GAAG,GAAG,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,0BAAkB,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AANW,QAAA,cAAc,kBAMzB","sourcesContent":["\"use client\";\nimport TamboAI, { advanceStream } from \"@tambo-ai/typescript-sdk\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport {\n GenerationStage,\n isIdleStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport { TamboThread } from \"../model/tambo-thread\";\nimport { renderComponentIntoMessage } from \"../util/generate-component\";\nimport { getAvailableComponents, getClientContext } from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\nimport { useTamboClient } from \"./tambo-client-provider\";\nimport { useTamboRegistry } from \"./tambo-registry-provider\";\n\nexport interface TamboThreadContextProps {\n thread: TamboThread;\n switchCurrentThread: (threadId: string) => void;\n addThreadMessage: (\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<TamboAI.Beta.Threads.ThreadMessage[]>;\n updateThreadMessage: (\n id: string,\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<void>;\n setLastThreadStatus: (status: GenerationStage) => void;\n inputValue: string;\n setInputValue: (value: string) => void;\n sendThreadMessage: (\n message: string,\n options?: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n },\n ) => Promise<TamboThreadMessage>;\n generationStage: GenerationStage;\n generationStatusMessage: string;\n isIdle: boolean;\n}\n\n/** This is a stub entry for when the thread is not yet created, the first time\n * the user sends a message\n *\n * Note that the consumer needs to be careful never to send `PLACEHOLDER_THREAD.id` to the server,\n * as this doesn't really exist on the server side.\n */\nexport const PLACEHOLDER_THREAD: TamboThread = {\n id: \"placeholder\",\n messages: [],\n createdAt: \"\",\n projectId: \"\",\n updatedAt: \"\",\n metadata: {},\n};\n\nexport const TamboThreadContext = createContext<TamboThreadContextProps>({\n thread: PLACEHOLDER_THREAD,\n switchCurrentThread: () => {\n throw new Error(\"switchCurrentThread not implemented\");\n },\n addThreadMessage: () => {\n throw new Error(\"updateThreadMessageHistory not implemented\");\n },\n setLastThreadStatus: () => {\n throw new Error(\"setLastThreadStatus not implemented\");\n },\n inputValue: \"\",\n setInputValue: () => {\n throw new Error(\"setInputValue not implemented\");\n },\n updateThreadMessage: () => {\n throw new Error(\"updateThreadMessage not implemented\");\n },\n sendThreadMessage: () => {\n throw new Error(\"advance not implemented\");\n },\n generationStage: GenerationStage.IDLE,\n generationStatusMessage: \"\",\n isIdle: true,\n});\n\nexport const TamboThreadProvider: React.FC<PropsWithChildren> = ({\n children,\n}) => {\n const [threadMap, setThreadMap] = useState<Record<string, TamboThread>>({\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n });\n const client = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n const [inputValue, setInputValue] = useState(\"\");\n\n const [currentThreadId, setCurrentThreadId] = useState<string>(\n PLACEHOLDER_THREAD.id,\n );\n const currentThread: TamboThread | undefined = threadMap[currentThreadId];\n\n // Use existing messages from the current thread to avoid re-generating any components\n const currentMessageCache = useMemo(() => {\n const messageCache = new Map<string, TamboThreadMessage>();\n if (currentThread) {\n for (const message of currentThread.messages) {\n messageCache.set(message.id, message);\n }\n }\n return messageCache;\n }, [currentThread]);\n\n const fetchThread = useCallback(\n async (threadId: string) => {\n const thread = await client.beta.threads.retrieve(threadId);\n const threadWithRenderedComponents = {\n ...thread,\n messages: thread.messages.map((message) => {\n if (currentMessageCache.has(message.id)) {\n const renderedMessage = currentMessageCache.get(message.id);\n return {\n ...renderedMessage,\n ...message,\n };\n }\n if (message.component?.componentName) {\n const messageWithComponent = renderComponentIntoMessage(\n message,\n componentList,\n );\n return messageWithComponent;\n }\n return message;\n }),\n };\n\n setThreadMap((prevMap) => ({\n ...prevMap,\n [threadId]: threadWithRenderedComponents,\n }));\n },\n [client.beta.threads, componentList, currentMessageCache],\n );\n\n useEffect(() => {\n if (\n currentThreadId &&\n currentThreadId !== PLACEHOLDER_THREAD.id &&\n !threadMap[currentThreadId]\n ) {\n fetchThread(currentThreadId);\n }\n }, [currentThreadId, fetchThread, threadMap]);\n\n const addThreadMessage = useCallback(\n async (\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n if (!currentThread) {\n console.warn(\"Cannot add messages if we do not have a current thread\");\n return [];\n }\n const chatMessage: TamboThreadMessage & {\n additionalContext?: string;\n } = {\n ...message,\n additionalContext:\n message.role === \"user\" ? getClientContext() : undefined,\n createdAt,\n };\n const threadId = message.threadId;\n // optimistically update the thread in the local state\n setThreadMap((prevMap) => {\n if (!threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[threadId]?.messages || [];\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: [...prevMessages, chatMessage],\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(currentThreadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n const updatedMessageHistory = [...currentThread.messages, chatMessage];\n\n return updatedMessageHistory;\n },\n [client.beta.threads.messages, currentThread, currentThreadId],\n );\n\n const updateThreadMessage = useCallback(\n async (\n id: string,\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n const chatMessage: TamboThreadMessage = {\n ...message,\n createdAt,\n };\n\n setThreadMap((prevMap) => {\n if (!message.threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[message.threadId]?.messages || [];\n const updatedMessages = prevMessages.map((msg) => {\n if (msg.id === id) {\n return chatMessage;\n }\n return msg;\n });\n return {\n ...prevMap,\n [message.threadId]: {\n ...prevMap[message.threadId],\n messages: updatedMessages,\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(currentThreadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n },\n [client.beta.threads.messages, currentThreadId],\n );\n\n const deleteThreadMessage = useCallback(\n (messageId: string) => {\n if (!currentThread) return;\n\n setThreadMap((prevMap) => ({\n ...prevMap,\n [currentThread.id]: {\n ...prevMap[currentThread.id],\n messages: prevMap[currentThread.id].messages.filter(\n (msg) => msg.id !== messageId,\n ),\n },\n }));\n },\n [currentThread],\n );\n\n const switchCurrentThread = useCallback(\n async (threadId: string, fetch = true) => {\n if (threadId === PLACEHOLDER_THREAD.id) {\n console.warn(\"Switching to placeholder thread, may be a bug\");\n return;\n }\n\n setCurrentThreadId(threadId);\n if (!threadMap[threadId]) {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n });\n }\n if (fetch) {\n await fetchThread(threadId);\n }\n },\n [fetchThread, threadMap],\n );\n\n const setLastThreadStatus = (status: GenerationStage) => {\n setThreadMap((prevMap) => {\n if (!currentThreadId) {\n return prevMap;\n }\n const headMessages = prevMap[currentThreadId].messages.slice(0, -1);\n const lastMessage =\n prevMap[currentThreadId].messages[\n prevMap[currentThreadId].messages.length - 1\n ];\n const updatedLastMessage = {\n ...lastMessage,\n status,\n };\n return {\n ...prevMap,\n [currentThreadId]: {\n ...prevMap[currentThreadId],\n messages: [...headMessages, updatedLastMessage],\n },\n };\n });\n };\n\n const updateThreadStatus = useCallback(\n (stage: GenerationStage, statusMessage?: string) => {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [currentThreadId]: {\n ...prevMap[currentThreadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\n });\n },\n [currentThreadId],\n );\n\n const handleAdvanceStream = useCallback(\n async (\n stream: AsyncIterable<TamboAI.Beta.Threads.ThreadAdvanceResponse>,\n params: TamboAI.Beta.Threads.ThreadAdvanceParams,\n messageIdToRemove?: string,\n ): Promise<TamboThreadMessage> => {\n let finalMessage: TamboThreadMessage | undefined;\n let hasSetThreadId = false;\n let isFirstChunk = true;\n updateThreadStatus(GenerationStage.STREAMING_RESPONSE);\n\n for await (const chunk of stream) {\n if (isFirstChunk && messageIdToRemove) {\n deleteThreadMessage(messageIdToRemove);\n }\n isFirstChunk = false;\n\n if (chunk.responseMessageDto.toolCallRequest) {\n updateThreadStatus(GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n chunk.responseMessageDto,\n toolRegistry,\n );\n const toolCallResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n content: [{ type: \"text\", text: toolCallResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: chunk.responseMessageDto.component,\n tool_call_id: chunk.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(GenerationStage.STREAMING_RESPONSE);\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n // Pass the current message's ID to be removed when the new stream starts, since we now know it is a tool call request message\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n finalMessage?.id,\n );\n } else {\n if (\n !hasSetThreadId &&\n chunk.responseMessageDto.threadId &&\n chunk.responseMessageDto.threadId !== currentThread?.id\n ) {\n hasSetThreadId = true;\n switchCurrentThread(chunk.responseMessageDto.threadId, false);\n }\n\n if (!finalMessage) {\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n addThreadMessage(finalMessage, false);\n } else {\n const previousId = finalMessage.id;\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n updateThreadMessage(previousId, finalMessage, false);\n }\n }\n }\n\n updateThreadStatus(GenerationStage.COMPLETE);\n if (finalMessage) {\n await fetchThread(finalMessage.threadId);\n }\n return (\n finalMessage ?? {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream` }],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n componentState: {},\n }\n );\n },\n [\n addThreadMessage,\n client,\n componentList,\n currentThread?.id,\n deleteThreadMessage,\n fetchThread,\n switchCurrentThread,\n toolRegistry,\n updateThreadMessage,\n updateThreadStatus,\n ],\n );\n\n const sendThreadMessage = useCallback(\n async (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n } = {},\n ): Promise<TamboThreadMessage> => {\n const { threadId, streamResponse } = options;\n const currentThreadId = threadId ?? currentThread?.id;\n\n if (currentThreadId !== PLACEHOLDER_THREAD.id) {\n await switchCurrentThread(currentThreadId);\n }\n\n updateThreadStatus(GenerationStage.CHOOSING_COMPONENT);\n\n addThreadMessage(\n {\n content: [{ type: \"text\", text: message }],\n renderedComponent: null,\n role: \"user\",\n threadId: currentThread.id,\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n componentState: {},\n },\n false,\n );\n\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n const params: TamboAI.Beta.Threads.ThreadAdvanceParams = {\n messageToAppend: {\n content: [{ type: \"text\", text: message }],\n role: \"user\",\n },\n contextKey: options.contextKey,\n availableComponents: availableComponents,\n };\n\n if (streamResponse) {\n const advanceStreamResponse = await advanceStream(\n client,\n params,\n currentThreadId === PLACEHOLDER_THREAD.id\n ? undefined\n : currentThreadId,\n );\n return await handleAdvanceStream(advanceStreamResponse, params);\n }\n let advanceResponse = await (currentThreadId === PLACEHOLDER_THREAD.id\n ? client.beta.threads.advance(params)\n : client.beta.threads.advanceById(currentThreadId, params));\n\n //handle tool calls\n while (advanceResponse.responseMessageDto.toolCallRequest) {\n updateThreadStatus(GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n advanceResponse.responseMessageDto,\n toolRegistry,\n );\n const toolResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n ...params.messageToAppend,\n content: [{ type: \"text\", text: toolResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: advanceResponse.responseMessageDto.component,\n tool_call_id: advanceResponse.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(GenerationStage.HYDRATING_COMPONENT);\n advanceResponse = await client.beta.threads.advanceById(\n advanceResponse.responseMessageDto.threadId,\n toolCallResponseParams,\n );\n }\n\n const finalMessage = advanceResponse.responseMessageDto.component\n ?.componentName\n ? renderComponentIntoMessage(\n advanceResponse.responseMessageDto,\n componentList,\n )\n : advanceResponse.responseMessageDto;\n await switchCurrentThread(advanceResponse.responseMessageDto.threadId);\n updateThreadStatus(GenerationStage.COMPLETE);\n return finalMessage;\n },\n [\n componentList,\n toolRegistry,\n componentToolAssociations,\n currentThread,\n switchCurrentThread,\n addThreadMessage,\n client,\n updateThreadStatus,\n handleAdvanceStream,\n ],\n );\n\n return (\n <TamboThreadContext.Provider\n value={{\n thread: currentThread,\n switchCurrentThread,\n addThreadMessage,\n updateThreadMessage,\n setLastThreadStatus,\n inputValue,\n setInputValue,\n sendThreadMessage,\n generationStage: (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n generationStatusMessage: currentThread?.statusMessage ?? \"\",\n isIdle: isIdleStage(\n (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n ),\n }}\n >\n {children}\n </TamboThreadContext.Provider>\n );\n};\n\nexport const useTamboThread = () => {\n const context = useContext(TamboThreadContext);\n if (context === undefined) {\n throw new Error(\"useTamboThread must be used within a TamboThreadProvider\");\n }\n return context;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"tambo-thread-provider.js","sourceRoot":"","sources":["../../src/providers/tambo-thread-provider.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACb,6DAAkE;AAClE,+CAQe;AACf,sFAI8C;AAE9C,mEAAwE;AACxE,+CAA4E;AAC5E,qDAAqD;AACrD,mEAAyD;AACzD,uEAA6D;AA8B7D;;;;;GAKG;AACU,QAAA,kBAAkB,GAAgB;IAC7C,EAAE,EAAE,aAAa;IACjB,QAAQ,EAAE,EAAE;IACZ,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;CACb,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAA,qBAAa,EAA0B;IACvE,MAAM,EAAE,0BAAkB;IAC1B,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,gBAAgB,EAAE,GAAG,EAAE;QACrB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IACD,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,UAAU,EAAE,EAAE;IACd,aAAa,EAAE,GAAG,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD,mBAAmB,EAAE,GAAG,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,iBAAiB,EAAE,GAAG,EAAE;QACtB,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,eAAe,EAAE,6CAAe,CAAC,IAAI;I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,CAAC,CAAC;AA1eW,QAAA,mBAAmB,uBA0e9B;AAEK,MAAM,cAAc,GAAG,GAAG,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,0BAAkB,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AANW,QAAA,cAAc,kBAMzB","sourcesContent":["\"use client\";\nimport TamboAI, { advanceStream } from \"@tambo-ai/typescript-sdk\";\nimport React, {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport {\n GenerationStage,\n isIdleStage,\n TamboThreadMessage,\n} from \"../model/generate-component-response\";\nimport { TamboThread } from \"../model/tambo-thread\";\nimport { renderComponentIntoMessage } from \"../util/generate-component\";\nimport { getAvailableComponents, getClientContext } from \"../util/registry\";\nimport { handleToolCall } from \"../util/tool-caller\";\nimport { useTamboClient } from \"./tambo-client-provider\";\nimport { useTamboRegistry } from \"./tambo-registry-provider\";\n\nexport interface TamboThreadContextProps {\n thread: TamboThread;\n switchCurrentThread: (threadId: string, fetch?: boolean) => void;\n addThreadMessage: (\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<TamboAI.Beta.Threads.ThreadMessage[]>;\n updateThreadMessage: (\n id: string,\n message: TamboThreadMessage,\n sendToServer: boolean,\n ) => Promise<void>;\n setLastThreadStatus: (status: GenerationStage) => void;\n inputValue: string;\n setInputValue: (value: string) => void;\n sendThreadMessage: (\n message: string,\n options?: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n },\n ) => Promise<TamboThreadMessage>;\n generationStage: GenerationStage;\n generationStatusMessage: string;\n isIdle: boolean;\n}\n\n/** This is a stub entry for when the thread is not yet created, the first time\n * the user sends a message\n *\n * Note that the consumer needs to be careful never to send `PLACEHOLDER_THREAD.id` to the server,\n * as this doesn't really exist on the server side.\n */\nexport const PLACEHOLDER_THREAD: TamboThread = {\n id: \"placeholder\",\n messages: [],\n createdAt: \"\",\n projectId: \"\",\n updatedAt: \"\",\n metadata: {},\n};\n\nexport const TamboThreadContext = createContext<TamboThreadContextProps>({\n thread: PLACEHOLDER_THREAD,\n switchCurrentThread: () => {\n throw new Error(\"switchCurrentThread not implemented\");\n },\n addThreadMessage: () => {\n throw new Error(\"updateThreadMessageHistory not implemented\");\n },\n setLastThreadStatus: () => {\n throw new Error(\"setLastThreadStatus not implemented\");\n },\n inputValue: \"\",\n setInputValue: () => {\n throw new Error(\"setInputValue not implemented\");\n },\n updateThreadMessage: () => {\n throw new Error(\"updateThreadMessage not implemented\");\n },\n sendThreadMessage: () => {\n throw new Error(\"advance not implemented\");\n },\n generationStage: GenerationStage.IDLE,\n generationStatusMessage: \"\",\n isIdle: true,\n});\n\nexport const TamboThreadProvider: React.FC<PropsWithChildren> = ({\n children,\n}) => {\n const [threadMap, setThreadMap] = useState<Record<string, TamboThread>>({\n [PLACEHOLDER_THREAD.id]: PLACEHOLDER_THREAD,\n });\n const client = useTamboClient();\n const { componentList, toolRegistry, componentToolAssociations } =\n useTamboRegistry();\n const [inputValue, setInputValue] = useState(\"\");\n\n const [currentThreadId, setCurrentThreadId] = useState<string>(\n PLACEHOLDER_THREAD.id,\n );\n const currentThread: TamboThread | undefined = threadMap[currentThreadId];\n\n // Use existing messages from the current thread to avoid re-generating any components\n const currentMessageCache = useMemo(() => {\n const messageCache = new Map<string, TamboThreadMessage>();\n if (currentThread) {\n for (const message of currentThread.messages) {\n messageCache.set(message.id, message);\n }\n }\n return messageCache;\n }, [currentThread]);\n\n const fetchThread = useCallback(\n async (threadId: string) => {\n const thread = await client.beta.threads.retrieve(threadId);\n const threadWithRenderedComponents = {\n ...thread,\n messages: thread.messages.map((message) => {\n if (currentMessageCache.has(message.id)) {\n const renderedMessage = currentMessageCache.get(message.id);\n return {\n ...renderedMessage,\n ...message,\n };\n }\n if (message.component?.componentName) {\n const messageWithComponent = renderComponentIntoMessage(\n message,\n componentList,\n );\n return messageWithComponent;\n }\n return message;\n }),\n };\n\n setThreadMap((prevMap) => ({\n ...prevMap,\n [threadId]: threadWithRenderedComponents,\n }));\n },\n [client.beta.threads, componentList, currentMessageCache],\n );\n\n useEffect(() => {\n if (\n currentThreadId &&\n currentThreadId !== PLACEHOLDER_THREAD.id &&\n !threadMap[currentThreadId]\n ) {\n fetchThread(currentThreadId);\n }\n }, [currentThreadId, fetchThread, threadMap]);\n\n const addThreadMessage = useCallback(\n async (\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n if (!currentThread) {\n console.warn(\"Cannot add messages if we do not have a current thread\");\n return [];\n }\n const chatMessage: TamboThreadMessage & {\n additionalContext?: string;\n } = {\n ...message,\n additionalContext:\n message.role === \"user\" ? getClientContext() : undefined,\n createdAt,\n };\n const threadId = message.threadId;\n // optimistically update the thread in the local state\n setThreadMap((prevMap) => {\n if (!threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[threadId]?.messages || [];\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[threadId],\n messages: [...prevMessages, chatMessage],\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(currentThreadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n const updatedMessageHistory = [...currentThread.messages, chatMessage];\n\n return updatedMessageHistory;\n },\n [client.beta.threads.messages, currentThread, currentThreadId],\n );\n\n const updateThreadMessage = useCallback(\n async (\n id: string,\n message: TamboThreadMessage,\n sendToServer = true,\n createdAt: string = new Date().toISOString(),\n ) => {\n const chatMessage: TamboThreadMessage = {\n ...message,\n createdAt,\n };\n\n setThreadMap((prevMap) => {\n if (!message.threadId) {\n return prevMap;\n }\n const prevMessages = prevMap[message.threadId]?.messages || [];\n const updatedMessages = prevMessages.map((msg) => {\n if (msg.id === id) {\n return chatMessage;\n }\n return msg;\n });\n return {\n ...prevMap,\n [message.threadId]: {\n ...prevMap[message.threadId],\n messages: updatedMessages,\n },\n };\n });\n if (sendToServer) {\n // TODO: if this fails, we need to revert the local state update\n await client.beta.threads.messages.create(currentThreadId, {\n content: message.content,\n role: message.role,\n // additionalContext: chatMessage.additionalContext,\n });\n }\n },\n [client.beta.threads.messages, currentThreadId],\n );\n\n const deleteThreadMessage = useCallback(\n (messageId: string) => {\n if (!currentThread) return;\n\n setThreadMap((prevMap) => ({\n ...prevMap,\n [currentThread.id]: {\n ...prevMap[currentThread.id],\n messages: prevMap[currentThread.id].messages.filter(\n (msg) => msg.id !== messageId,\n ),\n },\n }));\n },\n [currentThread],\n );\n\n const switchCurrentThread = useCallback(\n async (threadId: string, fetch = true) => {\n if (threadId === PLACEHOLDER_THREAD.id) {\n console.warn(\"Switching to placeholder thread, may be a bug\");\n return;\n }\n\n setCurrentThreadId(threadId);\n if (!threadMap[threadId]) {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [threadId]: {\n ...prevMap[PLACEHOLDER_THREAD.id],\n id: threadId,\n },\n };\n });\n }\n if (fetch) {\n await fetchThread(threadId);\n }\n },\n [fetchThread, threadMap],\n );\n\n const setLastThreadStatus = (status: GenerationStage) => {\n setThreadMap((prevMap) => {\n if (!currentThreadId) {\n return prevMap;\n }\n const headMessages = prevMap[currentThreadId].messages.slice(0, -1);\n const lastMessage =\n prevMap[currentThreadId].messages[\n prevMap[currentThreadId].messages.length - 1\n ];\n const updatedLastMessage = {\n ...lastMessage,\n status,\n };\n return {\n ...prevMap,\n [currentThreadId]: {\n ...prevMap[currentThreadId],\n messages: [...headMessages, updatedLastMessage],\n },\n };\n });\n };\n\n const updateThreadStatus = useCallback(\n (stage: GenerationStage, statusMessage?: string) => {\n setThreadMap((prevMap) => {\n return {\n ...prevMap,\n [currentThreadId]: {\n ...prevMap[currentThreadId],\n generationStage: stage,\n statusMessage: statusMessage,\n },\n };\n });\n },\n [currentThreadId],\n );\n\n const handleAdvanceStream = useCallback(\n async (\n stream: AsyncIterable<TamboAI.Beta.Threads.ThreadAdvanceResponse>,\n params: TamboAI.Beta.Threads.ThreadAdvanceParams,\n messageIdToRemove?: string,\n ): Promise<TamboThreadMessage> => {\n let finalMessage: TamboThreadMessage | undefined;\n let hasSetThreadId = false;\n let isFirstChunk = true;\n updateThreadStatus(GenerationStage.STREAMING_RESPONSE);\n\n for await (const chunk of stream) {\n if (isFirstChunk && messageIdToRemove) {\n deleteThreadMessage(messageIdToRemove);\n }\n isFirstChunk = false;\n\n if (chunk.responseMessageDto.toolCallRequest) {\n updateThreadStatus(GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n chunk.responseMessageDto,\n toolRegistry,\n );\n const toolCallResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n content: [{ type: \"text\", text: toolCallResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: chunk.responseMessageDto.component,\n tool_call_id: chunk.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(GenerationStage.STREAMING_RESPONSE);\n const toolCallResponseStream = await advanceStream(\n client,\n toolCallResponseParams,\n chunk.responseMessageDto.threadId,\n );\n\n // Pass the current message's ID to be removed when the new stream starts, since we now know it is a tool call request message\n return await handleAdvanceStream(\n toolCallResponseStream,\n toolCallResponseParams,\n finalMessage?.id,\n );\n } else {\n if (\n !hasSetThreadId &&\n chunk.responseMessageDto.threadId &&\n chunk.responseMessageDto.threadId !== currentThread?.id\n ) {\n hasSetThreadId = true;\n switchCurrentThread(chunk.responseMessageDto.threadId, false);\n }\n\n if (!finalMessage) {\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n addThreadMessage(finalMessage, false);\n } else {\n const previousId = finalMessage.id;\n finalMessage = chunk.responseMessageDto.component?.componentName\n ? renderComponentIntoMessage(\n chunk.responseMessageDto,\n componentList,\n )\n : chunk.responseMessageDto;\n updateThreadMessage(previousId, finalMessage, false);\n }\n }\n }\n\n updateThreadStatus(GenerationStage.COMPLETE);\n if (finalMessage) {\n await fetchThread(finalMessage.threadId);\n }\n return (\n finalMessage ?? {\n threadId: \"\",\n content: [{ type: \"text\", text: `Error processing stream` }],\n role: \"hydra\",\n createdAt: new Date().toISOString(),\n id: crypto.randomUUID(),\n componentState: {},\n }\n );\n },\n [\n addThreadMessage,\n client,\n componentList,\n currentThread?.id,\n deleteThreadMessage,\n fetchThread,\n switchCurrentThread,\n toolRegistry,\n updateThreadMessage,\n updateThreadStatus,\n ],\n );\n\n const sendThreadMessage = useCallback(\n async (\n message: string,\n options: {\n threadId?: string;\n streamResponse?: boolean;\n contextKey?: string;\n } = {},\n ): Promise<TamboThreadMessage> => {\n const { threadId, streamResponse } = options;\n const currentThreadId = threadId ?? currentThread?.id;\n\n if (currentThreadId !== PLACEHOLDER_THREAD.id) {\n await switchCurrentThread(currentThreadId);\n }\n\n updateThreadStatus(GenerationStage.CHOOSING_COMPONENT);\n\n addThreadMessage(\n {\n content: [{ type: \"text\", text: message }],\n renderedComponent: null,\n role: \"user\",\n threadId: currentThread.id,\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n componentState: {},\n },\n false,\n );\n\n const availableComponents = getAvailableComponents(\n componentList,\n toolRegistry,\n componentToolAssociations,\n );\n const params: TamboAI.Beta.Threads.ThreadAdvanceParams = {\n messageToAppend: {\n content: [{ type: \"text\", text: message }],\n role: \"user\",\n },\n contextKey: options.contextKey,\n availableComponents: availableComponents,\n };\n\n if (streamResponse) {\n const advanceStreamResponse = await advanceStream(\n client,\n params,\n currentThreadId === PLACEHOLDER_THREAD.id\n ? undefined\n : currentThreadId,\n );\n return await handleAdvanceStream(advanceStreamResponse, params);\n }\n let advanceResponse = await (currentThreadId === PLACEHOLDER_THREAD.id\n ? client.beta.threads.advance(params)\n : client.beta.threads.advanceById(currentThreadId, params));\n\n //handle tool calls\n while (advanceResponse.responseMessageDto.toolCallRequest) {\n updateThreadStatus(GenerationStage.FETCHING_CONTEXT);\n const toolCallResponse = await handleToolCall(\n advanceResponse.responseMessageDto,\n toolRegistry,\n );\n const toolResponseString =\n typeof toolCallResponse === \"string\"\n ? toolCallResponse\n : JSON.stringify(toolCallResponse);\n const toolCallResponseParams: TamboAI.Beta.Threads.ThreadAdvanceParams =\n {\n ...params,\n messageToAppend: {\n ...params.messageToAppend,\n content: [{ type: \"text\", text: toolResponseString }],\n role: \"tool\",\n actionType: \"tool_response\",\n component: advanceResponse.responseMessageDto.component,\n tool_call_id: advanceResponse.responseMessageDto.tool_call_id,\n },\n };\n updateThreadStatus(GenerationStage.HYDRATING_COMPONENT);\n advanceResponse = await client.beta.threads.advanceById(\n advanceResponse.responseMessageDto.threadId,\n toolCallResponseParams,\n );\n }\n\n const finalMessage = advanceResponse.responseMessageDto.component\n ?.componentName\n ? renderComponentIntoMessage(\n advanceResponse.responseMessageDto,\n componentList,\n )\n : advanceResponse.responseMessageDto;\n await switchCurrentThread(advanceResponse.responseMessageDto.threadId);\n updateThreadStatus(GenerationStage.COMPLETE);\n return finalMessage;\n },\n [\n componentList,\n toolRegistry,\n componentToolAssociations,\n currentThread,\n switchCurrentThread,\n addThreadMessage,\n client,\n updateThreadStatus,\n handleAdvanceStream,\n ],\n );\n\n return (\n <TamboThreadContext.Provider\n value={{\n thread: currentThread,\n switchCurrentThread,\n addThreadMessage,\n updateThreadMessage,\n setLastThreadStatus,\n inputValue,\n setInputValue,\n sendThreadMessage,\n generationStage: (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n generationStatusMessage: currentThread?.statusMessage ?? \"\",\n isIdle: isIdleStage(\n (currentThread?.generationStage ??\n GenerationStage.IDLE) as GenerationStage,\n ),\n }}\n >\n {children}\n </TamboThreadContext.Provider>\n );\n};\n\nexport const useTamboThread = () => {\n const context = useContext(TamboThreadContext);\n if (context === undefined) {\n throw new Error(\"useTamboThread must be used within a TamboThreadProvider\");\n }\n return context;\n};\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from "./react-query-hooks";
|
|
2
|
+
export { useTamboComponentState } from "./use-component-state";
|
|
3
|
+
export { useTamboCurrentMessage, useTamboMessageContext, } from "./use-current-message";
|
|
4
|
+
export { useTamboStreamingProps } from "./use-streaming-props";
|
|
5
|
+
export * from "./use-suggestions";
|
|
6
|
+
export { useTamboThreads } from "./use-tambo-threads";
|
|
7
|
+
export { useTamboThreadInput } from "./use-thread-input";
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AACA,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EACL,sBAAsB,EACtB,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Export all hooks from this directory
|
|
2
|
+
export * from "./react-query-hooks";
|
|
3
|
+
export { useTamboComponentState } from "./use-component-state";
|
|
4
|
+
export { useTamboCurrentMessage, useTamboMessageContext, } from "./use-current-message";
|
|
5
|
+
export { useTamboStreamingProps } from "./use-streaming-props";
|
|
6
|
+
export * from "./use-suggestions";
|
|
7
|
+
export { useTamboThreads } from "./use-tambo-threads";
|
|
8
|
+
export { useTamboThreadInput } from "./use-thread-input";
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EACL,sBAAsB,EACtB,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["// Export all hooks from this directory\nexport * from \"./react-query-hooks\";\nexport { useTamboComponentState } from \"./use-component-state\";\nexport {\n useTamboCurrentMessage,\n useTamboMessageContext,\n} from \"./use-current-message\";\nexport { useTamboStreamingProps } from \"./use-streaming-props\";\nexport * from \"./use-suggestions\";\nexport { useTamboThreads } from \"./use-tambo-threads\";\nexport { useTamboThreadInput } from \"./use-thread-input\";\n"]}
|
|
@@ -1,9 +1,44 @@
|
|
|
1
|
-
|
|
1
|
+
interface ComponentStateMeta {
|
|
2
|
+
isPending: boolean;
|
|
3
|
+
}
|
|
4
|
+
type StateUpdateResult<T> = [
|
|
5
|
+
currentState: T,
|
|
6
|
+
setState: (newState: T) => void,
|
|
7
|
+
meta: ComponentStateMeta
|
|
8
|
+
];
|
|
2
9
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
10
|
+
* A React hook that provides state management and passes user updates to Tambo.
|
|
11
|
+
* Benefits: Passes user changes to AI, and when threads are returned, state is preserved.
|
|
12
|
+
*
|
|
13
|
+
* @param keyName - The unique key to identify this state within the message's componentState object
|
|
14
|
+
* @param initialValue - Optional initial value for the state, used if no value exists in the message
|
|
15
|
+
* @param debounceTime - Optional debounce time in milliseconds (default: 300ms) to limit API calls
|
|
16
|
+
*
|
|
17
|
+
* @returns A tuple containing:
|
|
18
|
+
* - The current state value
|
|
19
|
+
* - A setter function to update the state (updates UI immediately, debounces server sync)
|
|
20
|
+
* - A metadata object with properties like isPending to track sync status
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* // Basic usage
|
|
24
|
+
* const [count, setCount, { isPending }] = useTamboComponentState("counter", 0);
|
|
25
|
+
*
|
|
26
|
+
* // Usage with object state
|
|
27
|
+
* const [formState, setFormState] = useTamboComponentState("myForm", {
|
|
28
|
+
* name: "",
|
|
29
|
+
* email: "",
|
|
30
|
+
* message: ""
|
|
31
|
+
* });
|
|
32
|
+
*
|
|
33
|
+
* // Handling form input
|
|
34
|
+
* const handleChange = (e) => {
|
|
35
|
+
* setFormState({
|
|
36
|
+
* ...formState,
|
|
37
|
+
* [e.target.name]: e.target.value
|
|
38
|
+
* });
|
|
39
|
+
* };
|
|
5
40
|
*/
|
|
6
|
-
export declare function useTamboComponentState<S = undefined>(keyName: string): StateUpdateResult<S | undefined>;
|
|
7
|
-
export declare function useTamboComponentState<S>(keyName: string, initialValue?:
|
|
41
|
+
export declare function useTamboComponentState<S = undefined>(keyName: string, initialValue?: S, debounceTime?: number): StateUpdateResult<S | undefined>;
|
|
42
|
+
export declare function useTamboComponentState<S>(keyName: string, initialValue: S, debounceTime?: number): StateUpdateResult<S>;
|
|
8
43
|
export {};
|
|
9
44
|
//# sourceMappingURL=use-component-state.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-component-state.d.ts","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-component-state.d.ts","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":"AASA,UAAU,kBAAkB;IAC1B,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,KAAK,iBAAiB,CAAC,CAAC,IAAI;IAC1B,YAAY,EAAE,CAAC;IACf,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,KAAK,IAAI;IAC/B,IAAI,EAAE,kBAAkB;CACzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,wBAAgB,sBAAsB,CAAC,CAAC,GAAG,SAAS,EAClD,OAAO,EAAE,MAAM,EACf,YAAY,CAAC,EAAE,CAAC,EAChB,YAAY,CAAC,EAAE,MAAM,GACpB,iBAAiB,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;AACpC,wBAAgB,sBAAsB,CAAC,CAAC,EACtC,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,CAAC,EACf,YAAY,CAAC,EAAE,MAAM,GACpB,iBAAiB,CAAC,CAAC,CAAC,CAAC"}
|
|
@@ -1,40 +1,134 @@
|
|
|
1
|
-
import { useCallback, useEffect,
|
|
1
|
+
import { useCallback, useEffect, useState } from "react";
|
|
2
|
+
import { useDebouncedCallback } from "use-debounce";
|
|
2
3
|
import { useTamboClient, useTamboThread } from "../providers";
|
|
3
4
|
import { useTamboCurrentMessage, useTamboMessageContext, } from "./use-current-message";
|
|
4
|
-
export function useTamboComponentState(keyName, initialValue) {
|
|
5
|
+
export function useTamboComponentState(keyName, initialValue, debounceTime = 300) {
|
|
5
6
|
const { threadId, messageId } = useTamboMessageContext();
|
|
6
7
|
const { updateThreadMessage } = useTamboThread();
|
|
7
8
|
const client = useTamboClient();
|
|
8
9
|
const message = useTamboCurrentMessage();
|
|
10
|
+
// Initial value management
|
|
9
11
|
const [cachedInitialValue] = useState(() => initialValue);
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
12
|
+
// UI state management
|
|
13
|
+
const [localState, setLocalState] = useState(cachedInitialValue);
|
|
14
|
+
// Synchronization state
|
|
15
|
+
const [isPending, setIsPending] = useState(false);
|
|
16
|
+
// Track the last user-initiated value instead of a simple boolean flag
|
|
17
|
+
const [lastUserValue, setLastUserValue] = useState(null);
|
|
18
|
+
const [haveInitialized, setHaveInitialized] = useState(false);
|
|
19
|
+
// Determine if we need to initialize state
|
|
20
|
+
const shouldInitialize = !haveInitialized &&
|
|
21
|
+
message &&
|
|
22
|
+
cachedInitialValue !== undefined &&
|
|
23
|
+
(!message.componentState || !(keyName in message.componentState));
|
|
24
|
+
// Helper function to check if two values are deeply equal
|
|
25
|
+
const isEqual = (a, b) => {
|
|
26
|
+
if (a === b)
|
|
27
|
+
return true;
|
|
28
|
+
// Handle primitive types
|
|
29
|
+
if (typeof a !== "object" ||
|
|
30
|
+
typeof b !== "object" ||
|
|
31
|
+
a === null ||
|
|
32
|
+
b === null)
|
|
33
|
+
return false;
|
|
34
|
+
// For objects and arrays, do a shallow comparison for simplicity
|
|
35
|
+
// This could be enhanced with a proper deep equality check if needed
|
|
36
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
37
|
+
if (a.length !== b.length)
|
|
38
|
+
return false;
|
|
39
|
+
return a.every((val, idx) => val === b[idx]);
|
|
40
|
+
}
|
|
41
|
+
const keysA = Object.keys(a);
|
|
42
|
+
const keysB = Object.keys(b);
|
|
43
|
+
if (keysA.length !== keysB.length)
|
|
44
|
+
return false;
|
|
45
|
+
return keysA.every((key) => a[key] === b[key]);
|
|
46
|
+
};
|
|
47
|
+
// Sync local state with message state on initial load and when message changes
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
if (message?.componentState && keyName in message.componentState) {
|
|
50
|
+
const messageState = message.componentState[keyName];
|
|
51
|
+
// If this is a user-initiated state that matches what we're getting from server,
|
|
52
|
+
// we can clear the lastUserValue flag since it's been synchronized
|
|
53
|
+
if (lastUserValue !== null && isEqual(messageState, lastUserValue)) {
|
|
54
|
+
setLastUserValue(null);
|
|
55
|
+
}
|
|
56
|
+
// Update local state with server state unless user has specifically changed this value
|
|
57
|
+
// This allows streaming updates to continue while protecting user edits
|
|
58
|
+
if (lastUserValue === null || !isEqual(localState, lastUserValue)) {
|
|
59
|
+
setLocalState(messageState);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Otherwise fall back to initial value if we have one
|
|
63
|
+
else if (cachedInitialValue !== undefined && !localState) {
|
|
64
|
+
setLocalState(cachedInitialValue);
|
|
65
|
+
}
|
|
66
|
+
}, [
|
|
67
|
+
keyName,
|
|
68
|
+
message?.componentState,
|
|
69
|
+
cachedInitialValue,
|
|
70
|
+
lastUserValue,
|
|
71
|
+
localState,
|
|
72
|
+
]);
|
|
73
|
+
// Create debounced save function for efficient server synchronization
|
|
74
|
+
const debouncedSave = useDebouncedCallback(async (newValue) => {
|
|
75
|
+
if (!message) {
|
|
76
|
+
console.warn(`Cannot update missing message ${messageId} for state key "${keyName}"`);
|
|
77
|
+
setLastUserValue(null);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
setIsPending(true);
|
|
81
|
+
try {
|
|
82
|
+
const messageUpdate = {
|
|
83
|
+
...message,
|
|
84
|
+
componentState: {
|
|
85
|
+
...message.componentState,
|
|
86
|
+
[keyName]: newValue,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
const componentStateUpdate = {
|
|
90
|
+
state: { [keyName]: newValue },
|
|
91
|
+
};
|
|
92
|
+
await Promise.all([
|
|
93
|
+
updateThreadMessage(messageId, messageUpdate, false),
|
|
94
|
+
client.beta.threads.messages.updateComponentState(threadId, messageId, componentStateUpdate),
|
|
95
|
+
]);
|
|
96
|
+
// Only clear the lastUserValue when we've successfully synced this exact value
|
|
97
|
+
if (isEqual(newValue, lastUserValue)) {
|
|
98
|
+
setLastUserValue(null);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
console.error(`Failed to save component state for key "${keyName}":`, err);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
setIsPending(false);
|
|
106
|
+
}
|
|
107
|
+
}, debounceTime);
|
|
108
|
+
// Initialize state on first render if needed
|
|
17
109
|
const initializeState = useCallback(async () => {
|
|
18
110
|
if (!message) {
|
|
19
|
-
console.warn(`Cannot initialize state for missing message ${messageId}`);
|
|
111
|
+
console.warn(`Cannot initialize state for missing message ${messageId} with key "${keyName}"`);
|
|
20
112
|
return;
|
|
21
113
|
}
|
|
22
114
|
try {
|
|
115
|
+
const messageUpdate = {
|
|
116
|
+
...message,
|
|
117
|
+
componentState: {
|
|
118
|
+
...message.componentState,
|
|
119
|
+
[keyName]: cachedInitialValue,
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
const componentStateUpdate = {
|
|
123
|
+
state: { [keyName]: cachedInitialValue },
|
|
124
|
+
};
|
|
23
125
|
await Promise.all([
|
|
24
|
-
updateThreadMessage(messageId,
|
|
25
|
-
|
|
26
|
-
componentState: {
|
|
27
|
-
...message.componentState,
|
|
28
|
-
[keyName]: cachedInitialValue,
|
|
29
|
-
},
|
|
30
|
-
}, false),
|
|
31
|
-
client.beta.threads.messages.updateComponentState(threadId, messageId, {
|
|
32
|
-
state: { [keyName]: cachedInitialValue },
|
|
33
|
-
}),
|
|
126
|
+
updateThreadMessage(messageId, messageUpdate, false),
|
|
127
|
+
client.beta.threads.messages.updateComponentState(threadId, messageId, componentStateUpdate),
|
|
34
128
|
]);
|
|
35
129
|
}
|
|
36
130
|
catch (err) {
|
|
37
|
-
console.warn(
|
|
131
|
+
console.warn(`Failed to initialize component state for key "${keyName}":`, err);
|
|
38
132
|
}
|
|
39
133
|
}, [
|
|
40
134
|
cachedInitialValue,
|
|
@@ -45,39 +139,36 @@ export function useTamboComponentState(keyName, initialValue) {
|
|
|
45
139
|
threadId,
|
|
46
140
|
updateThreadMessage,
|
|
47
141
|
]);
|
|
48
|
-
|
|
49
|
-
const shouldInitialize = !haveInitialized &&
|
|
50
|
-
message &&
|
|
51
|
-
cachedInitialValue !== undefined &&
|
|
52
|
-
(!message.componentState || !(keyName in message.componentState));
|
|
53
|
-
// send initial state
|
|
142
|
+
// Send initial state when component mounts
|
|
54
143
|
useEffect(() => {
|
|
55
144
|
if (shouldInitialize) {
|
|
56
145
|
initializeState();
|
|
57
146
|
setHaveInitialized(true);
|
|
58
147
|
}
|
|
59
148
|
}, [initializeState, shouldInitialize]);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
149
|
+
// setValue function for updating state
|
|
150
|
+
// Updates local state immediately and schedules debounced server sync
|
|
151
|
+
const setValue = useCallback((newValue) => {
|
|
152
|
+
// Track this as a user-initiated update
|
|
153
|
+
setLastUserValue(newValue);
|
|
154
|
+
setLocalState(newValue);
|
|
155
|
+
// Only trigger server updates if we have a message
|
|
156
|
+
if (message) {
|
|
157
|
+
debouncedSave(newValue);
|
|
64
158
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
updateThreadMessage,
|
|
80
|
-
]);
|
|
81
|
-
return [value, setValue];
|
|
159
|
+
else {
|
|
160
|
+
console.warn(`Cannot update server for missing message ${messageId} with key "${keyName}"`);
|
|
161
|
+
setLastUserValue(null);
|
|
162
|
+
}
|
|
163
|
+
}, [debouncedSave, message, messageId, keyName]);
|
|
164
|
+
// Ensure pending changes are flushed on unmount
|
|
165
|
+
useEffect(() => {
|
|
166
|
+
return () => {
|
|
167
|
+
debouncedSave.flush();
|
|
168
|
+
setLastUserValue(null);
|
|
169
|
+
};
|
|
170
|
+
}, [debouncedSave]);
|
|
171
|
+
// Return the local state for immediate UI rendering
|
|
172
|
+
return [localState, setValue, { isPending }];
|
|
82
173
|
}
|
|
83
174
|
//# sourceMappingURL=use-component-state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-component-state.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,S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AAG,OAAO,CAAC,cAAc;gBACzB,CAAC,OAAO,CAAC,EAAE,QAAQ;aACpB;SACF,EACD,KAAK,CACN,CAAC;QACF,MAAM,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CACrD,QAAQ,EACR,SAAS,EACT,EAAE,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,EAAE,CACnC,CAAC;IACJ,CAAC,EACD;QACE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ;QAC5B,OAAO;QACP,OAAO;QACP,SAAS;QACT,QAAQ;QACR,mBAAmB;KACpB,CACF,CAAC;IACF,OAAO,CAAC,KAAU,EAAE,QAAQ,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useTamboClient, useTamboThread } from \"../providers\";\nimport {\n useTamboCurrentMessage,\n useTamboMessageContext,\n} from \"./use-current-message\";\n\ntype StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];\n\n/**\n * Behaves similarly to useState, but the value is stored in the thread\n * message, and the state is keyed by the keyName\n */\nexport function useTamboComponentState<S = undefined>(\n keyName: string,\n): StateUpdateResult<S | undefined>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n): StateUpdateResult<S>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n): StateUpdateResult<S> {\n const { threadId, messageId } = useTamboMessageContext();\n const { updateThreadMessage } = useTamboThread();\n const client = useTamboClient();\n\n const message = useTamboCurrentMessage();\n const [cachedInitialValue] = useState(() => initialValue);\n\n const value = useMemo(() => {\n if (!message?.componentState) return cachedInitialValue;\n return keyName in message.componentState\n ? (message.componentState[keyName] as S)\n : cachedInitialValue;\n }, [cachedInitialValue, keyName, message?.componentState]);\n\n const initializeState = useCallback(async () => {\n if (!message) {\n console.warn(`Cannot initialize state for missing message ${messageId}`);\n return;\n }\n try {\n await Promise.all([\n updateThreadMessage(\n messageId,\n {\n ...message,\n componentState: {\n ...message.componentState,\n [keyName]: cachedInitialValue,\n },\n },\n false,\n ),\n client.beta.threads.messages.updateComponentState(threadId, messageId, {\n state: { [keyName]: cachedInitialValue },\n }),\n ]);\n } catch (err) {\n console.warn(\"Failed to initialize component state:\", err);\n }\n }, [\n cachedInitialValue,\n client.beta.threads.messages,\n keyName,\n message,\n messageId,\n threadId,\n updateThreadMessage,\n ]);\n const [haveInitialized, setHaveInitialized] = useState(false);\n const shouldInitialize =\n !haveInitialized &&\n message &&\n cachedInitialValue !== undefined &&\n (!message.componentState || !(keyName in message.componentState));\n\n // send initial state\n useEffect(() => {\n if (shouldInitialize) {\n initializeState();\n setHaveInitialized(true);\n }\n }, [initializeState, shouldInitialize]);\n\n const setValue = useCallback(\n async (newValue: S) => {\n if (!message) {\n console.warn(`Cannot update missing message ${messageId}`);\n return;\n }\n await updateThreadMessage(\n messageId,\n {\n ...message,\n componentState: {\n ...message.componentState,\n [keyName]: newValue,\n },\n },\n false,\n );\n await client.beta.threads.messages.updateComponentState(\n threadId,\n messageId,\n { state: { [keyName]: newValue } },\n );\n },\n [\n client.beta.threads.messages,\n keyName,\n message,\n messageId,\n threadId,\n updateThreadMessage,\n ],\n );\n return [value as S, setValue];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-component-state.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EACL,sBAAsB,EACtB,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAwD/B,MAAM,UAAU,sBAAsB,CACpC,OAAe,EACf,YAAgB,EAChB,YAAY,GAAG,GAAG;IAElB,MAAM,EAAE,QAAQ,EAA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,CAAC;IAExC,uCAAuC;IACvC,sEAAsE;IACtE,MAAM,QAAQ,GAAG,WAAW,CAC1B,CAAC,QAAW,EAAE,EAAE;QACd,wCAAwC;QACxC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;QAC3B,aAAa,CAAC,QAAQ,CAAC,CAAC;QAExB,mDAAmD;QACnD,IAAI,OAAO,EAAE,CAAC;YACZ,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC1B,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,IAAI,CACV,4CAA4C,SAAS,cAAc,OAAO,GAAG,CAC9E,CAAC;YACF,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;IACH,CAAC,EACD,CAAC,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAC7C,CAAC;IAEF,gDAAgD;IAChD,SAAS,CAAC,GAAG,EAAE;QACb,OAAO,GAAG,EAAE;YACV,aAAa,CAAC,KAAK,EAAE,CAAC;YACtB,gBAAgB,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC;IAEpB,oDAAoD;IACpD,OAAO,CAAC,UAAe,EAAE,QAAQ,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import { useCallback, useEffect, useState } from \"react\";\nimport { useDebouncedCallback } from \"use-debounce\";\nimport { useTamboClient, useTamboThread } from \"../providers\";\nimport {\n useTamboCurrentMessage,\n useTamboMessageContext,\n} from \"./use-current-message\";\n\n// Define metadata interface for better extensibility\ninterface ComponentStateMeta {\n isPending: boolean;\n}\n\ntype StateUpdateResult<T> = [\n currentState: T,\n setState: (newState: T) => void,\n meta: ComponentStateMeta,\n];\n\n/**\n * A React hook that provides state management and passes user updates to Tambo.\n * Benefits: Passes user changes to AI, and when threads are returned, state is preserved.\n *\n * @param keyName - The unique key to identify this state within the message's componentState object\n * @param initialValue - Optional initial value for the state, used if no value exists in the message\n * @param debounceTime - Optional debounce time in milliseconds (default: 300ms) to limit API calls\n *\n * @returns A tuple containing:\n * - The current state value\n * - A setter function to update the state (updates UI immediately, debounces server sync)\n * - A metadata object with properties like isPending to track sync status\n *\n * @example\n * // Basic usage\n * const [count, setCount, { isPending }] = useTamboComponentState(\"counter\", 0);\n *\n * // Usage with object state\n * const [formState, setFormState] = useTamboComponentState(\"myForm\", {\n * name: \"\",\n * email: \"\",\n * message: \"\"\n * });\n *\n * // Handling form input\n * const handleChange = (e) => {\n * setFormState({\n * ...formState,\n * [e.target.name]: e.target.value\n * });\n * };\n */\n\nexport function useTamboComponentState<S = undefined>(\n keyName: string,\n initialValue?: S,\n debounceTime?: number,\n): StateUpdateResult<S | undefined>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue: S,\n debounceTime?: number,\n): StateUpdateResult<S>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n debounceTime = 300,\n): StateUpdateResult<S> {\n const { threadId, messageId } = useTamboMessageContext();\n const { updateThreadMessage } = useTamboThread();\n const client = useTamboClient();\n const message = useTamboCurrentMessage();\n\n // Initial value management\n const [cachedInitialValue] = useState(() => initialValue);\n // UI state management\n const [localState, setLocalState] = useState<S | undefined>(\n cachedInitialValue,\n );\n // Synchronization state\n const [isPending, setIsPending] = useState(false);\n // Track the last user-initiated value instead of a simple boolean flag\n const [lastUserValue, setLastUserValue] = useState<S | null>(null);\n const [haveInitialized, setHaveInitialized] = useState(false);\n\n // Determine if we need to initialize state\n const shouldInitialize =\n !haveInitialized &&\n message &&\n cachedInitialValue !== undefined &&\n (!message.componentState || !(keyName in message.componentState));\n\n // Helper function to check if two values are deeply equal\n const isEqual = (a: any, b: any): boolean => {\n if (a === b) return true;\n\n // Handle primitive types\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n )\n return false;\n\n // For objects and arrays, do a shallow comparison for simplicity\n // This could be enhanced with a proper deep equality check if needed\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((val, idx) => val === b[idx]);\n }\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every((key) => a[key] === b[key]);\n };\n\n // Sync local state with message state on initial load and when message changes\n useEffect(() => {\n if (message?.componentState && keyName in message.componentState) {\n const messageState = message.componentState[keyName] as S;\n\n // If this is a user-initiated state that matches what we're getting from server,\n // we can clear the lastUserValue flag since it's been synchronized\n if (lastUserValue !== null && isEqual(messageState, lastUserValue)) {\n setLastUserValue(null);\n }\n\n // Update local state with server state unless user has specifically changed this value\n // This allows streaming updates to continue while protecting user edits\n if (lastUserValue === null || !isEqual(localState, lastUserValue)) {\n setLocalState(messageState);\n }\n }\n // Otherwise fall back to initial value if we have one\n else if (cachedInitialValue !== undefined && !localState) {\n setLocalState(cachedInitialValue);\n }\n }, [\n keyName,\n message?.componentState,\n cachedInitialValue,\n lastUserValue,\n localState,\n ]);\n\n // Create debounced save function for efficient server synchronization\n const debouncedSave = useDebouncedCallback(async (newValue: S) => {\n if (!message) {\n console.warn(\n `Cannot update missing message ${messageId} for state key \"${keyName}\"`,\n );\n setLastUserValue(null);\n return;\n }\n\n setIsPending(true);\n try {\n const messageUpdate = {\n ...message,\n componentState: {\n ...message.componentState,\n [keyName]: newValue,\n },\n };\n\n const componentStateUpdate = {\n state: { [keyName]: newValue },\n };\n\n await Promise.all([\n updateThreadMessage(messageId, messageUpdate, false),\n client.beta.threads.messages.updateComponentState(\n threadId,\n messageId,\n componentStateUpdate,\n ),\n ]);\n\n // Only clear the lastUserValue when we've successfully synced this exact value\n if (isEqual(newValue, lastUserValue)) {\n setLastUserValue(null);\n }\n } catch (err) {\n console.error(\n `Failed to save component state for key \"${keyName}\":`,\n err,\n );\n } finally {\n setIsPending(false);\n }\n }, debounceTime);\n\n // Initialize state on first render if needed\n const initializeState = useCallback(async () => {\n if (!message) {\n console.warn(\n `Cannot initialize state for missing message ${messageId} with key \"${keyName}\"`,\n );\n return;\n }\n\n try {\n const messageUpdate = {\n ...message,\n componentState: {\n ...message.componentState,\n [keyName]: cachedInitialValue,\n },\n };\n\n const componentStateUpdate = {\n state: { [keyName]: cachedInitialValue },\n };\n\n await Promise.all([\n updateThreadMessage(messageId, messageUpdate, false),\n client.beta.threads.messages.updateComponentState(\n threadId,\n messageId,\n componentStateUpdate,\n ),\n ]);\n } catch (err) {\n console.warn(\n `Failed to initialize component state for key \"${keyName}\":`,\n err,\n );\n }\n }, [\n cachedInitialValue,\n client.beta.threads.messages,\n keyName,\n message,\n messageId,\n threadId,\n updateThreadMessage,\n ]);\n\n // Send initial state when component mounts\n useEffect(() => {\n if (shouldInitialize) {\n initializeState();\n setHaveInitialized(true);\n }\n }, [initializeState, shouldInitialize]);\n\n // setValue function for updating state\n // Updates local state immediately and schedules debounced server sync\n const setValue = useCallback(\n (newValue: S) => {\n // Track this as a user-initiated update\n setLastUserValue(newValue);\n setLocalState(newValue);\n\n // Only trigger server updates if we have a message\n if (message) {\n debouncedSave(newValue);\n } else {\n console.warn(\n `Cannot update server for missing message ${messageId} with key \"${keyName}\"`,\n );\n setLastUserValue(null);\n }\n },\n [debouncedSave, message, messageId, keyName],\n );\n\n // Ensure pending changes are flushed on unmount\n useEffect(() => {\n return () => {\n debouncedSave.flush();\n setLastUserValue(null);\n };\n }, [debouncedSave]);\n\n // Return the local state for immediate UI rendering\n return [localState as S, setValue, { isPending }];\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A helper hook that automatically updates Tambo component state when specified props change.
|
|
3
|
+
*
|
|
4
|
+
* This hook streamlines the common pattern of updating component state when receiving new
|
|
5
|
+
* streamed values from Tambo, eliminating the need to write repetitive useEffect code.
|
|
6
|
+
*
|
|
7
|
+
* @param currentState - The current state object from useTamboComponentState
|
|
8
|
+
* @param setState - The setState function from useTamboComponentState
|
|
9
|
+
* @param streamingProps - An object mapping state keys to prop values that should update the state
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* // Instead of writing a complex useEffect:
|
|
14
|
+
* const [emailState, setEmailState] = useTamboComponentState("email", initialState);
|
|
15
|
+
*
|
|
16
|
+
* // Simply use:
|
|
17
|
+
* useTamboStreamingProps(emailState, setEmailState, {
|
|
18
|
+
* subject: aiGeneratedSubject,
|
|
19
|
+
* body: aiGeneratedBody,
|
|
20
|
+
* usersEmail: usersEmail
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare function useTamboStreamingProps<T extends Record<string, any>>(currentState: T | undefined, setState: (state: T) => void, streamingProps: Partial<T>): void;
|
|
25
|
+
//# sourceMappingURL=use-streaming-props.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-streaming-props.d.ts","sourceRoot":"","sources":["../../src/hooks/use-streaming-props.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAClE,YAAY,EAAE,CAAC,GAAG,SAAS,EAC3B,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,EAC5B,cAAc,EAAE,OAAO,CAAC,CAAC,CAAC,QAuB3B"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { useEffect } from "react";
|
|
2
|
+
/**
|
|
3
|
+
* A helper hook that automatically updates Tambo component state when specified props change.
|
|
4
|
+
*
|
|
5
|
+
* This hook streamlines the common pattern of updating component state when receiving new
|
|
6
|
+
* streamed values from Tambo, eliminating the need to write repetitive useEffect code.
|
|
7
|
+
*
|
|
8
|
+
* @param currentState - The current state object from useTamboComponentState
|
|
9
|
+
* @param setState - The setState function from useTamboComponentState
|
|
10
|
+
* @param streamingProps - An object mapping state keys to prop values that should update the state
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* // Instead of writing a complex useEffect:
|
|
15
|
+
* const [emailState, setEmailState] = useTamboComponentState("email", initialState);
|
|
16
|
+
*
|
|
17
|
+
* // Simply use:
|
|
18
|
+
* useTamboStreamingProps(emailState, setEmailState, {
|
|
19
|
+
* subject: aiGeneratedSubject,
|
|
20
|
+
* body: aiGeneratedBody,
|
|
21
|
+
* usersEmail: usersEmail
|
|
22
|
+
* });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export function useTamboStreamingProps(currentState, setState, streamingProps) {
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
if (currentState) {
|
|
28
|
+
let shouldUpdate = false;
|
|
29
|
+
const updates = {};
|
|
30
|
+
Object.entries(streamingProps).forEach(([key, value]) => {
|
|
31
|
+
if (value !== undefined && value !== currentState[key]) {
|
|
32
|
+
shouldUpdate = true;
|
|
33
|
+
updates[key] = value;
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
if (shouldUpdate) {
|
|
37
|
+
setState({
|
|
38
|
+
...currentState,
|
|
39
|
+
...updates,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
44
|
+
}, [currentState, setState, ...Object.values(streamingProps)]);
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=use-streaming-props.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-streaming-props.js","sourceRoot":"","sources":["../../src/hooks/use-streaming-props.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,sBAAsB,CACpC,YAA2B,EAC3B,QAA4B,EAC5B,cAA0B;IAE1B,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,YAAY,EAAE,CAAC;YACjB,IAAI,YAAY,GAAG,KAAK,CAAC;YACzB,MAAM,OAAO,GAAe,EAAE,CAAC;YAE/B,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACtD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;oBACvD,YAAY,GAAG,IAAI,CAAC;oBACpB,OAAO,CAAC,GAAc,CAAC,GAAG,KAAmB,CAAC;gBAChD,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,IAAI,YAAY,EAAE,CAAC;gBACjB,QAAQ,CAAC;oBACP,GAAG,YAAY;oBACf,GAAG,OAAO;iBACX,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,uDAAuD;IACzD,CAAC,EAAE,CAAC,YAAY,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import { useEffect } from \"react\";\n\n/**\n * A helper hook that automatically updates Tambo component state when specified props change.\n *\n * This hook streamlines the common pattern of updating component state when receiving new\n * streamed values from Tambo, eliminating the need to write repetitive useEffect code.\n *\n * @param currentState - The current state object from useTamboComponentState\n * @param setState - The setState function from useTamboComponentState\n * @param streamingProps - An object mapping state keys to prop values that should update the state\n *\n * @example\n * ```tsx\n * // Instead of writing a complex useEffect:\n * const [emailState, setEmailState] = useTamboComponentState(\"email\", initialState);\n *\n * // Simply use:\n * useTamboStreamingProps(emailState, setEmailState, {\n * subject: aiGeneratedSubject,\n * body: aiGeneratedBody,\n * usersEmail: usersEmail\n * });\n * ```\n */\nexport function useTamboStreamingProps<T extends Record<string, any>>(\n currentState: T | undefined,\n setState: (state: T) => void,\n streamingProps: Partial<T>,\n) {\n useEffect(() => {\n if (currentState) {\n let shouldUpdate = false;\n const updates: Partial<T> = {};\n\n Object.entries(streamingProps).forEach(([key, value]) => {\n if (value !== undefined && value !== currentState[key]) {\n shouldUpdate = true;\n updates[key as keyof T] = value as T[keyof T];\n }\n });\n\n if (shouldUpdate) {\n setState({\n ...currentState,\n ...updates,\n });\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [currentState, setState, ...Object.values(streamingProps)]);\n}\n"]}
|
package/esm/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Exports for the library. Only publically available exports are re-exported here. Anything not exported here is not supported and may change or break at any time. */
|
|
2
2
|
export { useTamboComponentState } from "./hooks/use-component-state";
|
|
3
3
|
export { TamboMessageProvider, useTamboCurrentMessage, useTamboMessageContext, } from "./hooks/use-current-message";
|
|
4
|
+
export { useTamboStreamingProps } from "./hooks/use-streaming-props";
|
|
4
5
|
export * from "./hooks/use-suggestions";
|
|
5
6
|
export { useTamboThreadInput } from "./hooks/use-thread-input";
|
|
6
7
|
export * from "./providers";
|
package/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wKAAwK;AACxK,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,sBAAsB,GACvB,MAAM,6BAA6B,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAG/D,cAAc,aAAa,CAAC;AAG5B,YAAY,EACV,QAAQ,EACR,cAAc,EACd,YAAY,GACb,MAAM,0BAA0B,CAAC;AAClC,YAAY,EACV,UAAU,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,6DAA6D,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EACL,KAAK,4BAA4B,EACjC,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,SAAS,GACf,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,KAAK,kBAAkB,GACxB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,sBAAsB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wKAAwK;AACxK,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,sBAAsB,GACvB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAG/D,cAAc,aAAa,CAAC;AAG5B,YAAY,EACV,QAAQ,EACR,cAAc,EACd,YAAY,GACb,MAAM,0BAA0B,CAAC;AAClC,YAAY,EACV,UAAU,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,6DAA6D,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EACL,KAAK,4BAA4B,EACjC,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,SAAS,GACf,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,KAAK,kBAAkB,GACxB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,sBAAsB,CAAC"}
|
package/esm/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Exports for the library. Only publically available exports are re-exported here. Anything not exported here is not supported and may change or break at any time. */
|
|
2
2
|
export { useTamboComponentState } from "./hooks/use-component-state";
|
|
3
3
|
export { TamboMessageProvider, useTamboCurrentMessage, useTamboMessageContext, } from "./hooks/use-current-message";
|
|
4
|
+
export { useTamboStreamingProps } from "./hooks/use-streaming-props";
|
|
4
5
|
export * from "./hooks/use-suggestions";
|
|
5
6
|
export { useTamboThreadInput } from "./hooks/use-thread-input";
|
|
6
7
|
// Re-export provider components
|