@devicai/ui 0.12.1 → 0.14.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/cjs/api/types.js.map +1 -1
- package/dist/cjs/components/AICommandBar/useAICommandBar.js +1 -1
- package/dist/cjs/components/AICommandBar/useAICommandBar.js.map +1 -1
- package/dist/cjs/components/AIElementWrapper/AIElementWrapper.js +334 -0
- package/dist/cjs/components/AIElementWrapper/AIElementWrapper.js.map +1 -0
- package/dist/cjs/components/AIElementWrapper/activeWrapperRegistry.js +30 -0
- package/dist/cjs/components/AIElementWrapper/activeWrapperRegistry.js.map +1 -0
- package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js +161 -0
- package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js.map +1 -0
- package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js +1 -1
- package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
- package/dist/cjs/components/ChatDrawer/ChatDrawer.js +53 -5
- package/dist/cjs/components/ChatDrawer/ChatDrawer.js.map +1 -1
- package/dist/cjs/components/ChatDrawer/ChatInput.js +13 -2
- package/dist/cjs/components/ChatDrawer/ChatInput.js.map +1 -1
- package/dist/cjs/components/ChatDrawer/ChatMessages.js +34 -4
- package/dist/cjs/components/ChatDrawer/ChatMessages.js.map +1 -1
- package/dist/cjs/components/ChatDrawer/HandoffSubagentWidget.js +1 -1
- package/dist/cjs/hooks/useDevicChat.js +71 -6
- package/dist/cjs/hooks/useDevicChat.js.map +1 -1
- package/dist/cjs/hooks/useModelInterface.js +33 -19
- package/dist/cjs/hooks/useModelInterface.js.map +1 -1
- package/dist/cjs/index.js +4 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/provider/DevicProvider.js +53 -14
- package/dist/cjs/provider/DevicProvider.js.map +1 -1
- package/dist/cjs/styles.css +1 -1
- package/dist/esm/api/types.d.ts +45 -2
- package/dist/esm/api/types.js.map +1 -1
- package/dist/esm/components/AICommandBar/useAICommandBar.js +1 -1
- package/dist/esm/components/AICommandBar/useAICommandBar.js.map +1 -1
- package/dist/esm/components/AIElementWrapper/AIElementWrapper.d.ts +14 -0
- package/dist/esm/components/AIElementWrapper/AIElementWrapper.js +332 -0
- package/dist/esm/components/AIElementWrapper/AIElementWrapper.js.map +1 -0
- package/dist/esm/components/AIElementWrapper/AIElementWrapper.types.d.ts +185 -0
- package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.d.ts +10 -0
- package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.js +26 -0
- package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.js.map +1 -0
- package/dist/esm/components/AIElementWrapper/index.d.ts +3 -0
- package/dist/esm/components/AIElementWrapper/useAIElementWrapper.d.ts +26 -0
- package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js +159 -0
- package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js.map +1 -0
- package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js +1 -1
- package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
- package/dist/esm/components/ChatDrawer/ChatDrawer.js +53 -5
- package/dist/esm/components/ChatDrawer/ChatDrawer.js.map +1 -1
- package/dist/esm/components/ChatDrawer/ChatDrawer.types.d.ts +24 -0
- package/dist/esm/components/ChatDrawer/ChatInput.d.ts +1 -1
- package/dist/esm/components/ChatDrawer/ChatInput.js +14 -3
- package/dist/esm/components/ChatDrawer/ChatInput.js.map +1 -1
- package/dist/esm/components/ChatDrawer/ChatMessages.d.ts +1 -1
- package/dist/esm/components/ChatDrawer/ChatMessages.js +34 -4
- package/dist/esm/components/ChatDrawer/ChatMessages.js.map +1 -1
- package/dist/esm/components/ChatDrawer/HandoffSubagentWidget.js +1 -1
- package/dist/esm/hooks/index.d.ts +1 -1
- package/dist/esm/hooks/useDevicChat.d.ts +15 -0
- package/dist/esm/hooks/useDevicChat.js +71 -6
- package/dist/esm/hooks/useDevicChat.js.map +1 -1
- package/dist/esm/hooks/useModelInterface.d.ts +25 -3
- package/dist/esm/hooks/useModelInterface.js +33 -19
- package/dist/esm/hooks/useModelInterface.js.map +1 -1
- package/dist/esm/index.d.ts +5 -3
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/provider/DevicProvider.js +54 -15
- package/dist/esm/provider/DevicProvider.js.map +1 -1
- package/dist/esm/provider/index.d.ts +1 -1
- package/dist/esm/provider/types.d.ts +50 -0
- package/dist/esm/styles.css +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AIElementWrapper.js","sources":["../../../../../src/components/AIElementWrapper/AIElementWrapper.tsx"],"sourcesContent":["import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useOptionalDevicContext } from '../../provider';\nimport { useAIElementWrapper } from './useAIElementWrapper';\nimport {\n getActiveWrapper,\n setActiveWrapper,\n subscribeActiveWrapper,\n} from './activeWrapperRegistry';\nimport { generateId } from '../../utils';\nimport type {\n AIElementWrapperHandle,\n AIElementWrapperOptions,\n AIElementWrapperPlacement,\n AIElementWrapperProps,\n} from './AIElementWrapper.types';\nimport './AIElementWrapper.css';\n\nconst DEFAULT_OPTIONS: Required<\n Omit<AIElementWrapperOptions, 'color' | 'drawerPromptPrefix' | 'defaultInlinePrompt'>\n> & {\n color?: string;\n drawerPromptPrefix?: AIElementWrapperOptions['drawerPromptPrefix'];\n defaultInlinePrompt?: string;\n} = {\n showOn: 'hover',\n triggerPlacement: 'bottom',\n tooltipPlacement: 'bottom',\n tooltipWidth: 360,\n triggerLabel: 'Preguntar a IA',\n highlightOnInteract: true,\n zIndex: 2147483000,\n triggerBorderRadius: 999,\n color: undefined,\n drawerPromptPrefix: undefined,\n defaultInlinePrompt: undefined,\n};\n\ninterface AnchorRect {\n top: number;\n left: number;\n width: number;\n height: number;\n}\n\nfunction rectFromDom(rect: DOMRect): AnchorRect {\n return { top: rect.top, left: rect.left, width: rect.width, height: rect.height };\n}\n\nfunction placementStyle(\n placement: AIElementWrapperPlacement,\n anchor: AnchorRect,\n offset = 8\n): React.CSSProperties {\n const cx = anchor.left + anchor.width / 2;\n const cy = anchor.top + anchor.height / 2;\n switch (placement) {\n case 'top':\n return { position: 'fixed', top: anchor.top - offset, left: cx, transform: 'translate(-50%, -100%)' };\n case 'bottom':\n return { position: 'fixed', top: anchor.top + anchor.height + offset, left: cx, transform: 'translateX(-50%)' };\n case 'left':\n return { position: 'fixed', top: cy, left: anchor.left - offset, transform: 'translate(-100%, -50%)' };\n case 'right':\n return { position: 'fixed', top: cy, left: anchor.left + anchor.width + offset, transform: 'translateY(-50%)' };\n }\n}\n\n/**\n * AIElementWrapper wraps an arbitrary React node and exposes an AI trigger\n * that can either show an inline floating tooltip with the assistant's\n * answer (`behavior='inline'`) or push a reference to the registered\n * ChatDrawer (`behavior='drawer'`).\n *\n * The trigger and inline tooltip are rendered through a React portal anchored\n * to the wrapped element, so they always sit above other UI (including the\n * ChatDrawer) regardless of stacking context.\n */\nexport const AIElementWrapper = forwardRef<AIElementWrapperHandle, AIElementWrapperProps>(\n function AIElementWrapper(props, ref) {\n const {\n label,\n data,\n referenceContent,\n behavior = 'inline',\n trigger,\n options = {},\n assistantId,\n getPrompt,\n apiKey,\n baseUrl,\n tenantId,\n tenantMetadata,\n modelInterfaceTools,\n inlineRenderer,\n onActivate,\n onInlineResponse,\n onError,\n className,\n style,\n children,\n } = props;\n\n const merged = useMemo(() => ({ ...DEFAULT_OPTIONS, ...options }), [options]);\n\n // Stable instance ID used by the active-wrapper registry (singleton)\n const wrapperIdRef = useRef<string>('');\n if (!wrapperIdRef.current) wrapperIdRef.current = generateId();\n\n const [activeWrapperId, setActiveWrapperLocal] = useState<string | null>(getActiveWrapper());\n useEffect(() => subscribeActiveWrapper(setActiveWrapperLocal), []);\n\n const context = useOptionalDevicContext();\n const containerRef = useRef<HTMLSpanElement>(null);\n const tooltipRef = useRef<HTMLDivElement>(null);\n const triggerRef = useRef<HTMLDivElement>(null);\n\n const [isHovered, setIsHovered] = useState(false);\n const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const setHoveredImmediately = useCallback((v: boolean) => {\n if (hoverTimerRef.current) {\n clearTimeout(hoverTimerRef.current);\n hoverTimerRef.current = null;\n }\n if (v) {\n setIsHovered(true);\n } else {\n // Grace period so the cursor can travel from the wrapper to the\n // portal-rendered trigger without the trigger disappearing mid-flight.\n hoverTimerRef.current = setTimeout(() => setIsHovered(false), 200);\n }\n }, []);\n useEffect(() => () => {\n if (hoverTimerRef.current) clearTimeout(hoverTimerRef.current);\n }, []);\n const [isInlineOpen, setIsInlineOpen] = useState(false);\n const [containerRect, setContainerRect] = useState<AnchorRect | null>(null);\n const [selectionRect, setSelectionRect] = useState<AnchorRect | null>(null);\n\n const inline = useAIElementWrapper({\n assistantId,\n apiKey,\n baseUrl,\n tenantId,\n tenantMetadata,\n modelInterfaceTools,\n onResponse: onInlineResponse,\n onError,\n });\n\n // What this wrapper would show if there were no coordination.\n const wantsTriggerVisible =\n merged.showOn === 'always' ||\n (merged.showOn === 'hover' && isHovered) ||\n (merged.showOn === 'click' && isInlineOpen) ||\n (merged.showOn === 'select' && selectionRect !== null);\n\n // Coordinate via the singleton registry so only one wrapper shows the\n // floating trigger at a time. The most recent wrapper to want visibility\n // wins; others hide until they are activated again.\n const isActive = activeWrapperId === wrapperIdRef.current;\n const triggerVisible = wantsTriggerVisible && (activeWrapperId === null || isActive);\n\n useEffect(() => {\n const id = wrapperIdRef.current;\n if (wantsTriggerVisible) {\n setActiveWrapper(id);\n } else if (getActiveWrapper() === id) {\n setActiveWrapper(null);\n }\n }, [wantsTriggerVisible]);\n\n // Release the registry slot if the component unmounts while active.\n useEffect(\n () => () => {\n if (getActiveWrapper() === wrapperIdRef.current) {\n setActiveWrapper(null);\n }\n },\n []\n );\n\n // Track container rect (for hover/click/always trigger and tooltip anchor)\n const updateContainerRect = useCallback(() => {\n const el = containerRef.current;\n if (!el) return;\n setContainerRect(rectFromDom(el.getBoundingClientRect()));\n }, []);\n\n useLayoutEffect(() => {\n if (!triggerVisible && !isInlineOpen) return;\n updateContainerRect();\n const onScrollOrResize = () => updateContainerRect();\n window.addEventListener('scroll', onScrollOrResize, true);\n window.addEventListener('resize', onScrollOrResize);\n return () => {\n window.removeEventListener('scroll', onScrollOrResize, true);\n window.removeEventListener('resize', onScrollOrResize);\n };\n }, [triggerVisible, isInlineOpen, updateContainerRect]);\n\n // selectionchange listener for showOn='select'\n useEffect(() => {\n if (merged.showOn !== 'select') {\n setSelectionRect(null);\n return;\n }\n const isInside = (node: Node | null, cont: HTMLElement) => {\n if (!node) return false;\n if (node === cont) return true;\n return cont.contains(node);\n };\n const recompute = () => {\n const sel = window.getSelection();\n const cont = containerRef.current;\n if (!sel || sel.isCollapsed || !cont || sel.rangeCount === 0) {\n setSelectionRect(null);\n return;\n }\n // Don't react to selections happening elsewhere — but tolerate the\n // case where anchor or focus are inside our container.\n if (!isInside(sel.anchorNode, cont) && !isInside(sel.focusNode, cont)) {\n setSelectionRect(null);\n return;\n }\n const range = sel.getRangeAt(0);\n const rect = range.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) {\n setSelectionRect(null);\n return;\n }\n setSelectionRect(rectFromDom(rect));\n };\n const onMouseUp = () => {\n // Run on next tick so the browser commits the final selection state.\n setTimeout(recompute, 0);\n };\n document.addEventListener('selectionchange', recompute);\n document.addEventListener('mouseup', onMouseUp);\n return () => {\n document.removeEventListener('selectionchange', recompute);\n document.removeEventListener('mouseup', onMouseUp);\n };\n }, [merged.showOn]);\n\n const buildPrompt = useCallback((): string => {\n if (getPrompt) return getPrompt({ data, label });\n if (merged.defaultInlinePrompt) return merged.defaultInlinePrompt;\n // Use selected text if available, otherwise fall back to label\n if (merged.showOn === 'select') {\n const sel = window.getSelection();\n const txt = sel?.toString().trim();\n if (txt) return `Cuéntame más sobre: \"${txt}\"`;\n }\n return `Cuéntame más sobre: ${label}`;\n }, [getPrompt, data, label, merged.defaultInlinePrompt, merged.showOn]);\n\n const handleActivate = useCallback(() => {\n onActivate?.();\n\n if (behavior === 'inline') {\n if (!assistantId) {\n const err = new Error('assistantId is required for behavior=\"inline\"');\n onError?.(err);\n // eslint-disable-next-line no-console\n console.warn('[AIElementWrapper]', err.message);\n return;\n }\n setIsInlineOpen(true);\n inline.reset();\n inline.sendInlinePrompt(buildPrompt());\n return;\n }\n\n // drawer behavior\n if (!context) {\n // eslint-disable-next-line no-console\n console.warn(\n '[AIElementWrapper] behavior=\"drawer\" requires a DevicProvider ancestor.'\n );\n return;\n }\n // For 'select' showOn, prefer selected text as label content fallback\n let finalLabel = label;\n if (merged.showOn === 'select') {\n const txt = window.getSelection()?.toString().trim();\n if (txt) finalLabel = txt;\n }\n context.addReference({ label: finalLabel, content: referenceContent, data });\n context.openDrawer();\n }, [\n onActivate,\n behavior,\n assistantId,\n onError,\n inline,\n buildPrompt,\n context,\n label,\n referenceContent,\n data,\n merged.showOn,\n ]);\n\n const closeInline = useCallback(() => {\n setIsInlineOpen(false);\n inline.reset();\n }, [inline]);\n\n useImperativeHandle(\n ref,\n () => ({\n activate: handleActivate,\n close: closeInline,\n }),\n [handleActivate, closeInline]\n );\n\n // Click outside to close inline tooltip\n useEffect(() => {\n if (!isInlineOpen) return;\n const handler = (e: MouseEvent) => {\n const t = tooltipRef.current;\n const c = containerRef.current;\n const tr = triggerRef.current;\n const target = e.target as Node;\n if (\n t && !t.contains(target) &&\n c && !c.contains(target) &&\n (!tr || !tr.contains(target))\n ) {\n closeInline();\n }\n };\n document.addEventListener('mousedown', handler);\n return () => document.removeEventListener('mousedown', handler);\n }, [isInlineOpen, closeInline]);\n\n // Anchor for trigger: selection rect (when showOn='select') else container rect\n const triggerAnchor = merged.showOn === 'select' ? selectionRect : containerRect;\n // Tooltip anchor: container rect (or selection if select mode)\n const tooltipAnchor = merged.showOn === 'select' && selectionRect ? selectionRect : containerRect;\n\n const triggerStyle = useMemo<React.CSSProperties>(() => {\n if (!triggerAnchor) return { display: 'none' };\n return {\n ...placementStyle(merged.triggerPlacement, triggerAnchor),\n zIndex: merged.zIndex + 1,\n pointerEvents: 'auto',\n };\n }, [triggerAnchor, merged.triggerPlacement, merged.zIndex]);\n\n const tooltipStyle = useMemo<React.CSSProperties>(() => {\n const w = typeof merged.tooltipWidth === 'number' ? `${merged.tooltipWidth}px` : merged.tooltipWidth;\n if (!tooltipAnchor) return { display: 'none' };\n return {\n ...placementStyle(merged.tooltipPlacement, tooltipAnchor),\n width: w,\n zIndex: merged.zIndex,\n };\n }, [tooltipAnchor, merged.tooltipPlacement, merged.tooltipWidth, merged.zIndex]);\n\n const renderInlineContent = () => {\n if (inline.error) {\n return <div className=\"devic-aiwrap-error\">{inline.error.message}</div>;\n }\n if (inline.isProcessing) {\n return (\n <div className=\"devic-aiwrap-processing\">\n <span className=\"devic-aiwrap-spinner\" aria-hidden=\"true\" />\n <span>Pensando…</span>\n </div>\n );\n }\n if (inline.response) {\n if (inlineRenderer) return inlineRenderer(inline.response);\n const text =\n typeof inline.response.content === 'string'\n ? inline.response.content\n : (inline.response.content as any)?.message || '';\n return <div className=\"devic-aiwrap-answer\">{text}</div>;\n }\n return null;\n };\n\n const triggerNode = trigger ?? (\n <button\n type=\"button\"\n className=\"devic-aiwrap-trigger\"\n style={{\n borderRadius:\n typeof merged.triggerBorderRadius === 'number'\n ? `${merged.triggerBorderRadius}px`\n : merged.triggerBorderRadius,\n ...(merged.color ? { ['--devic-aiwrap-color' as any]: merged.color } : {}),\n }}\n >\n <span className=\"devic-aiwrap-trigger-icon\" aria-hidden=\"true\">\n <SparklesIcon />\n </span>\n <span className=\"devic-aiwrap-trigger-label\">{merged.triggerLabel}</span>\n </button>\n );\n\n const portalTarget = typeof document !== 'undefined' ? document.body : null;\n\n return (\n <span\n ref={containerRef}\n className={`devic-aiwrap-container ${className || ''}`}\n style={{ position: 'relative', display: 'inline-block', ...style }}\n data-highlight={merged.highlightOnInteract && (isHovered || isInlineOpen) ? 'true' : 'false'}\n onMouseEnter={() => setHoveredImmediately(true)}\n onMouseLeave={() => setHoveredImmediately(false)}\n >\n <span className=\"devic-aiwrap-content\">{children}</span>\n\n {portalTarget && triggerVisible &&\n createPortal(\n <div\n ref={triggerRef}\n className=\"devic-aiwrap-trigger-wrapper\"\n style={triggerStyle}\n onMouseEnter={() => setHoveredImmediately(true)}\n onMouseLeave={() => setHoveredImmediately(false)}\n onMouseDown={(e) => {\n // Prevent losing the text selection when interacting with trigger\n e.preventDefault();\n }}\n onClick={(e) => {\n e.stopPropagation();\n handleActivate();\n }}\n >\n {triggerNode}\n </div>,\n portalTarget\n )}\n\n {portalTarget && behavior === 'inline' && isInlineOpen &&\n createPortal(\n <div\n ref={tooltipRef}\n className=\"devic-aiwrap-tooltip\"\n style={tooltipStyle}\n data-placement={merged.tooltipPlacement}\n >\n <div className=\"devic-aiwrap-tooltip-header\">\n <span className=\"devic-aiwrap-tooltip-label\">{label}</span>\n <button\n type=\"button\"\n className=\"devic-aiwrap-tooltip-close\"\n onClick={closeInline}\n aria-label=\"Cerrar\"\n >\n <CloseIcon />\n </button>\n </div>\n <div className=\"devic-aiwrap-tooltip-body\">{renderInlineContent()}</div>\n </div>,\n portalTarget\n )}\n </span>\n );\n }\n);\n\nfunction SparklesIcon(): JSX.Element {\n return (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 20 20\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M10 2L11.5 8.5L18 10L11.5 11.5L10 18L8.5 11.5L2 10L8.5 8.5L10 2Z\" opacity=\"0.95\" />\n <path d=\"M16 3L16.5 5L18.5 5.5L16.5 6L16 8L15.5 6L13.5 5.5L15.5 5L16 3Z\" opacity=\"0.6\" />\n </svg>\n );\n}\n\nfunction CloseIcon(): JSX.Element {\n return (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </svg>\n );\n}\n"],"names":["forwardRef","useMemo","useRef","generateId","useState","getActiveWrapper","useEffect","subscribeActiveWrapper","useOptionalDevicContext","useCallback","useAIElementWrapper","setActiveWrapper","useLayoutEffect","useImperativeHandle","_jsx","_jsxs","createPortal"],"mappings":";;;;;;;;;;AA2BA,MAAM,eAAe,GAMjB;AACF,IAAA,MAAM,EAAE,OAAO;AACf,IAAA,gBAAgB,EAAE,QAAQ;AAC1B,IAAA,gBAAgB,EAAE,QAAQ;AAC1B,IAAA,YAAY,EAAE,GAAG;AACjB,IAAA,YAAY,EAAE,gBAAgB;AAC9B,IAAA,mBAAmB,EAAE,IAAI;AACzB,IAAA,MAAM,EAAE,UAAU;AAClB,IAAA,mBAAmB,EAAE,GAAG;AACxB,IAAA,KAAK,EAAE,SAAS;AAChB,IAAA,kBAAkB,EAAE,SAAS;AAC7B,IAAA,mBAAmB,EAAE,SAAS;CAC/B;AASD,SAAS,WAAW,CAAC,IAAa,EAAA;IAChC,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE;AACnF;AAEA,SAAS,cAAc,CACrB,SAAoC,EACpC,MAAkB,EAClB,MAAM,GAAG,CAAC,EAAA;IAEV,MAAM,EAAE,GAAG,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,GAAG,CAAC;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC;IACzC,QAAQ,SAAS;AACf,QAAA,KAAK,KAAK;YACR,OAAO,EA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ACEC,eAAA,CAAA,KAAA,EAAA,EAAK,KAAK,EAAC,IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,cAAc,EAAC,KAAK,EAAC,4BAA4B,aACpGD,cAAA,CAAA,MAAA,EAAA,EAAM,CAAC,EAAC,kEAAkE,EAAC,OAAO,EAAC,MAAM,GAAG,EAC5FA,cAAA,CAAA,MAAA,EAAA,EAAM,CAAC,EAAC,gEAAgE,EAAC,OAAO,EAAC,KAAK,EAAA,CAAG,CAAA,EAAA,CACrF;AAEV;AAEA,SAAS,SAAS,GAAA;AAChB,IAAA,QACEC,eAAA,CAAA,KAAA,EAAA,EAAK,KAAK,EAAC,IAAI,EAAC,MAAM,EAAC,IAAI,EAAC,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,EAAC,WAAW,EAAC,GAAG,EAAC,aAAa,EAAC,OAAO,EAAC,cAAc,EAAC,OAAO,EAAA,QAAA,EAAA,CAC5ID,cAAA,CAAA,MAAA,EAAA,EAAM,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,IAAI,EAAA,CAAG,EACtCA,cAAA,CAAA,MAAA,EAAA,EAAM,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,IAAI,EAAA,CAAG,CAAA,EAAA,CAClC;AAEV;;;;"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Module-level singleton that coordinates which AIElementWrapper instance
|
|
5
|
+
* currently owns the floating trigger. Ensures only one wrapper shows its
|
|
6
|
+
* trigger at any given time across the page.
|
|
7
|
+
*/
|
|
8
|
+
let activeId = null;
|
|
9
|
+
const listeners = new Set();
|
|
10
|
+
function getActiveWrapper() {
|
|
11
|
+
return activeId;
|
|
12
|
+
}
|
|
13
|
+
function setActiveWrapper(id) {
|
|
14
|
+
if (activeId === id)
|
|
15
|
+
return;
|
|
16
|
+
activeId = id;
|
|
17
|
+
for (const l of listeners)
|
|
18
|
+
l(activeId);
|
|
19
|
+
}
|
|
20
|
+
function subscribeActiveWrapper(listener) {
|
|
21
|
+
listeners.add(listener);
|
|
22
|
+
return () => {
|
|
23
|
+
listeners.delete(listener);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
exports.getActiveWrapper = getActiveWrapper;
|
|
28
|
+
exports.setActiveWrapper = setActiveWrapper;
|
|
29
|
+
exports.subscribeActiveWrapper = subscribeActiveWrapper;
|
|
30
|
+
//# sourceMappingURL=activeWrapperRegistry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"activeWrapperRegistry.js","sources":["../../../../../src/components/AIElementWrapper/activeWrapperRegistry.ts"],"sourcesContent":["/**\n * Module-level singleton that coordinates which AIElementWrapper instance\n * currently owns the floating trigger. Ensures only one wrapper shows its\n * trigger at any given time across the page.\n */\n\ntype Listener = (activeId: string | null) => void;\n\nlet activeId: string | null = null;\nconst listeners = new Set<Listener>();\n\nexport function getActiveWrapper(): string | null {\n return activeId;\n}\n\nexport function setActiveWrapper(id: string | null): void {\n if (activeId === id) return;\n activeId = id;\n for (const l of listeners) l(activeId);\n}\n\nexport function subscribeActiveWrapper(listener: Listener): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n"],"names":[],"mappings":";;AAAA;;;;AAIG;AAIH,IAAI,QAAQ,GAAkB,IAAI;AAClC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAY;SAErB,gBAAgB,GAAA;AAC9B,IAAA,OAAO,QAAQ;AACjB;AAEM,SAAU,gBAAgB,CAAC,EAAiB,EAAA;IAChD,IAAI,QAAQ,KAAK,EAAE;QAAE;IACrB,QAAQ,GAAG,EAAE;IACb,KAAK,MAAM,CAAC,IAAI,SAAS;QAAE,CAAC,CAAC,QAAQ,CAAC;AACxC;AAEM,SAAU,sBAAsB,CAAC,QAAkB,EAAA;AACvD,IAAA,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AACvB,IAAA,OAAO,MAAK;AACV,QAAA,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,CAAC;AACH;;;;;;"}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var React = require('react');
|
|
4
|
+
require('react/jsx-runtime');
|
|
5
|
+
var DevicContext = require('../../provider/DevicContext.js');
|
|
6
|
+
var client = require('../../api/client.js');
|
|
7
|
+
var usePolling = require('../../hooks/usePolling.js');
|
|
8
|
+
var useModelInterface = require('../../hooks/useModelInterface.js');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Hook that manages the inline AI generation flow for AIElementWrapper.
|
|
12
|
+
* Reuses sendMessageAsync + polling, similar to useAIGenerationButton but
|
|
13
|
+
* without the modal/tooltip UI orchestration.
|
|
14
|
+
*/
|
|
15
|
+
function useAIElementWrapper(options) {
|
|
16
|
+
const { assistantId, apiKey: propsApiKey, baseUrl: propsBaseUrl, tenantId, tenantMetadata, modelInterfaceTools = [], onResponse, onError, } = options;
|
|
17
|
+
const context = DevicContext.useOptionalDevicContext();
|
|
18
|
+
const apiKey = propsApiKey || context?.apiKey;
|
|
19
|
+
const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';
|
|
20
|
+
const resolvedTenantId = tenantId || context?.tenantId;
|
|
21
|
+
const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };
|
|
22
|
+
const [isProcessing, setIsProcessing] = React.useState(false);
|
|
23
|
+
const [response, setResponse] = React.useState(null);
|
|
24
|
+
const [error, setError] = React.useState(null);
|
|
25
|
+
const [chatUid, setChatUid] = React.useState(null);
|
|
26
|
+
const [shouldPoll, setShouldPoll] = React.useState(false);
|
|
27
|
+
const onResponseRef = React.useRef(onResponse);
|
|
28
|
+
const onErrorRef = React.useRef(onError);
|
|
29
|
+
React.useEffect(() => {
|
|
30
|
+
onResponseRef.current = onResponse;
|
|
31
|
+
onErrorRef.current = onError;
|
|
32
|
+
});
|
|
33
|
+
const clientRef = React.useRef(null);
|
|
34
|
+
if (!clientRef.current && apiKey) {
|
|
35
|
+
clientRef.current = new client.DevicApiClient({ apiKey, baseUrl });
|
|
36
|
+
}
|
|
37
|
+
React.useEffect(() => {
|
|
38
|
+
if (clientRef.current && apiKey) {
|
|
39
|
+
clientRef.current.setConfig({ apiKey, baseUrl });
|
|
40
|
+
}
|
|
41
|
+
}, [apiKey, baseUrl]);
|
|
42
|
+
const { toolSchemas, handleToolCalls: executeToolCalls, extractPendingToolCalls, } = useModelInterface.useModelInterface({ tools: modelInterfaceTools });
|
|
43
|
+
const handlePendingToolCalls = React.useCallback(async (data) => {
|
|
44
|
+
if (!clientRef.current || !chatUid || !assistantId)
|
|
45
|
+
return;
|
|
46
|
+
const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);
|
|
47
|
+
if (pendingCalls.length === 0)
|
|
48
|
+
return;
|
|
49
|
+
try {
|
|
50
|
+
const { responses } = await executeToolCalls(pendingCalls);
|
|
51
|
+
if (responses.length > 0) {
|
|
52
|
+
await clientRef.current.sendToolResponses(assistantId, chatUid, responses);
|
|
53
|
+
setShouldPoll(true);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
58
|
+
setError(error);
|
|
59
|
+
onErrorRef.current?.(error);
|
|
60
|
+
}
|
|
61
|
+
}, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]);
|
|
62
|
+
usePolling.usePolling(shouldPoll ? chatUid : null, async () => {
|
|
63
|
+
if (!clientRef.current || !chatUid || !assistantId) {
|
|
64
|
+
throw new Error('Cannot poll without client, chatUid or assistantId');
|
|
65
|
+
}
|
|
66
|
+
return clientRef.current.getRealtimeHistory(assistantId, chatUid);
|
|
67
|
+
}, {
|
|
68
|
+
interval: 1000,
|
|
69
|
+
enabled: shouldPoll,
|
|
70
|
+
stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],
|
|
71
|
+
onUpdate: async (data) => {
|
|
72
|
+
if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {
|
|
73
|
+
await handlePendingToolCalls(data);
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
onStop: (data) => {
|
|
77
|
+
setShouldPoll(false);
|
|
78
|
+
if (data?.status === 'error') {
|
|
79
|
+
setIsProcessing(false);
|
|
80
|
+
const err = new Error('Processing failed');
|
|
81
|
+
setError(err);
|
|
82
|
+
onErrorRef.current?.(err);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (data?.status === 'completed') {
|
|
86
|
+
setIsProcessing(false);
|
|
87
|
+
const assistantMessages = data.chatHistory.filter((m) => m.role === 'assistant');
|
|
88
|
+
const last = assistantMessages[assistantMessages.length - 1];
|
|
89
|
+
if (last) {
|
|
90
|
+
setResponse(last);
|
|
91
|
+
onResponseRef.current?.(last);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
onError: (err) => {
|
|
96
|
+
setError(err);
|
|
97
|
+
setIsProcessing(false);
|
|
98
|
+
setShouldPoll(false);
|
|
99
|
+
onErrorRef.current?.(err);
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
const sendInlinePrompt = React.useCallback(async (prompt) => {
|
|
103
|
+
if (!assistantId) {
|
|
104
|
+
const err = new Error('assistantId is required for inline behavior');
|
|
105
|
+
setError(err);
|
|
106
|
+
onErrorRef.current?.(err);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (!clientRef.current) {
|
|
110
|
+
const err = new Error('API client not configured. Please provide an API key.');
|
|
111
|
+
setError(err);
|
|
112
|
+
onErrorRef.current?.(err);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const trimmed = prompt.trim();
|
|
116
|
+
if (!trimmed) {
|
|
117
|
+
const err = new Error('Prompt is empty');
|
|
118
|
+
setError(err);
|
|
119
|
+
onErrorRef.current?.(err);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
setIsProcessing(true);
|
|
123
|
+
setError(null);
|
|
124
|
+
setResponse(null);
|
|
125
|
+
try {
|
|
126
|
+
const dto = {
|
|
127
|
+
message: trimmed,
|
|
128
|
+
metadata: resolvedTenantMetadata,
|
|
129
|
+
tenantId: resolvedTenantId,
|
|
130
|
+
...(toolSchemas.length > 0 && { tools: toolSchemas }),
|
|
131
|
+
};
|
|
132
|
+
const resp = await clientRef.current.sendMessageAsync(assistantId, dto);
|
|
133
|
+
if (resp.chatUid)
|
|
134
|
+
setChatUid(resp.chatUid);
|
|
135
|
+
setShouldPoll(true);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
139
|
+
setError(error);
|
|
140
|
+
setIsProcessing(false);
|
|
141
|
+
onErrorRef.current?.(error);
|
|
142
|
+
}
|
|
143
|
+
}, [assistantId, resolvedTenantId, resolvedTenantMetadata, toolSchemas]);
|
|
144
|
+
const reset = React.useCallback(() => {
|
|
145
|
+
setIsProcessing(false);
|
|
146
|
+
setResponse(null);
|
|
147
|
+
setError(null);
|
|
148
|
+
setChatUid(null);
|
|
149
|
+
setShouldPoll(false);
|
|
150
|
+
}, []);
|
|
151
|
+
return {
|
|
152
|
+
isProcessing,
|
|
153
|
+
response,
|
|
154
|
+
error,
|
|
155
|
+
sendInlinePrompt,
|
|
156
|
+
reset,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
exports.useAIElementWrapper = useAIElementWrapper;
|
|
161
|
+
//# sourceMappingURL=useAIElementWrapper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAIElementWrapper.js","sources":["../../../../../src/components/AIElementWrapper/useAIElementWrapper.ts"],"sourcesContent":["import { useState, useCallback, useRef, useEffect } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\n\nexport interface UseAIElementWrapperOptions {\n assistantId?: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (message: ChatMessage) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface UseAIElementWrapperResult {\n isProcessing: boolean;\n response: ChatMessage | null;\n error: Error | null;\n /** Send a prompt to the inline assistant. */\n sendInlinePrompt: (prompt: string) => Promise<void>;\n /** Reset response/error state. */\n reset: () => void;\n}\n\n/**\n * Hook that manages the inline AI generation flow for AIElementWrapper.\n * Reuses sendMessageAsync + polling, similar to useAIGenerationButton but\n * without the modal/tooltip UI orchestration.\n */\nexport function useAIElementWrapper(\n options: UseAIElementWrapperOptions\n): UseAIElementWrapperResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n modelInterfaceTools = [],\n onResponse,\n onError,\n } = options;\n\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n\n const [isProcessing, setIsProcessing] = useState(false);\n const [response, setResponse] = useState<ChatMessage | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n const onResponseRef = useRef(onResponse);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onResponseRef.current = onResponse;\n onErrorRef.current = onError;\n });\n\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && apiKey) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl });\n }\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({ tools: modelInterfaceTools });\n\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid || !assistantId) return;\n const pendingCalls =\n data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n if (pendingCalls.length === 0) return;\n try {\n const { responses } = await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(assistantId, chatUid, responses);\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]\n );\n\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid || !assistantId) {\n throw new Error('Cannot poll without client, chatUid or assistantId');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: 1000,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error('Processing failed');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n if (data?.status === 'completed') {\n setIsProcessing(false);\n const assistantMessages = data.chatHistory.filter(\n (m: ChatMessage) => m.role === 'assistant'\n );\n const last = assistantMessages[assistantMessages.length - 1];\n if (last) {\n setResponse(last);\n onResponseRef.current?.(last);\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n const sendInlinePrompt = useCallback(\n async (prompt: string) => {\n if (!assistantId) {\n const err = new Error('assistantId is required for inline behavior');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n if (!clientRef.current) {\n const err = new Error('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n const trimmed = prompt.trim();\n if (!trimmed) {\n const err = new Error('Prompt is empty');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n setIsProcessing(true);\n setError(null);\n setResponse(null);\n\n try {\n const dto = {\n message: trimmed,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n const resp = await clientRef.current.sendMessageAsync(assistantId, dto);\n if (resp.chatUid) setChatUid(resp.chatUid);\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n }\n },\n [assistantId, resolvedTenantId, resolvedTenantMetadata, toolSchemas]\n );\n\n const reset = useCallback(() => {\n setIsProcessing(false);\n setResponse(null);\n setError(null);\n setChatUid(null);\n setShouldPoll(false);\n }, []);\n\n return {\n isProcessing,\n response,\n error,\n sendInlinePrompt,\n reset,\n };\n}\n"],"names":["useOptionalDevicContext","useState","useRef","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;AAgCA;;;;AAIG;AACG,SAAU,mBAAmB,CACjC,OAAmC,EAAA;IAEnC,MAAM,EACJ,WAAW,EACX,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,OAAO,GACR,GAAG,OAAO;AAEX,IAAA,MAAM,OAAO,GA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AAC;aACtD;AACD,YAAA,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,gBAAgB,CAAC,WAAW,EAAE,GAAG,CAAC;YACvE,IAAI,IAAI,CAAC,OAAO;AAAE,gBAAA,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC;YAC1C,aAAa,CAAC,IAAI,CAAC;QACrB;QAAE,OAAO,GAAG,EAAE;YACZ,MAAM,KAAK,GAAG,GAAG,YAAY,KAAK,GAAG,GAAG,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACjE,QAAQ,CAAC,KAAK,CAAC;YACf,eAAe,CAAC,KAAK,CAAC;AACtB,YAAA,UAAU,CAAC,OAAO,GAAG,KAAK,CAAC;QAC7B;IACF,CAAC,EACD,CAAC,WAAW,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,WAAW,CAAC,CACrE;AAED,IAAA,MAAM,KAAK,GAAGA,iBAAW,CAAC,MAAK;QAC7B,eAAe,CAAC,KAAK,CAAC;QACtB,WAAW,CAAC,IAAI,CAAC;QACjB,QAAQ,CAAC,IAAI,CAAC;QACd,UAAU,CAAC,IAAI,CAAC;QAChB,aAAa,CAAC,KAAK,CAAC;IACtB,CAAC,EAAE,EAAE,CAAC;IAEN,OAAO;QACL,YAAY;QACZ,QAAQ;QACR,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN;AACH;;;;"}
|
|
@@ -120,7 +120,7 @@ function useAIGenerationButton(options) {
|
|
|
120
120
|
if (pendingCalls.length === 0)
|
|
121
121
|
return;
|
|
122
122
|
try {
|
|
123
|
-
const responses = await executeToolCalls(pendingCalls);
|
|
123
|
+
const { responses } = await executeToolCalls(pendingCalls);
|
|
124
124
|
if (responses.length > 0) {
|
|
125
125
|
await clientRef.current.sendToolResponses(assistantId, chatUid, responses);
|
|
126
126
|
setShouldPoll(true);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAIGenerationButton.js","sources":["../../../../../src/components/AIGenerationButton/useAIGenerationButton.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\nimport type {\n AIGenerationButtonOptions,\n GenerationResult,\n} from './AIGenerationButton.types';\nimport type { ToolCallSummary } from '../AICommandBar/AICommandBar.types';\n\nexport interface UseAIGenerationButtonOptions {\n assistantId: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n options?: AIGenerationButtonOptions;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (result: GenerationResult) => void;\n onBeforeSend?: (prompt: string) => string | undefined | Promise<string | undefined>;\n onError?: (error: Error) => void;\n onStart?: () => void;\n onOpen?: () => void;\n onClose?: () => void;\n disabled?: boolean;\n}\n\nexport interface UseAIGenerationButtonResult {\n // State\n isOpen: boolean;\n isProcessing: boolean;\n inputValue: string;\n setInputValue: (value: string) => void;\n error: Error | null;\n result: GenerationResult | null;\n\n // Tool calls state\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Input ref\n inputRef: React.RefObject<HTMLTextAreaElement>;\n\n // Actions\n open: () => void;\n close: () => void;\n toggle: () => void;\n generate: (prompt?: string) => Promise<GenerationResult | null>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n}\n\n/**\n * Hook for managing AIGenerationButton state and behavior\n */\nexport function useAIGenerationButton(\n options: UseAIGenerationButtonOptions\n): UseAIGenerationButtonResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n options: buttonOptions = {},\n modelInterfaceTools = [],\n onResponse,\n onBeforeSend,\n onError,\n onStart,\n onOpen,\n onClose,\n disabled,\n } = options;\n\n const { mode = 'modal' } = buttonOptions;\n\n // Get context\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n\n // State\n const [isOpen, setIsOpen] = useState(false);\n const [isProcessing, setIsProcessing] = useState(false);\n const [inputValue, setInputValue] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<GenerationResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // Tool calls state\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Refs\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const resolveRef = useRef<((value: GenerationResult | null) => void) | null>(null);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onBeforeSendRef = useRef(onBeforeSend);\n const onStartRef = useRef(onStart);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onBeforeSendRef.current = onBeforeSend;\n onStartRef.current = onStart;\n onOpenRef.current = onOpen;\n onCloseRef.current = onClose;\n });\n\n // API client\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && apiKey) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl });\n }\n\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n // Model interface\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({\n tools: modelInterfaceTools,\n });\n\n /**\n * Format tool name to human-readable (fallback when no summary)\n */\n const formatToolName = (toolName: string): string => {\n return toolName\n .replace(/_/g, ' ')\n .replace(/([A-Z])/g, ' $1')\n .trim()\n .toLowerCase()\n .replace(/^./, (c) => c.toUpperCase());\n };\n\n /**\n * Process tool calls from realtime data\n */\n const processToolCalls = useCallback((messages: ChatMessage[]): ToolCallSummary[] => {\n const summaries: ToolCallSummary[] = [];\n const toolResponseMap = new Map<string, any>();\n\n // Collect tool responses\n for (const msg of messages) {\n if (msg.role === 'tool' && msg.tool_call_id) {\n toolResponseMap.set(msg.tool_call_id, msg.content);\n }\n }\n\n // Collect tool calls from assistant messages\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.tool_calls?.length) {\n for (const tc of msg.tool_calls) {\n const hasResponse = toolResponseMap.has(tc.id);\n let input: any;\n try {\n input = JSON.parse(tc.function.arguments || '{}');\n } catch {\n input = {};\n }\n\n // Use message summary if available, otherwise format tool name\n const summaryText = msg.summary || formatToolName(tc.function.name);\n\n summaries.push({\n id: tc.id,\n name: tc.function.name,\n status: hasResponse ? 'completed' : 'executing',\n summary: summaryText,\n input,\n output: toolResponseMap.get(tc.id),\n });\n }\n }\n }\n\n return summaries;\n }, []);\n\n // Handle pending client-side tool calls\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid) return;\n\n const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n if (pendingCalls.length === 0) return;\n\n try {\n const responses = await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(assistantId, chatUid, responses);\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]\n );\n\n // Polling\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid) {\n throw new Error('Cannot poll without client or chatUid');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: 1000,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n // Update tool calls display\n const summaries = processToolCalls(data.chatHistory);\n setToolCalls(summaries);\n\n // Update current tool summary - show executing tool or last tool\n if (summaries.length > 0) {\n const lastExecuting = summaries.filter(s => s.status === 'executing').pop();\n const lastTool = summaries[summaries.length - 1];\n setCurrentToolSummary(lastExecuting?.summary || lastTool?.summary || null);\n }\n\n // Handle client-side tool calls\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error('Processing failed');\n setError(err);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\n return;\n }\n\n if (data?.status === 'completed') {\n setIsProcessing(false);\n\n // Extract final assistant message\n const assistantMessages = data.chatHistory.filter((m: ChatMessage) => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const finalToolCalls = processToolCalls(data.chatHistory);\n const generationResult: GenerationResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: finalToolCalls,\n rawResponse: data,\n };\n\n setResult(generationResult);\n onResponseRef.current?.(generationResult);\n resolveRef.current?.(generationResult);\n resolveRef.current = null;\n\n // Close modal/tooltip after successful generation\n setIsOpen(false);\n onCloseRef.current?.();\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\n },\n }\n );\n\n // Open modal/tooltip\n const open = useCallback(() => {\n if (disabled) return;\n setIsOpen(true);\n setError(null);\n onOpenRef.current?.();\n // Focus input after opening\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [disabled]);\n\n // Close modal/tooltip\n const close = useCallback(() => {\n setIsOpen(false);\n setInputValue('');\n onCloseRef.current?.();\n }, []);\n\n // Toggle\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n // Generate\n const generate = useCallback(\n async (prompt?: string): Promise<GenerationResult | null> => {\n // Determine the prompt to use\n let finalPrompt = prompt ?? inputValue;\n\n // For direct mode, use predefined prompt if no prompt provided\n if (mode === 'direct' && !finalPrompt) {\n finalPrompt = buttonOptions.prompt || '';\n }\n\n if (!finalPrompt.trim()) {\n const err = new Error('Prompt is required');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n if (disabled) {\n return null;\n }\n\n if (!clientRef.current) {\n const err = new Error('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n // Call onBeforeSend hook\n if (onBeforeSendRef.current) {\n const modifiedPrompt = await onBeforeSendRef.current(finalPrompt);\n if (modifiedPrompt !== undefined) {\n finalPrompt = modifiedPrompt;\n }\n }\n\n // Start processing\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n onStartRef.current?.();\n\n // Create a promise that will resolve when generation completes\n const resultPromise = new Promise<GenerationResult | null>((resolve) => {\n resolveRef.current = resolve;\n });\n\n try {\n const dto = {\n message: finalPrompt,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n\n const response = await clientRef.current.sendMessageAsync(assistantId, dto);\n\n if (response.chatUid) {\n setChatUid(response.chatUid);\n }\n\n setShouldPoll(true);\n\n return resultPromise;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n return null;\n }\n },\n [\n inputValue,\n mode,\n buttonOptions.prompt,\n disabled,\n assistantId,\n resolvedTenantId,\n resolvedTenantMetadata,\n toolSchemas,\n ]\n );\n\n // Reset\n const reset = useCallback(() => {\n setIsOpen(false);\n setIsProcessing(false);\n setInputValue('');\n setError(null);\n setResult(null);\n setChatUid(null);\n setShouldPoll(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\n }, []);\n\n // Handle keyboard events\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n // Handle Escape\n if (e.key === 'Escape') {\n e.preventDefault();\n close();\n return;\n }\n\n // Handle Enter to submit (Cmd/Ctrl + Enter or Enter without Shift)\n if (e.key === 'Enter' && !isProcessing) {\n if (e.metaKey || e.ctrlKey || !e.shiftKey) {\n e.preventDefault();\n generate();\n }\n }\n },\n [isProcessing, generate, close]\n );\n\n return {\n isOpen,\n isProcessing,\n inputValue,\n setInputValue,\n error,\n result,\n toolCalls,\n currentToolSummary,\n inputRef,\n open,\n close,\n toggle,\n generate,\n reset,\n handleKeyDown,\n };\n}\n"],"names":["useOptionalDevicContext","useState","useRef","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;AA0DA;;AAEG;AACG,SAAU,qBAAqB,CACnC,OAAqC,EAAA;AAErC,IAAA,MAAM,EACJ,WAAW,EACX,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,OAAO,EAAE,aAAa,GAAG,EAAE,EAC3B,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,YAAY,EACZ,OAAO,EACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,QAAQ,GACT,GAAG,OAAO;AAEX,IAAA,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE,GAAG,aAAa;;AAGxC,IAAA,MAAM,OAAO,GAAGA,oCAAuB,EAAE;AACzC,IAAA,MAAM,MAAM,GAAG,WAAW,IAAI,OAAO,EAAE,MAAM;IAC7C,MAAM,OAAO,GAAG,YAAY,IAAI,OAAO,EAAE,OAAO,IAAI,sBAAsB;AAC1E,IAAA,MAAM,gBAAgB,GAAG,QAAQ,IAAI,OAAO,EAAE,QAAQ;IACtD,MAAM,sBAAsB,GAAG,EAAE,GAAG,O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"useAIGenerationButton.js","sources":["../../../../../src/components/AIGenerationButton/useAIGenerationButton.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\nimport type {\n AIGenerationButtonOptions,\n GenerationResult,\n} from './AIGenerationButton.types';\nimport type { ToolCallSummary } from '../AICommandBar/AICommandBar.types';\n\nexport interface UseAIGenerationButtonOptions {\n assistantId: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n options?: AIGenerationButtonOptions;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (result: GenerationResult) => void;\n onBeforeSend?: (prompt: string) => string | undefined | Promise<string | undefined>;\n onError?: (error: Error) => void;\n onStart?: () => void;\n onOpen?: () => void;\n onClose?: () => void;\n disabled?: boolean;\n}\n\nexport interface UseAIGenerationButtonResult {\n // State\n isOpen: boolean;\n isProcessing: boolean;\n inputValue: string;\n setInputValue: (value: string) => void;\n error: Error | null;\n result: GenerationResult | null;\n\n // Tool calls state\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Input ref\n inputRef: React.RefObject<HTMLTextAreaElement>;\n\n // Actions\n open: () => void;\n close: () => void;\n toggle: () => void;\n generate: (prompt?: string) => Promise<GenerationResult | null>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n}\n\n/**\n * Hook for managing AIGenerationButton state and behavior\n */\nexport function useAIGenerationButton(\n options: UseAIGenerationButtonOptions\n): UseAIGenerationButtonResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n options: buttonOptions = {},\n modelInterfaceTools = [],\n onResponse,\n onBeforeSend,\n onError,\n onStart,\n onOpen,\n onClose,\n disabled,\n } = options;\n\n const { mode = 'modal' } = buttonOptions;\n\n // Get context\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n\n // State\n const [isOpen, setIsOpen] = useState(false);\n const [isProcessing, setIsProcessing] = useState(false);\n const [inputValue, setInputValue] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<GenerationResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // Tool calls state\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Refs\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const resolveRef = useRef<((value: GenerationResult | null) => void) | null>(null);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onBeforeSendRef = useRef(onBeforeSend);\n const onStartRef = useRef(onStart);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onBeforeSendRef.current = onBeforeSend;\n onStartRef.current = onStart;\n onOpenRef.current = onOpen;\n onCloseRef.current = onClose;\n });\n\n // API client\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && apiKey) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl });\n }\n\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n // Model interface\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({\n tools: modelInterfaceTools,\n });\n\n /**\n * Format tool name to human-readable (fallback when no summary)\n */\n const formatToolName = (toolName: string): string => {\n return toolName\n .replace(/_/g, ' ')\n .replace(/([A-Z])/g, ' $1')\n .trim()\n .toLowerCase()\n .replace(/^./, (c) => c.toUpperCase());\n };\n\n /**\n * Process tool calls from realtime data\n */\n const processToolCalls = useCallback((messages: ChatMessage[]): ToolCallSummary[] => {\n const summaries: ToolCallSummary[] = [];\n const toolResponseMap = new Map<string, any>();\n\n // Collect tool responses\n for (const msg of messages) {\n if (msg.role === 'tool' && msg.tool_call_id) {\n toolResponseMap.set(msg.tool_call_id, msg.content);\n }\n }\n\n // Collect tool calls from assistant messages\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.tool_calls?.length) {\n for (const tc of msg.tool_calls) {\n const hasResponse = toolResponseMap.has(tc.id);\n let input: any;\n try {\n input = JSON.parse(tc.function.arguments || '{}');\n } catch {\n input = {};\n }\n\n // Use message summary if available, otherwise format tool name\n const summaryText = msg.summary || formatToolName(tc.function.name);\n\n summaries.push({\n id: tc.id,\n name: tc.function.name,\n status: hasResponse ? 'completed' : 'executing',\n summary: summaryText,\n input,\n output: toolResponseMap.get(tc.id),\n });\n }\n }\n }\n\n return summaries;\n }, []);\n\n // Handle pending client-side tool calls\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid) return;\n\n const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n if (pendingCalls.length === 0) return;\n\n try {\n const { responses } = await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(assistantId, chatUid, responses);\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]\n );\n\n // Polling\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid) {\n throw new Error('Cannot poll without client or chatUid');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: 1000,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n // Update tool calls display\n const summaries = processToolCalls(data.chatHistory);\n setToolCalls(summaries);\n\n // Update current tool summary - show executing tool or last tool\n if (summaries.length > 0) {\n const lastExecuting = summaries.filter(s => s.status === 'executing').pop();\n const lastTool = summaries[summaries.length - 1];\n setCurrentToolSummary(lastExecuting?.summary || lastTool?.summary || null);\n }\n\n // Handle client-side tool calls\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error('Processing failed');\n setError(err);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\n return;\n }\n\n if (data?.status === 'completed') {\n setIsProcessing(false);\n\n // Extract final assistant message\n const assistantMessages = data.chatHistory.filter((m: ChatMessage) => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const finalToolCalls = processToolCalls(data.chatHistory);\n const generationResult: GenerationResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: finalToolCalls,\n rawResponse: data,\n };\n\n setResult(generationResult);\n onResponseRef.current?.(generationResult);\n resolveRef.current?.(generationResult);\n resolveRef.current = null;\n\n // Close modal/tooltip after successful generation\n setIsOpen(false);\n onCloseRef.current?.();\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\n },\n }\n );\n\n // Open modal/tooltip\n const open = useCallback(() => {\n if (disabled) return;\n setIsOpen(true);\n setError(null);\n onOpenRef.current?.();\n // Focus input after opening\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [disabled]);\n\n // Close modal/tooltip\n const close = useCallback(() => {\n setIsOpen(false);\n setInputValue('');\n onCloseRef.current?.();\n }, []);\n\n // Toggle\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n // Generate\n const generate = useCallback(\n async (prompt?: string): Promise<GenerationResult | null> => {\n // Determine the prompt to use\n let finalPrompt = prompt ?? inputValue;\n\n // For direct mode, use predefined prompt if no prompt provided\n if (mode === 'direct' && !finalPrompt) {\n finalPrompt = buttonOptions.prompt || '';\n }\n\n if (!finalPrompt.trim()) {\n const err = new Error('Prompt is required');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n if (disabled) {\n return null;\n }\n\n if (!clientRef.current) {\n const err = new Error('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n // Call onBeforeSend hook\n if (onBeforeSendRef.current) {\n const modifiedPrompt = await onBeforeSendRef.current(finalPrompt);\n if (modifiedPrompt !== undefined) {\n finalPrompt = modifiedPrompt;\n }\n }\n\n // Start processing\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n onStartRef.current?.();\n\n // Create a promise that will resolve when generation completes\n const resultPromise = new Promise<GenerationResult | null>((resolve) => {\n resolveRef.current = resolve;\n });\n\n try {\n const dto = {\n message: finalPrompt,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n\n const response = await clientRef.current.sendMessageAsync(assistantId, dto);\n\n if (response.chatUid) {\n setChatUid(response.chatUid);\n }\n\n setShouldPoll(true);\n\n return resultPromise;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n return null;\n }\n },\n [\n inputValue,\n mode,\n buttonOptions.prompt,\n disabled,\n assistantId,\n resolvedTenantId,\n resolvedTenantMetadata,\n toolSchemas,\n ]\n );\n\n // Reset\n const reset = useCallback(() => {\n setIsOpen(false);\n setIsProcessing(false);\n setInputValue('');\n setError(null);\n setResult(null);\n setChatUid(null);\n setShouldPoll(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\n }, []);\n\n // Handle keyboard events\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n // Handle Escape\n if (e.key === 'Escape') {\n e.preventDefault();\n close();\n return;\n }\n\n // Handle Enter to submit (Cmd/Ctrl + Enter or Enter without Shift)\n if (e.key === 'Enter' && !isProcessing) {\n if (e.metaKey || e.ctrlKey || !e.shiftKey) {\n e.preventDefault();\n generate();\n }\n }\n },\n [isProcessing, generate, close]\n );\n\n return {\n isOpen,\n isProcessing,\n inputValue,\n setInputValue,\n error,\n result,\n toolCalls,\n currentToolSummary,\n inputRef,\n open,\n close,\n toggle,\n generate,\n reset,\n handleKeyDown,\n };\n}\n"],"names":["useOptionalDevicContext","useState","useRef","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;AA0DA;;AAEG;AACG,SAAU,qBAAqB,CACnC,OAAqC,EAAA;AAErC,IAAA,MAAM,EACJ,WAAW,EACX,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,OAAO,EAAE,aAAa,GAAG,EAAE,EAC3B,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,YAAY,EACZ,OAAO,EACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,QAAQ,GACT,GAAG,OAAO;AAEX,IAAA,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE,GAAG,aAAa;;AAGxC,IAAA,MAAM,OAAO,GAAGA,oCAAuB,EAAE;AACzC,IAAA,MAAM,MAAM,GAAG,WAAW,IAAI,OAAO,EAAE,MAAM;IAC7C,MAAM,OAAO,GAAG,YAAY,IAAI,OAAO,EAAE,OAAO,IAAI,sBAAsB;AAC1E,IAAA,MAAM,gBAAgB,GAAG,QAAQ,IAAI,OAAO,EAAE,QAAQ;IACtD,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;KACd;AACH;;;;"}
|
|
@@ -174,10 +174,51 @@ function ChatDrawerInner({ assistantId, chatUid: initialChatUid, options = {}, e
|
|
|
174
174
|
chat.sendMessage(message);
|
|
175
175
|
},
|
|
176
176
|
}), [handleOpen, handleClose, handleToggle, chat]);
|
|
177
|
-
//
|
|
177
|
+
// Register this drawer in the DevicProvider so AIElementWrapper can open it
|
|
178
|
+
React.useEffect(() => {
|
|
179
|
+
if (!context?.registerDrawer)
|
|
180
|
+
return;
|
|
181
|
+
const unregister = context.registerDrawer({
|
|
182
|
+
open: handleOpen,
|
|
183
|
+
close: handleClose,
|
|
184
|
+
toggle: handleToggle,
|
|
185
|
+
sendMessage: (message) => chat.sendMessage(message),
|
|
186
|
+
});
|
|
187
|
+
return unregister;
|
|
188
|
+
}, [context, handleOpen, handleClose, handleToggle, chat]);
|
|
189
|
+
// Partition pending widget calls by render mode
|
|
190
|
+
const { inlineWidgets, inputWidget } = React.useMemo(() => {
|
|
191
|
+
const inline = [];
|
|
192
|
+
let input = null;
|
|
193
|
+
for (const wc of chat.pendingWidgetCalls) {
|
|
194
|
+
if (wc.widget.render === 'input' && !input) {
|
|
195
|
+
input = wc;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
inline.push(wc);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return { inlineWidgets: inline, inputWidget: input };
|
|
202
|
+
}, [chat.pendingWidgetCalls]);
|
|
203
|
+
// Active references from DevicProvider (created by AIElementWrapper)
|
|
204
|
+
const references = context?.references ?? [];
|
|
205
|
+
const removeReference = React.useCallback((id) => {
|
|
206
|
+
context?.removeReference(id);
|
|
207
|
+
}, [context]);
|
|
208
|
+
const clearReferences = React.useCallback(() => {
|
|
209
|
+
context?.clearReferences();
|
|
210
|
+
}, [context]);
|
|
211
|
+
// Handle send message — prefix references and clear them after sending
|
|
178
212
|
const handleSend = React.useCallback((message, files) => {
|
|
179
|
-
|
|
180
|
-
|
|
213
|
+
let finalMessage = message;
|
|
214
|
+
if (references.length > 0) {
|
|
215
|
+
const labels = references.map((r) => `"${r.label}"`).join(', ');
|
|
216
|
+
finalMessage = `Elemento referenciado: ${labels}\n\n${message}`;
|
|
217
|
+
}
|
|
218
|
+
chat.sendMessage(finalMessage, { files });
|
|
219
|
+
if (references.length > 0)
|
|
220
|
+
clearReferences();
|
|
221
|
+
}, [chat, references, clearReferences]);
|
|
181
222
|
// Handle conversation selection
|
|
182
223
|
const handleConversationSelect = React.useCallback((chatUid) => {
|
|
183
224
|
chat.loadChat(chatUid);
|
|
@@ -324,12 +365,19 @@ function ChatDrawerInner({ assistantId, chatUid: initialChatUid, options = {}, e
|
|
|
324
365
|
[mergedOptions.position]: 20,
|
|
325
366
|
bottom: 20,
|
|
326
367
|
}), [mergedOptions.zIndex, mergedOptions.position]);
|
|
327
|
-
return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [!isInline && (jsxRuntime.jsx("div", { className: "devic-drawer-overlay", "data-open": isOpen, style: overlayStyle, onClick: handleClose })), jsxRuntime.jsxs("div", { ref: drawerRef, className: `devic-chat-drawer ${className || ''}`, "data-position": mergedOptions.position, "data-open": isOpen, "data-mode": mode, style: drawerStyle, children: [mergedOptions.resizable && (jsxRuntime.jsx("div", { className: "devic-resize-handle", "data-position": mergedOptions.position, onMouseDown: handleResizeStart })), jsxRuntime.jsxs("div", { className: "devic-drawer-header", children: [avatarUrl && (jsxRuntime.jsx("img", { className: "devic-drawer-avatar", src: avatarUrl, alt: "", "aria-hidden": "true" })), jsxRuntime.jsx("h2", { className: "devic-drawer-title", children: mergedOptions.title }), jsxRuntime.jsx(ConversationSelector.ConversationSelector, { assistantId: assistantId, currentChatUid: chat.chatUid, onSelect: handleConversationSelect, onNewChat: handleNewChat, apiKey: apiKey, baseUrl: baseUrl, tenantId: tenantId, conversationPreview: mergedOptions.conversationPreview }), jsxRuntime.jsxs("div", { className: "devic-drawer-header-actions", children: [jsxRuntime.jsx("button", { className: "devic-new-chat-btn", onClick: handleNewChat, type: "button", "aria-label": "New chat", title: "New chat", children: jsxRuntime.jsx(PlusIcon, {}) }), !isInline && (jsxRuntime.jsx("button", { className: "devic-drawer-close", onClick: handleClose, type: "button", "aria-label": "Close chat", children: jsxRuntime.jsx(CloseIcon, {}) }))] })] }), chat.error && (jsxRuntime.jsx("div", { className: "devic-error", children: chat.error.message })), jsxRuntime.jsx(ChatMessages.ChatMessages, { messages: chat.messages, allMessages: chat.messages, isLoading: chat.isLoading, welcomeMessage: mergedOptions.welcomeMessage, suggestedMessages: mergedOptions.suggestedMessages, onSuggestedClick: handleSuggestedClick, showToolTimeline: mergedOptions.showToolTimeline, toolRenderers: mergedOptions.toolRenderers, toolIcons: mergedOptions.toolIcons, loadingIndicator: mergedOptions.loadingIndicator, showFeedback: mergedOptions.showFeedback, feedbackMap: feedbackMap, onFeedback: handleFeedback, handedOffSubThreadId: chat.handedOffSubThreadId || undefined, onHandoffCompleted: chat.onHandoffCompleted, handoffWidgetRenderer: mergedOptions.handoffWidgetRenderer, toolGroups: mergedOptions.toolGroups, apiKey: resolvedApiKey, baseUrl: resolvedBaseUrl }), mergedOptions.customPromptBox ? (jsxRuntime.jsx("div", { className: "devic-input-area", children: mergedOptions.customPromptBox({
|
|
368
|
+
return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [!isInline && (jsxRuntime.jsx("div", { className: "devic-drawer-overlay", "data-open": isOpen, style: overlayStyle, onClick: handleClose })), jsxRuntime.jsxs("div", { ref: drawerRef, className: `devic-chat-drawer ${className || ''}`, "data-position": mergedOptions.position, "data-open": isOpen, "data-mode": mode, style: drawerStyle, children: [mergedOptions.resizable && (jsxRuntime.jsx("div", { className: "devic-resize-handle", "data-position": mergedOptions.position, onMouseDown: handleResizeStart })), jsxRuntime.jsxs("div", { className: "devic-drawer-header", children: [avatarUrl && (jsxRuntime.jsx("img", { className: "devic-drawer-avatar", src: avatarUrl, alt: "", "aria-hidden": "true" })), jsxRuntime.jsx("h2", { className: "devic-drawer-title", children: mergedOptions.title }), jsxRuntime.jsx(ConversationSelector.ConversationSelector, { assistantId: assistantId, currentChatUid: chat.chatUid, onSelect: handleConversationSelect, onNewChat: handleNewChat, apiKey: apiKey, baseUrl: baseUrl, tenantId: tenantId, conversationPreview: mergedOptions.conversationPreview }), jsxRuntime.jsxs("div", { className: "devic-drawer-header-actions", children: [jsxRuntime.jsx("button", { className: "devic-new-chat-btn", onClick: handleNewChat, type: "button", "aria-label": "New chat", title: "New chat", children: jsxRuntime.jsx(PlusIcon, {}) }), !isInline && (jsxRuntime.jsx("button", { className: "devic-drawer-close", onClick: handleClose, type: "button", "aria-label": "Close chat", children: jsxRuntime.jsx(CloseIcon, {}) }))] })] }), chat.error && (jsxRuntime.jsx("div", { className: "devic-error", children: chat.error.message })), jsxRuntime.jsx(ChatMessages.ChatMessages, { messages: chat.messages, allMessages: chat.messages, isLoading: chat.isLoading, welcomeMessage: mergedOptions.welcomeMessage, suggestedMessages: mergedOptions.suggestedMessages, onSuggestedClick: handleSuggestedClick, showToolTimeline: mergedOptions.showToolTimeline, toolRenderers: mergedOptions.toolRenderers, toolIcons: mergedOptions.toolIcons, loadingIndicator: mergedOptions.loadingIndicator, showFeedback: mergedOptions.showFeedback, feedbackMap: feedbackMap, onFeedback: handleFeedback, handedOffSubThreadId: chat.handedOffSubThreadId || undefined, onHandoffCompleted: chat.onHandoffCompleted, handoffWidgetRenderer: mergedOptions.handoffWidgetRenderer, toolGroups: mergedOptions.toolGroups, apiKey: resolvedApiKey, baseUrl: resolvedBaseUrl, pendingInlineWidgets: inlineWidgets, onSubmitWidget: chat.submitWidgetResponse, onCancelWidget: chat.cancelWidgetCall }), mergedOptions.customPromptBox ? (jsxRuntime.jsx("div", { className: "devic-input-area", children: mergedOptions.customPromptBox({
|
|
328
369
|
sendMessage: handleSend,
|
|
329
370
|
stop: chat.stopChat,
|
|
330
371
|
isLoading: chat.isLoading,
|
|
331
372
|
newConversation: chat.clearChat,
|
|
332
|
-
|
|
373
|
+
references,
|
|
374
|
+
removeReference,
|
|
375
|
+
clearReferences,
|
|
376
|
+
}) })) : (jsxRuntime.jsx(ChatInput.ChatInput, { onSend: handleSend, disabled: chat.isLoading || chat.handedOff || inlineWidgets.length > 0, placeholder: mergedOptions.inputPlaceholder, enableFileUploads: mergedOptions.enableFileUploads, allowedFileTypes: mergedOptions.allowedFileTypes, maxFileSize: mergedOptions.maxFileSize, sendButtonContent: mergedOptions.sendButtonContent, disabledMessage: chat.handedOff
|
|
377
|
+
? 'Waiting for subagent to complete'
|
|
378
|
+
: inlineWidgets.length > 0
|
|
379
|
+
? 'Waiting for tool response'
|
|
380
|
+
: undefined, isProcessing: chat.isLoading && !chat.handedOff, onStop: chat.stopChat, stopButtonContent: mergedOptions.stopButtonContent, pendingInputWidget: inputWidget, onSubmitWidget: chat.submitWidgetResponse, onCancelWidget: chat.cancelWidgetCall, references: references, onRemoveReference: removeReference }))] }), !isInline && !isOpen && (jsxRuntime.jsx("button", { className: "devic-trigger", onClick: handleOpen, style: triggerStyle, type: "button", "aria-label": "Open chat", children: jsxRuntime.jsx(ChatIcon, {}) }))] }));
|
|
333
381
|
}
|
|
334
382
|
/**
|
|
335
383
|
* Close icon
|