@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.
Files changed (70) hide show
  1. package/dist/cjs/api/types.js.map +1 -1
  2. package/dist/cjs/components/AICommandBar/useAICommandBar.js +1 -1
  3. package/dist/cjs/components/AICommandBar/useAICommandBar.js.map +1 -1
  4. package/dist/cjs/components/AIElementWrapper/AIElementWrapper.js +334 -0
  5. package/dist/cjs/components/AIElementWrapper/AIElementWrapper.js.map +1 -0
  6. package/dist/cjs/components/AIElementWrapper/activeWrapperRegistry.js +30 -0
  7. package/dist/cjs/components/AIElementWrapper/activeWrapperRegistry.js.map +1 -0
  8. package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js +161 -0
  9. package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js.map +1 -0
  10. package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js +1 -1
  11. package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
  12. package/dist/cjs/components/ChatDrawer/ChatDrawer.js +53 -5
  13. package/dist/cjs/components/ChatDrawer/ChatDrawer.js.map +1 -1
  14. package/dist/cjs/components/ChatDrawer/ChatInput.js +13 -2
  15. package/dist/cjs/components/ChatDrawer/ChatInput.js.map +1 -1
  16. package/dist/cjs/components/ChatDrawer/ChatMessages.js +34 -4
  17. package/dist/cjs/components/ChatDrawer/ChatMessages.js.map +1 -1
  18. package/dist/cjs/components/ChatDrawer/HandoffSubagentWidget.js +1 -1
  19. package/dist/cjs/hooks/useDevicChat.js +71 -6
  20. package/dist/cjs/hooks/useDevicChat.js.map +1 -1
  21. package/dist/cjs/hooks/useModelInterface.js +33 -19
  22. package/dist/cjs/hooks/useModelInterface.js.map +1 -1
  23. package/dist/cjs/index.js +4 -0
  24. package/dist/cjs/index.js.map +1 -1
  25. package/dist/cjs/provider/DevicProvider.js +53 -14
  26. package/dist/cjs/provider/DevicProvider.js.map +1 -1
  27. package/dist/cjs/styles.css +1 -1
  28. package/dist/esm/api/types.d.ts +45 -2
  29. package/dist/esm/api/types.js.map +1 -1
  30. package/dist/esm/components/AICommandBar/useAICommandBar.js +1 -1
  31. package/dist/esm/components/AICommandBar/useAICommandBar.js.map +1 -1
  32. package/dist/esm/components/AIElementWrapper/AIElementWrapper.d.ts +14 -0
  33. package/dist/esm/components/AIElementWrapper/AIElementWrapper.js +332 -0
  34. package/dist/esm/components/AIElementWrapper/AIElementWrapper.js.map +1 -0
  35. package/dist/esm/components/AIElementWrapper/AIElementWrapper.types.d.ts +185 -0
  36. package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.d.ts +10 -0
  37. package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.js +26 -0
  38. package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.js.map +1 -0
  39. package/dist/esm/components/AIElementWrapper/index.d.ts +3 -0
  40. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.d.ts +26 -0
  41. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js +159 -0
  42. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js.map +1 -0
  43. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js +1 -1
  44. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
  45. package/dist/esm/components/ChatDrawer/ChatDrawer.js +53 -5
  46. package/dist/esm/components/ChatDrawer/ChatDrawer.js.map +1 -1
  47. package/dist/esm/components/ChatDrawer/ChatDrawer.types.d.ts +24 -0
  48. package/dist/esm/components/ChatDrawer/ChatInput.d.ts +1 -1
  49. package/dist/esm/components/ChatDrawer/ChatInput.js +14 -3
  50. package/dist/esm/components/ChatDrawer/ChatInput.js.map +1 -1
  51. package/dist/esm/components/ChatDrawer/ChatMessages.d.ts +1 -1
  52. package/dist/esm/components/ChatDrawer/ChatMessages.js +34 -4
  53. package/dist/esm/components/ChatDrawer/ChatMessages.js.map +1 -1
  54. package/dist/esm/components/ChatDrawer/HandoffSubagentWidget.js +1 -1
  55. package/dist/esm/hooks/index.d.ts +1 -1
  56. package/dist/esm/hooks/useDevicChat.d.ts +15 -0
  57. package/dist/esm/hooks/useDevicChat.js +71 -6
  58. package/dist/esm/hooks/useDevicChat.js.map +1 -1
  59. package/dist/esm/hooks/useModelInterface.d.ts +25 -3
  60. package/dist/esm/hooks/useModelInterface.js +33 -19
  61. package/dist/esm/hooks/useModelInterface.js.map +1 -1
  62. package/dist/esm/index.d.ts +5 -3
  63. package/dist/esm/index.js +2 -0
  64. package/dist/esm/index.js.map +1 -1
  65. package/dist/esm/provider/DevicProvider.js +54 -15
  66. package/dist/esm/provider/DevicProvider.js.map +1 -1
  67. package/dist/esm/provider/index.d.ts +1 -1
  68. package/dist/esm/provider/types.d.ts +50 -0
  69. package/dist/esm/styles.css +1 -1
  70. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../../../src/api/types.ts"],"sourcesContent":["import type React from 'react';\n\n/**\n * File attachment for messages\n */\nexport interface ChatFile {\n name: string;\n downloadUrl?: string;\n fileType?: 'image' | 'document' | 'audio' | 'video' | 'other';\n}\n\n/**\n * Message content structure\n */\nexport interface MessageContent {\n message?: string;\n data?: any;\n files?: Array<{\n name: string;\n url: string;\n type: string;\n }>;\n}\n\n/**\n * Tool call from the model\n */\nexport interface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\n/**\n * Chat message structure\n */\nexport interface ChatMessage {\n uid: string;\n role: 'user' | 'assistant' | 'developer' | 'system' | 'tool';\n content: MessageContent;\n timestamp: number;\n chatUid?: string;\n tool_calls?: ToolCall[];\n tool_call_id?: string;\n summary?: string;\n}\n\n/**\n * Previous conversation message for initialization\n */\nexport interface PreviousMessage {\n message: string;\n role: 'user' | 'assistant';\n}\n\n/**\n * Model interface tool schema following OpenAI function calling format\n */\nexport interface ModelInterfaceToolSchema {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: {\n type: 'object';\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\n/**\n * Model interface tool definition for client-side tools\n */\nexport interface ModelInterfaceTool {\n toolName: string;\n schema: ModelInterfaceToolSchema;\n callback: (params: any) => Promise<any> | any;\n}\n\n/**\n * Tool call response to send back to the API\n */\nexport interface ToolCallResponse {\n tool_call_id: string;\n content: any;\n role: 'tool';\n}\n\n/**\n * DTO for sending messages to the assistant\n */\nexport interface ProcessMessageDto {\n message: string;\n chatUid?: string;\n userName?: string;\n files?: ChatFile[];\n metadata?: {\n promptTemplateParams?: Record<string, any>;\n tenantToken?: string;\n [key: string]: any;\n };\n tenantId?: string;\n previousConversation?: PreviousMessage[];\n enabledTools?: string[];\n provider?: string;\n model?: string;\n // Model interface protocol fields\n tools?: ModelInterfaceToolSchema[];\n applicationState?: Record<string, any>;\n skipSummarization?: boolean;\n}\n\n/**\n * Response from the assistant\n */\nexport interface AssistantResponse {\n messages: ChatMessage[];\n chatUid: string;\n inputTokens?: number;\n outputTokens?: number;\n}\n\n/**\n * Async mode response\n */\nexport interface AsyncResponse {\n chatUid: string;\n message?: string;\n error?: string;\n}\n\n/**\n * Real-time chat history status\n */\nexport type RealtimeStatus = 'processing' | 'completed' | 'error' | 'waiting_for_tool_response' | 'handed_off';\n\n/**\n * Real-time chat history response\n */\nexport interface RealtimeChatHistory {\n chatUID: string;\n clientUID: string;\n chatHistory: ChatMessage[];\n status: RealtimeStatus;\n lastUpdatedAt: number;\n pendingToolCalls?: ToolCall[];\n handedOffSubThreadId?: string;\n}\n\n/**\n * Chat history structure\n */\nexport interface ChatHistory {\n chatUID: string;\n clientUID: string;\n userUID: string;\n chatContent: ChatMessage[];\n name?: string;\n assistantSpecializationIdentifier: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n llm?: string;\n inputTokens?: number;\n outputTokens?: number;\n metadata?: Record<string, any>;\n tenantId?: string;\n handedOff?: boolean;\n handedOffSubThreadId?: string;\n handedOffToolCallId?: string;\n}\n\n/**\n * Assistant specialization info\n */\nexport interface AssistantSpecialization {\n identifier: string;\n name: string;\n description: string;\n state: 'active' | 'inactive' | 'coming_soon';\n imgUrl?: string;\n availableToolsGroups?: Array<{\n name: string;\n description?: string;\n uid?: string;\n iconUrl?: string;\n tools?: Array<{\n name: string;\n description: string;\n }>;\n }>;\n model?: string;\n isCustom?: boolean;\n creationTimestampMs?: number;\n}\n\n/**\n * Summary of a conversation for listing\n */\nexport interface ConversationSummary {\n chatUID: string;\n name?: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n}\n\nexport interface ListConversationsResponse {\n histories: ConversationSummary[];\n total: number;\n offset: number;\n limit: number;\n}\n\n/**\n * API error response\n */\nexport interface ApiError {\n statusCode: number;\n message: string;\n error?: string;\n}\n\n/**\n * Feedback submission request\n */\nexport interface FeedbackSubmission {\n messageId: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n}\n\n/**\n * Feedback entry response\n */\nexport interface FeedbackEntry {\n _id: string;\n requestId: string;\n chatUID?: string;\n threadId?: string;\n agentId?: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n creationTimestamp: string;\n lastEditTimestamp?: string;\n}\n\n/**\n * Agent thread states\n */\nexport enum AgentThreadState {\n QUEUED = 'queued',\n PROCESSING = 'processing',\n COMPLETED = 'completed',\n FAILED = 'failed',\n TERMINATED = 'terminated',\n PAUSED = 'paused',\n PAUSED_FOR_APPROVAL = 'paused_for_approval',\n APPROVAL_REJECTED = 'approval_rejected',\n WAITING_FOR_RESPONSE = 'waiting_for_response',\n PAUSED_FOR_RESUME = 'paused_for_resume',\n HANDED_OFF = 'handed_off',\n GUARDRAIL_TRIGGER = 'guardrail_trigger',\n}\n\n/**\n * Task within an agent thread\n */\nexport interface AgentTaskDto {\n _id?: string;\n title?: string;\n description?: string;\n completed: boolean;\n}\n\n/**\n * Agent thread DTO\n */\nexport interface AgentThreadDto {\n _id?: string;\n agentId: string;\n state: AgentThreadState;\n threadContent: ChatMessage[];\n tasks?: AgentTaskDto[];\n finishReason?: string;\n pausedReason?: string;\n name?: string;\n creationTimestampMs?: number;\n lastEditTimestampMs?: number;\n pauseUntil?: number;\n isSubthread?: boolean;\n parentThreadId?: string;\n subThreadToolCallId?: string;\n parentAgentId?: string;\n}\n\n/**\n * Agent details\n */\nexport interface AgentDto {\n _id?: string;\n name: string;\n description?: string;\n imgUrl?: string;\n agentId?: string;\n}\n\n/**\n * Hand-off tool response content\n */\nexport interface HandOffToolResponse {\n response: string;\n subthreadId: string;\n}\n\n/**\n * Represents a single tool call within a tool group\n */\nexport interface ToolGroupCall {\n name: string;\n input: any;\n output: any;\n toolCallId: string;\n}\n\n/**\n * Configuration for grouping consecutive tool calls under a single renderer\n */\nexport interface ToolGroupConfig {\n tools: string[];\n renderer: (calls: ToolGroupCall[]) => React.ReactNode;\n}\n"],"names":["AgentThreadState"],"mappings":";;AA2PA;;AAEG;AACSA;AAAZ,CAAA,UAAY,gBAAgB,EAAA;AAC1B,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,qBAAA,CAAA,GAAA,qBAA2C;AAC3C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACzC,CAAC,EAbWA,wBAAgB,KAAhBA,wBAAgB,GAAA,EAAA,CAAA,CAAA;;"}
1
+ {"version":3,"file":"types.js","sources":["../../../../src/api/types.ts"],"sourcesContent":["import type React from 'react';\n\n/**\n * File attachment for messages\n */\nexport interface ChatFile {\n name: string;\n downloadUrl?: string;\n fileType?: 'image' | 'document' | 'audio' | 'video' | 'other';\n}\n\n/**\n * Message content structure\n */\nexport interface MessageContent {\n message?: string;\n data?: any;\n files?: Array<{\n name: string;\n url: string;\n type: string;\n }>;\n}\n\n/**\n * Tool call from the model\n */\nexport interface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\n/**\n * Chat message structure\n */\nexport interface ChatMessage {\n uid: string;\n role: 'user' | 'assistant' | 'developer' | 'system' | 'tool';\n content: MessageContent;\n timestamp: number;\n chatUid?: string;\n tool_calls?: ToolCall[];\n tool_call_id?: string;\n summary?: string;\n}\n\n/**\n * Previous conversation message for initialization\n */\nexport interface PreviousMessage {\n message: string;\n role: 'user' | 'assistant';\n}\n\n/**\n * Model interface tool schema following OpenAI function calling format\n */\nexport interface ModelInterfaceToolSchema {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: {\n type: 'object';\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\n/**\n * Props passed to a response widget component.\n * The widget is responsible for collecting the user's response and\n * calling `submit` with the payload to resolve the tool call.\n */\nexport interface ResponseWidgetProps {\n /** The tool call this widget is responding to */\n toolCall: ToolCall;\n /** Parsed arguments from the tool call */\n params: any;\n /** Submit the tool response payload (sent as the tool call result to the model) */\n submit: (response: any) => void;\n /** Cancel the tool call. Sends an error response so the model can continue. */\n cancel?: (reason?: string) => void;\n /** Whether the widget is currently submitting */\n isSubmitting?: boolean;\n}\n\n/**\n * Interactive response widget configuration for a client-side tool.\n *\n * When the model calls a tool configured with a `responseWidget`, the\n * widget is rendered in the chat UI instead of executing a callback.\n * The user interacts with the widget, which calls `submit(response)` to\n * define the tool response sent back to the model.\n *\n * - `render: 'inline'` renders the widget in the message thread at the\n * position of the tool call. The text input remains enabled.\n * - `render: 'input'` replaces the chat input area with the widget\n * while it is pending. The text input is disabled until submission.\n */\nexport interface ResponseWidgetConfig {\n /** Where to render the widget */\n render: 'inline' | 'input';\n /** The widget component */\n component: React.ComponentType<ResponseWidgetProps>;\n}\n\n/**\n * Model interface tool definition for client-side tools.\n *\n * A tool must provide either a `callback` (executed automatically when\n * the model invokes the tool) or a `responseWidget` (renders UI for\n * the user to produce the tool response). Providing both is an error.\n */\nexport interface ModelInterfaceTool {\n toolName: string;\n schema: ModelInterfaceToolSchema;\n /** Executed automatically when the model calls this tool */\n callback?: (params: any) => Promise<any> | any;\n /** Interactive widget that collects the user's tool response */\n responseWidget?: ResponseWidgetConfig;\n}\n\n/**\n * Tool call response to send back to the API\n */\nexport interface ToolCallResponse {\n tool_call_id: string;\n content: any;\n role: 'tool';\n}\n\n/**\n * DTO for sending messages to the assistant\n */\nexport interface ProcessMessageDto {\n message: string;\n chatUid?: string;\n userName?: string;\n files?: ChatFile[];\n metadata?: {\n promptTemplateParams?: Record<string, any>;\n tenantToken?: string;\n [key: string]: any;\n };\n tenantId?: string;\n previousConversation?: PreviousMessage[];\n enabledTools?: string[];\n provider?: string;\n model?: string;\n // Model interface protocol fields\n tools?: ModelInterfaceToolSchema[];\n applicationState?: Record<string, any>;\n skipSummarization?: boolean;\n}\n\n/**\n * Response from the assistant\n */\nexport interface AssistantResponse {\n messages: ChatMessage[];\n chatUid: string;\n inputTokens?: number;\n outputTokens?: number;\n}\n\n/**\n * Async mode response\n */\nexport interface AsyncResponse {\n chatUid: string;\n message?: string;\n error?: string;\n}\n\n/**\n * Real-time chat history status\n */\nexport type RealtimeStatus = 'processing' | 'completed' | 'error' | 'waiting_for_tool_response' | 'handed_off';\n\n/**\n * Real-time chat history response\n */\nexport interface RealtimeChatHistory {\n chatUID: string;\n clientUID: string;\n chatHistory: ChatMessage[];\n status: RealtimeStatus;\n lastUpdatedAt: number;\n pendingToolCalls?: ToolCall[];\n handedOffSubThreadId?: string;\n}\n\n/**\n * Chat history structure\n */\nexport interface ChatHistory {\n chatUID: string;\n clientUID: string;\n userUID: string;\n chatContent: ChatMessage[];\n name?: string;\n assistantSpecializationIdentifier: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n llm?: string;\n inputTokens?: number;\n outputTokens?: number;\n metadata?: Record<string, any>;\n tenantId?: string;\n handedOff?: boolean;\n handedOffSubThreadId?: string;\n handedOffToolCallId?: string;\n}\n\n/**\n * Assistant specialization info\n */\nexport interface AssistantSpecialization {\n identifier: string;\n name: string;\n description: string;\n state: 'active' | 'inactive' | 'coming_soon';\n imgUrl?: string;\n availableToolsGroups?: Array<{\n name: string;\n description?: string;\n uid?: string;\n iconUrl?: string;\n tools?: Array<{\n name: string;\n description: string;\n }>;\n }>;\n model?: string;\n isCustom?: boolean;\n creationTimestampMs?: number;\n}\n\n/**\n * Summary of a conversation for listing\n */\nexport interface ConversationSummary {\n chatUID: string;\n name?: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n}\n\nexport interface ListConversationsResponse {\n histories: ConversationSummary[];\n total: number;\n offset: number;\n limit: number;\n}\n\n/**\n * API error response\n */\nexport interface ApiError {\n statusCode: number;\n message: string;\n error?: string;\n}\n\n/**\n * Feedback submission request\n */\nexport interface FeedbackSubmission {\n messageId: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n}\n\n/**\n * Feedback entry response\n */\nexport interface FeedbackEntry {\n _id: string;\n requestId: string;\n chatUID?: string;\n threadId?: string;\n agentId?: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n creationTimestamp: string;\n lastEditTimestamp?: string;\n}\n\n/**\n * Agent thread states\n */\nexport enum AgentThreadState {\n QUEUED = 'queued',\n PROCESSING = 'processing',\n COMPLETED = 'completed',\n FAILED = 'failed',\n TERMINATED = 'terminated',\n PAUSED = 'paused',\n PAUSED_FOR_APPROVAL = 'paused_for_approval',\n APPROVAL_REJECTED = 'approval_rejected',\n WAITING_FOR_RESPONSE = 'waiting_for_response',\n PAUSED_FOR_RESUME = 'paused_for_resume',\n HANDED_OFF = 'handed_off',\n GUARDRAIL_TRIGGER = 'guardrail_trigger',\n}\n\n/**\n * Task within an agent thread\n */\nexport interface AgentTaskDto {\n _id?: string;\n title?: string;\n description?: string;\n completed: boolean;\n}\n\n/**\n * Agent thread DTO\n */\nexport interface AgentThreadDto {\n _id?: string;\n agentId: string;\n state: AgentThreadState;\n threadContent: ChatMessage[];\n tasks?: AgentTaskDto[];\n finishReason?: string;\n pausedReason?: string;\n name?: string;\n creationTimestampMs?: number;\n lastEditTimestampMs?: number;\n pauseUntil?: number;\n isSubthread?: boolean;\n parentThreadId?: string;\n subThreadToolCallId?: string;\n parentAgentId?: string;\n}\n\n/**\n * Agent details\n */\nexport interface AgentDto {\n _id?: string;\n name: string;\n description?: string;\n imgUrl?: string;\n agentId?: string;\n}\n\n/**\n * Hand-off tool response content\n */\nexport interface HandOffToolResponse {\n response: string;\n subthreadId: string;\n}\n\n/**\n * Represents a single tool call within a tool group\n */\nexport interface ToolGroupCall {\n name: string;\n input: any;\n output: any;\n toolCallId: string;\n}\n\n/**\n * Configuration for grouping consecutive tool calls under a single renderer\n */\nexport interface ToolGroupConfig {\n tools: string[];\n renderer: (calls: ToolGroupCall[]) => React.ReactNode;\n}\n"],"names":["AgentThreadState"],"mappings":";;AAwSA;;AAEG;AACSA;AAAZ,CAAA,UAAY,gBAAgB,EAAA;AAC1B,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,qBAAA,CAAA,GAAA,qBAA2C;AAC3C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACzC,CAAC,EAbWA,wBAAgB,KAAhBA,wBAAgB,GAAA,EAAA,CAAA,CAAA;;"}
@@ -337,7 +337,7 @@ function useAICommandBar(options) {
337
337
  if (pendingCalls.length === 0)
338
338
  return;
339
339
  try {
340
- const responses = await executeToolCalls(pendingCalls);
340
+ const { responses } = await executeToolCalls(pendingCalls);
341
341
  if (responses.length > 0) {
342
342
  await clientRef.current.sendToolResponses(assistantId, chatUid, responses);
343
343
  setShouldPoll(true);
@@ -1 +1 @@
1
- {"version":3,"file":"useAICommandBar.js","sources":["../../../../../src/components/AICommandBar/useAICommandBar.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef, useMemo } 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 AICommandBarOptions,\n AICommandBarCommand,\n CommandBarResult,\n ToolCallSummary,\n ChatDrawerHandle,\n} from './AICommandBar.types';\n\nexport interface UseAICommandBarOptions {\n assistantId: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n options?: AICommandBarOptions;\n isVisible?: boolean;\n onVisibilityChange?: (visible: boolean) => void;\n onExecute?: 'openDrawer' | 'callback';\n chatDrawerRef?: React.RefObject<ChatDrawerHandle>;\n onResponse?: (response: CommandBarResult) => void;\n modelInterfaceTools?: ModelInterfaceTool[];\n onSubmit?: (message: string) => void;\n onToolCall?: (toolName: string, params: Record<string, any>) => void;\n onError?: (error: Error) => void;\n onOpen?: () => void;\n onClose?: () => void;\n}\n\nexport interface UseAICommandBarResult {\n // Visibility\n isVisible: boolean;\n open: () => void;\n close: () => void;\n toggle: () => void;\n\n // Input\n inputValue: string;\n setInputValue: (value: string) => void;\n inputRef: React.RefObject<HTMLInputElement>;\n focus: () => void;\n\n // Processing state\n isProcessing: boolean;\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Result\n result: CommandBarResult | null;\n chatUid: string | null;\n error: Error | null;\n\n // History\n history: string[];\n historyIndex: number;\n showingHistory: boolean;\n setShowingHistory: (show: boolean) => void;\n\n // Commands\n showingCommands: boolean;\n filteredCommands: AICommandBarCommand[];\n selectedCommandIndex: number;\n selectCommand: (command: AICommandBarCommand) => void;\n\n // Actions\n submit: (message?: string) => Promise<void>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n clearHistory: () => void;\n}\n\n/**\n * Parse a shortcut string like \"cmd+j\" into its components\n */\nfunction parseShortcut(shortcut: string): { key: string; modifiers: string[] } {\n const parts = shortcut.toLowerCase().split('+');\n const key = parts.pop() || '';\n const modifiers = parts;\n return { key, modifiers };\n}\n\n/**\n * Check if a keyboard event matches a shortcut string\n */\nfunction matchShortcut(event: KeyboardEvent, shortcut: string): boolean {\n const { key, modifiers } = parseShortcut(shortcut);\n\n const keyMatch = event.key.toLowerCase() === key;\n const cmdMatch = modifiers.includes('cmd') === (event.metaKey || event.ctrlKey);\n const shiftMatch = modifiers.includes('shift') === event.shiftKey;\n const altMatch = modifiers.includes('alt') === event.altKey;\n\n return keyMatch && cmdMatch && shiftMatch && altMatch;\n}\n\n/**\n * Format a shortcut string for display\n */\nexport function formatShortcut(shortcut: string): string {\n const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform);\n return shortcut\n .replace(/cmd/gi, isMac ? '\\u2318' : 'Ctrl')\n .replace(/shift/gi, '\\u21E7')\n .replace(/alt/gi, isMac ? '\\u2325' : 'Alt')\n .replace(/\\+/g, ' ')\n .replace(/([a-z])/gi, (match) => match.toUpperCase());\n}\n\n/**\n * Format tool name to human-readable (fallback when no summary)\n */\nfunction formatToolName(toolName: string): string {\n // Convert snake_case or camelCase to human-readable\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 * Hook for managing AICommandBar state and behavior\n */\nexport function useAICommandBar(options: UseAICommandBarOptions): UseAICommandBarResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n options: barOptions = {},\n isVisible: controlledVisible,\n onVisibilityChange,\n onExecute = 'callback',\n chatDrawerRef,\n onResponse,\n modelInterfaceTools = [],\n onSubmit,\n onToolCall,\n onError,\n onOpen,\n onClose,\n } = options;\n\n const { shortcut } = barOptions;\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 // Visibility state\n const [internalVisible, setInternalVisible] = useState(false);\n const isVisible = controlledVisible ?? internalVisible;\n\n // Input state\n const [inputValue, setInputValue] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n\n // Processing state\n const [isProcessing, setIsProcessing] = useState(false);\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Result state\n const [result, setResult] = useState<CommandBarResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Polling state\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // History state\n const enableHistory = barOptions.enableHistory !== false; // default true\n const maxHistoryItems = barOptions.maxHistoryItems ?? 50;\n const historyStorageKey = barOptions.historyStorageKey ?? 'devic-command-bar-history';\n const showHistoryCommand = barOptions.showHistoryCommand !== false; // default true\n\n const [history, setHistory] = useState<string[]>(() => {\n if (!enableHistory || typeof window === 'undefined') return [];\n try {\n const stored = localStorage.getItem(historyStorageKey);\n return stored ? JSON.parse(stored) : [];\n } catch {\n return [];\n }\n });\n const [historyIndex, setHistoryIndex] = useState(-1);\n const [showingHistory, setShowingHistory] = useState(false);\n const [tempInput, setTempInput] = useState(''); // Store current input when navigating history\n\n // Commands state\n const commands = barOptions.commands ?? [];\n const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);\n\n // Built-in history command\n const historyCommand: AICommandBarCommand = useMemo(() => ({\n keyword: 'history',\n description: 'Show command history',\n message: '', // Special handling\n }), []);\n\n // All available commands (user commands + built-in)\n const allCommands = useMemo(() => {\n const userCommands = commands;\n // Add history command if enabled and not overwritten\n if (showHistoryCommand && !userCommands.some(c => c.keyword === 'history')) {\n return [...userCommands, historyCommand];\n }\n return userCommands;\n }, [commands, showHistoryCommand, historyCommand]);\n\n // Detect if showing command suggestions\n const isCommandMode = inputValue.startsWith('/');\n const commandQuery = isCommandMode ? inputValue.slice(1).toLowerCase() : '';\n const showingCommands = isCommandMode && !isProcessing && !result;\n\n // Filter commands based on query\n const filteredCommands = useMemo(() => {\n if (!showingCommands) return [];\n if (commandQuery === '') return allCommands;\n return allCommands.filter(cmd =>\n cmd.keyword.toLowerCase().includes(commandQuery) ||\n cmd.description.toLowerCase().includes(commandQuery)\n );\n }, [showingCommands, commandQuery, allCommands]);\n\n // Reset command selection when filtered list changes\n useEffect(() => {\n setSelectedCommandIndex(0);\n }, [filteredCommands.length]);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onToolCallRef = useRef(onToolCall);\n const onSubmitRef = useRef(onSubmit);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onToolCallRef.current = onToolCall;\n onSubmitRef.current = onSubmit;\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 onToolExecute: onToolCall,\n });\n\n // Visibility controls\n const open = useCallback(() => {\n setInternalVisible(true);\n onVisibilityChange?.(true);\n onOpenRef.current?.();\n // Focus input after visibility change\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [onVisibilityChange]);\n\n const close = useCallback(() => {\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n }, [onVisibilityChange]);\n\n const toggle = useCallback(() => {\n if (isVisible) {\n close();\n } else {\n open();\n }\n }, [isVisible, open, close]);\n\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Save history to localStorage\n const saveHistory = useCallback((newHistory: string[]) => {\n if (!enableHistory || typeof window === 'undefined') return;\n try {\n localStorage.setItem(historyStorageKey, JSON.stringify(newHistory));\n } catch {\n // Ignore localStorage errors\n }\n }, [enableHistory, historyStorageKey]);\n\n // Add item to history\n const addToHistory = useCallback((message: string) => {\n if (!enableHistory || !message.trim() || message.startsWith('/')) return;\n\n setHistory(prev => {\n // Don't add duplicates at the top\n const filtered = prev.filter(item => item !== message);\n const newHistory = [message, ...filtered].slice(0, maxHistoryItems);\n saveHistory(newHistory);\n return newHistory;\n });\n setHistoryIndex(-1);\n }, [enableHistory, maxHistoryItems, saveHistory]);\n\n // Clear history\n const clearHistory = useCallback(() => {\n setHistory([]);\n setHistoryIndex(-1);\n if (enableHistory && typeof window !== 'undefined') {\n try {\n localStorage.removeItem(historyStorageKey);\n } catch {\n // Ignore\n }\n }\n }, [enableHistory, historyStorageKey]);\n\n // Navigate history\n const navigateHistory = useCallback((direction: 'up' | 'down') => {\n if (!enableHistory || history.length === 0) return;\n\n if (direction === 'up') {\n if (historyIndex === -1) {\n // Save current input before navigating\n setTempInput(inputValue);\n setHistoryIndex(0);\n setInputValue(history[0]);\n } else if (historyIndex < history.length - 1) {\n const newIndex = historyIndex + 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n }\n } else {\n if (historyIndex > 0) {\n const newIndex = historyIndex - 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n } else if (historyIndex === 0) {\n setHistoryIndex(-1);\n setInputValue(tempInput);\n }\n }\n }, [enableHistory, history, historyIndex, inputValue, tempInput]);\n\n // Ref to hold submit function (to avoid circular dependency)\n const submitRef = useRef<(message?: string) => Promise<void>>();\n\n // Select a command\n const selectCommand = useCallback((command: AICommandBarCommand) => {\n if (command.keyword === 'history') {\n // Special handling for history command\n setShowingHistory(true);\n setInputValue('');\n } else {\n // Send the command's message\n setInputValue('');\n submitRef.current?.(command.message);\n }\n }, []);\n\n // Navigate commands\n const navigateCommands = useCallback((direction: 'up' | 'down') => {\n if (filteredCommands.length === 0) return;\n\n if (direction === 'down') {\n setSelectedCommandIndex(prev =>\n prev < filteredCommands.length - 1 ? prev + 1 : 0\n );\n } else {\n setSelectedCommandIndex(prev =>\n prev > 0 ? prev - 1 : filteredCommands.length - 1\n );\n }\n }, [filteredCommands.length]);\n\n // Register keyboard shortcut\n useEffect(() => {\n if (!shortcut) return;\n\n const handler = (e: KeyboardEvent) => {\n if (matchShortcut(e, shortcut)) {\n e.preventDefault();\n toggle();\n }\n };\n\n window.addEventListener('keydown', handler);\n return () => window.removeEventListener('keydown', handler);\n }, [shortcut, toggle]);\n\n // Process tool calls from realtime data\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\n // Prefer showing an executing tool, but fall back to the last tool (completed or not)\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 return;\n }\n\n if (data?.status === 'completed') {\n setIsProcessing(false);\n\n // Extract final assistant message\n const assistantMessages = data.chatHistory.filter(m => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const commandResult: CommandBarResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: processToolCalls(data.chatHistory),\n };\n\n setResult(commandResult);\n\n // Handle execution mode\n if (onExecute === 'openDrawer' && chatDrawerRef?.current) {\n chatDrawerRef.current.setChatUid(chatUid);\n chatDrawerRef.current.open();\n // Close and reset the command bar when handing off to drawer\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n } else {\n onResponseRef.current?.(commandResult);\n }\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n // Submit message\n const submit = useCallback(\n async (message?: string) => {\n const msg = message ?? inputValue;\n if (!msg.trim()) 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\n // Add to history before processing\n addToHistory(msg);\n\n // Clear input and start processing\n setInputValue('');\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setShowingHistory(false);\n setHistoryIndex(-1);\n\n onSubmitRef.current?.(msg);\n\n try {\n const dto = {\n message: msg,\n chatUid: chatUid || undefined,\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 && response.chatUid !== chatUid) {\n setChatUid(response.chatUid);\n }\n\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 [inputValue, chatUid, assistantId, resolvedTenantId, resolvedTenantMetadata, toolSchemas, addToHistory]\n );\n\n // Update submit ref for use in selectCommand\n submitRef.current = submit;\n\n // Reset state\n const reset = useCallback(() => {\n setInputValue('');\n setIsProcessing(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setResult(null);\n setChatUid(null);\n setError(null);\n setShouldPoll(false);\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 if (showingHistory) {\n setShowingHistory(false);\n return;\n }\n if (showingCommands) {\n setInputValue('');\n return;\n }\n // Reset if there's a result or if processing\n if (result || isProcessing) {\n reset();\n }\n close();\n return;\n }\n\n // Handle arrow keys for commands\n if (showingCommands && filteredCommands.length > 0) {\n if (e.key === 'ArrowDown') {\n e.preventDefault();\n navigateCommands('down');\n return;\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateCommands('up');\n return;\n }\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n selectCommand(selectedCommand);\n }\n return;\n }\n if (e.key === 'Tab') {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n setInputValue('/' + selectedCommand.keyword + ' ');\n }\n return;\n }\n }\n\n // Handle arrow keys for history (only when not in command mode)\n if (!showingCommands && !isProcessing) {\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateHistory('up');\n return;\n }\n if (e.key === 'ArrowDown' && historyIndex >= 0) {\n e.preventDefault();\n navigateHistory('down');\n return;\n }\n }\n\n // Handle Enter to submit\n if (e.key === 'Enter' && !e.shiftKey && !isProcessing) {\n e.preventDefault();\n submit();\n }\n },\n [\n isProcessing,\n result,\n showingCommands,\n showingHistory,\n filteredCommands,\n selectedCommandIndex,\n historyIndex,\n submit,\n reset,\n close,\n navigateCommands,\n navigateHistory,\n selectCommand,\n ]\n );\n\n return {\n isVisible,\n open,\n close,\n toggle,\n inputValue,\n setInputValue,\n inputRef,\n focus,\n isProcessing,\n toolCalls,\n currentToolSummary,\n result,\n chatUid,\n error,\n history,\n historyIndex,\n showingHistory,\n setShowingHistory,\n showingCommands,\n filteredCommands,\n selectedCommandIndex,\n selectCommand,\n submit,\n reset,\n handleKeyDown,\n clearHistory,\n };\n}\n"],"names":["useOptionalDevicContext","useState","useRef","useMemo","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;AAgFA;;AAEG;AACH,SAAS,aAAa,CAAC,QAAgB,EAAA;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IAC/C,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE;IAC7B,MAAM,SAAS,GAAG,KAAK;AACvB,IAAA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE;AAC3B;AAEA;;AAEG;AACH,SAAS,aAAa,CAAC,KAAoB,EAAE,QAAgB,EAAA;IAC3D,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,aAAa,CAAC,QAAQ,CAAC;IAElD,MAAM,QAAQ,GAAG,KAAK,CA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"}
1
+ {"version":3,"file":"useAICommandBar.js","sources":["../../../../../src/components/AICommandBar/useAICommandBar.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef, useMemo } 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 AICommandBarOptions,\n AICommandBarCommand,\n CommandBarResult,\n ToolCallSummary,\n ChatDrawerHandle,\n} from './AICommandBar.types';\n\nexport interface UseAICommandBarOptions {\n assistantId: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n options?: AICommandBarOptions;\n isVisible?: boolean;\n onVisibilityChange?: (visible: boolean) => void;\n onExecute?: 'openDrawer' | 'callback';\n chatDrawerRef?: React.RefObject<ChatDrawerHandle>;\n onResponse?: (response: CommandBarResult) => void;\n modelInterfaceTools?: ModelInterfaceTool[];\n onSubmit?: (message: string) => void;\n onToolCall?: (toolName: string, params: Record<string, any>) => void;\n onError?: (error: Error) => void;\n onOpen?: () => void;\n onClose?: () => void;\n}\n\nexport interface UseAICommandBarResult {\n // Visibility\n isVisible: boolean;\n open: () => void;\n close: () => void;\n toggle: () => void;\n\n // Input\n inputValue: string;\n setInputValue: (value: string) => void;\n inputRef: React.RefObject<HTMLInputElement>;\n focus: () => void;\n\n // Processing state\n isProcessing: boolean;\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Result\n result: CommandBarResult | null;\n chatUid: string | null;\n error: Error | null;\n\n // History\n history: string[];\n historyIndex: number;\n showingHistory: boolean;\n setShowingHistory: (show: boolean) => void;\n\n // Commands\n showingCommands: boolean;\n filteredCommands: AICommandBarCommand[];\n selectedCommandIndex: number;\n selectCommand: (command: AICommandBarCommand) => void;\n\n // Actions\n submit: (message?: string) => Promise<void>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n clearHistory: () => void;\n}\n\n/**\n * Parse a shortcut string like \"cmd+j\" into its components\n */\nfunction parseShortcut(shortcut: string): { key: string; modifiers: string[] } {\n const parts = shortcut.toLowerCase().split('+');\n const key = parts.pop() || '';\n const modifiers = parts;\n return { key, modifiers };\n}\n\n/**\n * Check if a keyboard event matches a shortcut string\n */\nfunction matchShortcut(event: KeyboardEvent, shortcut: string): boolean {\n const { key, modifiers } = parseShortcut(shortcut);\n\n const keyMatch = event.key.toLowerCase() === key;\n const cmdMatch = modifiers.includes('cmd') === (event.metaKey || event.ctrlKey);\n const shiftMatch = modifiers.includes('shift') === event.shiftKey;\n const altMatch = modifiers.includes('alt') === event.altKey;\n\n return keyMatch && cmdMatch && shiftMatch && altMatch;\n}\n\n/**\n * Format a shortcut string for display\n */\nexport function formatShortcut(shortcut: string): string {\n const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform);\n return shortcut\n .replace(/cmd/gi, isMac ? '\\u2318' : 'Ctrl')\n .replace(/shift/gi, '\\u21E7')\n .replace(/alt/gi, isMac ? '\\u2325' : 'Alt')\n .replace(/\\+/g, ' ')\n .replace(/([a-z])/gi, (match) => match.toUpperCase());\n}\n\n/**\n * Format tool name to human-readable (fallback when no summary)\n */\nfunction formatToolName(toolName: string): string {\n // Convert snake_case or camelCase to human-readable\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 * Hook for managing AICommandBar state and behavior\n */\nexport function useAICommandBar(options: UseAICommandBarOptions): UseAICommandBarResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n options: barOptions = {},\n isVisible: controlledVisible,\n onVisibilityChange,\n onExecute = 'callback',\n chatDrawerRef,\n onResponse,\n modelInterfaceTools = [],\n onSubmit,\n onToolCall,\n onError,\n onOpen,\n onClose,\n } = options;\n\n const { shortcut } = barOptions;\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 // Visibility state\n const [internalVisible, setInternalVisible] = useState(false);\n const isVisible = controlledVisible ?? internalVisible;\n\n // Input state\n const [inputValue, setInputValue] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n\n // Processing state\n const [isProcessing, setIsProcessing] = useState(false);\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Result state\n const [result, setResult] = useState<CommandBarResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Polling state\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // History state\n const enableHistory = barOptions.enableHistory !== false; // default true\n const maxHistoryItems = barOptions.maxHistoryItems ?? 50;\n const historyStorageKey = barOptions.historyStorageKey ?? 'devic-command-bar-history';\n const showHistoryCommand = barOptions.showHistoryCommand !== false; // default true\n\n const [history, setHistory] = useState<string[]>(() => {\n if (!enableHistory || typeof window === 'undefined') return [];\n try {\n const stored = localStorage.getItem(historyStorageKey);\n return stored ? JSON.parse(stored) : [];\n } catch {\n return [];\n }\n });\n const [historyIndex, setHistoryIndex] = useState(-1);\n const [showingHistory, setShowingHistory] = useState(false);\n const [tempInput, setTempInput] = useState(''); // Store current input when navigating history\n\n // Commands state\n const commands = barOptions.commands ?? [];\n const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);\n\n // Built-in history command\n const historyCommand: AICommandBarCommand = useMemo(() => ({\n keyword: 'history',\n description: 'Show command history',\n message: '', // Special handling\n }), []);\n\n // All available commands (user commands + built-in)\n const allCommands = useMemo(() => {\n const userCommands = commands;\n // Add history command if enabled and not overwritten\n if (showHistoryCommand && !userCommands.some(c => c.keyword === 'history')) {\n return [...userCommands, historyCommand];\n }\n return userCommands;\n }, [commands, showHistoryCommand, historyCommand]);\n\n // Detect if showing command suggestions\n const isCommandMode = inputValue.startsWith('/');\n const commandQuery = isCommandMode ? inputValue.slice(1).toLowerCase() : '';\n const showingCommands = isCommandMode && !isProcessing && !result;\n\n // Filter commands based on query\n const filteredCommands = useMemo(() => {\n if (!showingCommands) return [];\n if (commandQuery === '') return allCommands;\n return allCommands.filter(cmd =>\n cmd.keyword.toLowerCase().includes(commandQuery) ||\n cmd.description.toLowerCase().includes(commandQuery)\n );\n }, [showingCommands, commandQuery, allCommands]);\n\n // Reset command selection when filtered list changes\n useEffect(() => {\n setSelectedCommandIndex(0);\n }, [filteredCommands.length]);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onToolCallRef = useRef(onToolCall);\n const onSubmitRef = useRef(onSubmit);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onToolCallRef.current = onToolCall;\n onSubmitRef.current = onSubmit;\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 onToolExecute: onToolCall,\n });\n\n // Visibility controls\n const open = useCallback(() => {\n setInternalVisible(true);\n onVisibilityChange?.(true);\n onOpenRef.current?.();\n // Focus input after visibility change\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [onVisibilityChange]);\n\n const close = useCallback(() => {\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n }, [onVisibilityChange]);\n\n const toggle = useCallback(() => {\n if (isVisible) {\n close();\n } else {\n open();\n }\n }, [isVisible, open, close]);\n\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Save history to localStorage\n const saveHistory = useCallback((newHistory: string[]) => {\n if (!enableHistory || typeof window === 'undefined') return;\n try {\n localStorage.setItem(historyStorageKey, JSON.stringify(newHistory));\n } catch {\n // Ignore localStorage errors\n }\n }, [enableHistory, historyStorageKey]);\n\n // Add item to history\n const addToHistory = useCallback((message: string) => {\n if (!enableHistory || !message.trim() || message.startsWith('/')) return;\n\n setHistory(prev => {\n // Don't add duplicates at the top\n const filtered = prev.filter(item => item !== message);\n const newHistory = [message, ...filtered].slice(0, maxHistoryItems);\n saveHistory(newHistory);\n return newHistory;\n });\n setHistoryIndex(-1);\n }, [enableHistory, maxHistoryItems, saveHistory]);\n\n // Clear history\n const clearHistory = useCallback(() => {\n setHistory([]);\n setHistoryIndex(-1);\n if (enableHistory && typeof window !== 'undefined') {\n try {\n localStorage.removeItem(historyStorageKey);\n } catch {\n // Ignore\n }\n }\n }, [enableHistory, historyStorageKey]);\n\n // Navigate history\n const navigateHistory = useCallback((direction: 'up' | 'down') => {\n if (!enableHistory || history.length === 0) return;\n\n if (direction === 'up') {\n if (historyIndex === -1) {\n // Save current input before navigating\n setTempInput(inputValue);\n setHistoryIndex(0);\n setInputValue(history[0]);\n } else if (historyIndex < history.length - 1) {\n const newIndex = historyIndex + 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n }\n } else {\n if (historyIndex > 0) {\n const newIndex = historyIndex - 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n } else if (historyIndex === 0) {\n setHistoryIndex(-1);\n setInputValue(tempInput);\n }\n }\n }, [enableHistory, history, historyIndex, inputValue, tempInput]);\n\n // Ref to hold submit function (to avoid circular dependency)\n const submitRef = useRef<(message?: string) => Promise<void>>();\n\n // Select a command\n const selectCommand = useCallback((command: AICommandBarCommand) => {\n if (command.keyword === 'history') {\n // Special handling for history command\n setShowingHistory(true);\n setInputValue('');\n } else {\n // Send the command's message\n setInputValue('');\n submitRef.current?.(command.message);\n }\n }, []);\n\n // Navigate commands\n const navigateCommands = useCallback((direction: 'up' | 'down') => {\n if (filteredCommands.length === 0) return;\n\n if (direction === 'down') {\n setSelectedCommandIndex(prev =>\n prev < filteredCommands.length - 1 ? prev + 1 : 0\n );\n } else {\n setSelectedCommandIndex(prev =>\n prev > 0 ? prev - 1 : filteredCommands.length - 1\n );\n }\n }, [filteredCommands.length]);\n\n // Register keyboard shortcut\n useEffect(() => {\n if (!shortcut) return;\n\n const handler = (e: KeyboardEvent) => {\n if (matchShortcut(e, shortcut)) {\n e.preventDefault();\n toggle();\n }\n };\n\n window.addEventListener('keydown', handler);\n return () => window.removeEventListener('keydown', handler);\n }, [shortcut, toggle]);\n\n // Process tool calls from realtime data\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\n // Prefer showing an executing tool, but fall back to the last tool (completed or not)\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 return;\n }\n\n if (data?.status === 'completed') {\n setIsProcessing(false);\n\n // Extract final assistant message\n const assistantMessages = data.chatHistory.filter(m => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const commandResult: CommandBarResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: processToolCalls(data.chatHistory),\n };\n\n setResult(commandResult);\n\n // Handle execution mode\n if (onExecute === 'openDrawer' && chatDrawerRef?.current) {\n chatDrawerRef.current.setChatUid(chatUid);\n chatDrawerRef.current.open();\n // Close and reset the command bar when handing off to drawer\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n } else {\n onResponseRef.current?.(commandResult);\n }\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n // Submit message\n const submit = useCallback(\n async (message?: string) => {\n const msg = message ?? inputValue;\n if (!msg.trim()) 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\n // Add to history before processing\n addToHistory(msg);\n\n // Clear input and start processing\n setInputValue('');\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setShowingHistory(false);\n setHistoryIndex(-1);\n\n onSubmitRef.current?.(msg);\n\n try {\n const dto = {\n message: msg,\n chatUid: chatUid || undefined,\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 && response.chatUid !== chatUid) {\n setChatUid(response.chatUid);\n }\n\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 [inputValue, chatUid, assistantId, resolvedTenantId, resolvedTenantMetadata, toolSchemas, addToHistory]\n );\n\n // Update submit ref for use in selectCommand\n submitRef.current = submit;\n\n // Reset state\n const reset = useCallback(() => {\n setInputValue('');\n setIsProcessing(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setResult(null);\n setChatUid(null);\n setError(null);\n setShouldPoll(false);\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 if (showingHistory) {\n setShowingHistory(false);\n return;\n }\n if (showingCommands) {\n setInputValue('');\n return;\n }\n // Reset if there's a result or if processing\n if (result || isProcessing) {\n reset();\n }\n close();\n return;\n }\n\n // Handle arrow keys for commands\n if (showingCommands && filteredCommands.length > 0) {\n if (e.key === 'ArrowDown') {\n e.preventDefault();\n navigateCommands('down');\n return;\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateCommands('up');\n return;\n }\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n selectCommand(selectedCommand);\n }\n return;\n }\n if (e.key === 'Tab') {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n setInputValue('/' + selectedCommand.keyword + ' ');\n }\n return;\n }\n }\n\n // Handle arrow keys for history (only when not in command mode)\n if (!showingCommands && !isProcessing) {\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateHistory('up');\n return;\n }\n if (e.key === 'ArrowDown' && historyIndex >= 0) {\n e.preventDefault();\n navigateHistory('down');\n return;\n }\n }\n\n // Handle Enter to submit\n if (e.key === 'Enter' && !e.shiftKey && !isProcessing) {\n e.preventDefault();\n submit();\n }\n },\n [\n isProcessing,\n result,\n showingCommands,\n showingHistory,\n filteredCommands,\n selectedCommandIndex,\n historyIndex,\n submit,\n reset,\n close,\n navigateCommands,\n navigateHistory,\n selectCommand,\n ]\n );\n\n return {\n isVisible,\n open,\n close,\n toggle,\n inputValue,\n setInputValue,\n inputRef,\n focus,\n isProcessing,\n toolCalls,\n currentToolSummary,\n result,\n chatUid,\n error,\n history,\n historyIndex,\n showingHistory,\n setShowingHistory,\n showingCommands,\n filteredCommands,\n selectedCommandIndex,\n selectCommand,\n submit,\n reset,\n handleKeyDown,\n clearHistory,\n };\n}\n"],"names":["useOptionalDevicContext","useState","useRef","useMemo","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;AAgFA;;AAEG;AACH,SAAS,aAAa,CAAC,QAAgB,EAAA;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IAC/C,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE;IAC7B,MAAM,SAAS,GAAG,KAAK;AACvB,IAAA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE;AAC3B;AAEA;;AAEG;AACH,SAAS,aAAa,CAAC,KAAoB,EAAE,QAAgB,EAAA;IAC3D,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,aAAa,CAAC,QAAQ,CAAC;IAElD,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,GAAG;AAChD,IAAA,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC;AAC/E,IAAA,MAAM,UAAU,GAAG,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,KAAK,CAAC,QAAQ;AACjE,IAAA,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC,MAAM;AAE3D,IAAA,OAAO,QAAQ,IAAI,QAAQ,IAAI,UAAU,IAAI,QAAQ;AACvD;AAEA;;AAEG;AACG,SAAU,cAAc,CAAC,QAAgB,EAAA;AAC7C,IAAA,MAAM,KAAK,GAAG,OAAO,SAAS,KAAK,WAAW,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;AAChF,IAAA,OAAO;AACJ,SAAA,OAAO,CAAC,OAAO,EAAE,KAAK,GAAG,QAAQ,GA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,EAAE;YACrD,CAAC,CAAC,cAAc,EAAE;AAClB,YAAA,MAAM,EAAE;QACV;AACF,IAAA,CAAC,EACD;QACE,YAAY;QACZ,MAAM;QACN,eAAe;QACf,cAAc;QACd,gBAAgB;QAChB,oBAAoB;QACpB,YAAY;QACZ,MAAM;QACN,KAAK;QACL,KAAK;QACL,gBAAgB;QAChB,eAAe;QACf,aAAa;AACd,KAAA,CACF;IAED,OAAO;QACL,SAAS;QACT,IAAI;QACJ,KAAK;QACL,MAAM;QACN,UAAU;QACV,aAAa;QACb,QAAQ;QACR,KAAK;QACL,YAAY;QACZ,SAAS;QACT,kBAAkB;QAClB,MAAM;QACN,OAAO;QACP,KAAK;QACL,OAAO;QACP,YAAY;QACZ,cAAc;QACd,iBAAiB;QACjB,eAAe;QACf,gBAAgB;QAChB,oBAAoB;QACpB,aAAa;QACb,MAAM;QACN,KAAK;QACL,aAAa;QACb,YAAY;KACb;AACH;;;;;"}
@@ -0,0 +1,334 @@
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('react/jsx-runtime');
4
+ var React = require('react');
5
+ var reactDom = require('react-dom');
6
+ var DevicContext = require('../../provider/DevicContext.js');
7
+ var index = require('../../utils/index.js');
8
+ var useAIElementWrapper = require('./useAIElementWrapper.js');
9
+ var activeWrapperRegistry = require('./activeWrapperRegistry.js');
10
+
11
+ const DEFAULT_OPTIONS = {
12
+ showOn: 'hover',
13
+ triggerPlacement: 'bottom',
14
+ tooltipPlacement: 'bottom',
15
+ tooltipWidth: 360,
16
+ triggerLabel: 'Preguntar a IA',
17
+ highlightOnInteract: true,
18
+ zIndex: 2147483000,
19
+ triggerBorderRadius: 999,
20
+ color: undefined,
21
+ drawerPromptPrefix: undefined,
22
+ defaultInlinePrompt: undefined,
23
+ };
24
+ function rectFromDom(rect) {
25
+ return { top: rect.top, left: rect.left, width: rect.width, height: rect.height };
26
+ }
27
+ function placementStyle(placement, anchor, offset = 8) {
28
+ const cx = anchor.left + anchor.width / 2;
29
+ const cy = anchor.top + anchor.height / 2;
30
+ switch (placement) {
31
+ case 'top':
32
+ return { position: 'fixed', top: anchor.top - offset, left: cx, transform: 'translate(-50%, -100%)' };
33
+ case 'bottom':
34
+ return { position: 'fixed', top: anchor.top + anchor.height + offset, left: cx, transform: 'translateX(-50%)' };
35
+ case 'left':
36
+ return { position: 'fixed', top: cy, left: anchor.left - offset, transform: 'translate(-100%, -50%)' };
37
+ case 'right':
38
+ return { position: 'fixed', top: cy, left: anchor.left + anchor.width + offset, transform: 'translateY(-50%)' };
39
+ }
40
+ }
41
+ /**
42
+ * AIElementWrapper wraps an arbitrary React node and exposes an AI trigger
43
+ * that can either show an inline floating tooltip with the assistant's
44
+ * answer (`behavior='inline'`) or push a reference to the registered
45
+ * ChatDrawer (`behavior='drawer'`).
46
+ *
47
+ * The trigger and inline tooltip are rendered through a React portal anchored
48
+ * to the wrapped element, so they always sit above other UI (including the
49
+ * ChatDrawer) regardless of stacking context.
50
+ */
51
+ const AIElementWrapper = React.forwardRef(function AIElementWrapper(props, ref) {
52
+ const { label, data, referenceContent, behavior = 'inline', trigger, options = {}, assistantId, getPrompt, apiKey, baseUrl, tenantId, tenantMetadata, modelInterfaceTools, inlineRenderer, onActivate, onInlineResponse, onError, className, style, children, } = props;
53
+ const merged = React.useMemo(() => ({ ...DEFAULT_OPTIONS, ...options }), [options]);
54
+ // Stable instance ID used by the active-wrapper registry (singleton)
55
+ const wrapperIdRef = React.useRef('');
56
+ if (!wrapperIdRef.current)
57
+ wrapperIdRef.current = index.generateId();
58
+ const [activeWrapperId, setActiveWrapperLocal] = React.useState(activeWrapperRegistry.getActiveWrapper());
59
+ React.useEffect(() => activeWrapperRegistry.subscribeActiveWrapper(setActiveWrapperLocal), []);
60
+ const context = DevicContext.useOptionalDevicContext();
61
+ const containerRef = React.useRef(null);
62
+ const tooltipRef = React.useRef(null);
63
+ const triggerRef = React.useRef(null);
64
+ const [isHovered, setIsHovered] = React.useState(false);
65
+ const hoverTimerRef = React.useRef(null);
66
+ const setHoveredImmediately = React.useCallback((v) => {
67
+ if (hoverTimerRef.current) {
68
+ clearTimeout(hoverTimerRef.current);
69
+ hoverTimerRef.current = null;
70
+ }
71
+ if (v) {
72
+ setIsHovered(true);
73
+ }
74
+ else {
75
+ // Grace period so the cursor can travel from the wrapper to the
76
+ // portal-rendered trigger without the trigger disappearing mid-flight.
77
+ hoverTimerRef.current = setTimeout(() => setIsHovered(false), 200);
78
+ }
79
+ }, []);
80
+ React.useEffect(() => () => {
81
+ if (hoverTimerRef.current)
82
+ clearTimeout(hoverTimerRef.current);
83
+ }, []);
84
+ const [isInlineOpen, setIsInlineOpen] = React.useState(false);
85
+ const [containerRect, setContainerRect] = React.useState(null);
86
+ const [selectionRect, setSelectionRect] = React.useState(null);
87
+ const inline = useAIElementWrapper.useAIElementWrapper({
88
+ assistantId,
89
+ apiKey,
90
+ baseUrl,
91
+ tenantId,
92
+ tenantMetadata,
93
+ modelInterfaceTools,
94
+ onResponse: onInlineResponse,
95
+ onError,
96
+ });
97
+ // What this wrapper would show if there were no coordination.
98
+ const wantsTriggerVisible = merged.showOn === 'always' ||
99
+ (merged.showOn === 'hover' && isHovered) ||
100
+ (merged.showOn === 'click' && isInlineOpen) ||
101
+ (merged.showOn === 'select' && selectionRect !== null);
102
+ // Coordinate via the singleton registry so only one wrapper shows the
103
+ // floating trigger at a time. The most recent wrapper to want visibility
104
+ // wins; others hide until they are activated again.
105
+ const isActive = activeWrapperId === wrapperIdRef.current;
106
+ const triggerVisible = wantsTriggerVisible && (activeWrapperId === null || isActive);
107
+ React.useEffect(() => {
108
+ const id = wrapperIdRef.current;
109
+ if (wantsTriggerVisible) {
110
+ activeWrapperRegistry.setActiveWrapper(id);
111
+ }
112
+ else if (activeWrapperRegistry.getActiveWrapper() === id) {
113
+ activeWrapperRegistry.setActiveWrapper(null);
114
+ }
115
+ }, [wantsTriggerVisible]);
116
+ // Release the registry slot if the component unmounts while active.
117
+ React.useEffect(() => () => {
118
+ if (activeWrapperRegistry.getActiveWrapper() === wrapperIdRef.current) {
119
+ activeWrapperRegistry.setActiveWrapper(null);
120
+ }
121
+ }, []);
122
+ // Track container rect (for hover/click/always trigger and tooltip anchor)
123
+ const updateContainerRect = React.useCallback(() => {
124
+ const el = containerRef.current;
125
+ if (!el)
126
+ return;
127
+ setContainerRect(rectFromDom(el.getBoundingClientRect()));
128
+ }, []);
129
+ React.useLayoutEffect(() => {
130
+ if (!triggerVisible && !isInlineOpen)
131
+ return;
132
+ updateContainerRect();
133
+ const onScrollOrResize = () => updateContainerRect();
134
+ window.addEventListener('scroll', onScrollOrResize, true);
135
+ window.addEventListener('resize', onScrollOrResize);
136
+ return () => {
137
+ window.removeEventListener('scroll', onScrollOrResize, true);
138
+ window.removeEventListener('resize', onScrollOrResize);
139
+ };
140
+ }, [triggerVisible, isInlineOpen, updateContainerRect]);
141
+ // selectionchange listener for showOn='select'
142
+ React.useEffect(() => {
143
+ if (merged.showOn !== 'select') {
144
+ setSelectionRect(null);
145
+ return;
146
+ }
147
+ const isInside = (node, cont) => {
148
+ if (!node)
149
+ return false;
150
+ if (node === cont)
151
+ return true;
152
+ return cont.contains(node);
153
+ };
154
+ const recompute = () => {
155
+ const sel = window.getSelection();
156
+ const cont = containerRef.current;
157
+ if (!sel || sel.isCollapsed || !cont || sel.rangeCount === 0) {
158
+ setSelectionRect(null);
159
+ return;
160
+ }
161
+ // Don't react to selections happening elsewhere — but tolerate the
162
+ // case where anchor or focus are inside our container.
163
+ if (!isInside(sel.anchorNode, cont) && !isInside(sel.focusNode, cont)) {
164
+ setSelectionRect(null);
165
+ return;
166
+ }
167
+ const range = sel.getRangeAt(0);
168
+ const rect = range.getBoundingClientRect();
169
+ if (rect.width === 0 && rect.height === 0) {
170
+ setSelectionRect(null);
171
+ return;
172
+ }
173
+ setSelectionRect(rectFromDom(rect));
174
+ };
175
+ const onMouseUp = () => {
176
+ // Run on next tick so the browser commits the final selection state.
177
+ setTimeout(recompute, 0);
178
+ };
179
+ document.addEventListener('selectionchange', recompute);
180
+ document.addEventListener('mouseup', onMouseUp);
181
+ return () => {
182
+ document.removeEventListener('selectionchange', recompute);
183
+ document.removeEventListener('mouseup', onMouseUp);
184
+ };
185
+ }, [merged.showOn]);
186
+ const buildPrompt = React.useCallback(() => {
187
+ if (getPrompt)
188
+ return getPrompt({ data, label });
189
+ if (merged.defaultInlinePrompt)
190
+ return merged.defaultInlinePrompt;
191
+ // Use selected text if available, otherwise fall back to label
192
+ if (merged.showOn === 'select') {
193
+ const sel = window.getSelection();
194
+ const txt = sel?.toString().trim();
195
+ if (txt)
196
+ return `Cuéntame más sobre: "${txt}"`;
197
+ }
198
+ return `Cuéntame más sobre: ${label}`;
199
+ }, [getPrompt, data, label, merged.defaultInlinePrompt, merged.showOn]);
200
+ const handleActivate = React.useCallback(() => {
201
+ onActivate?.();
202
+ if (behavior === 'inline') {
203
+ if (!assistantId) {
204
+ const err = new Error('assistantId is required for behavior="inline"');
205
+ onError?.(err);
206
+ // eslint-disable-next-line no-console
207
+ console.warn('[AIElementWrapper]', err.message);
208
+ return;
209
+ }
210
+ setIsInlineOpen(true);
211
+ inline.reset();
212
+ inline.sendInlinePrompt(buildPrompt());
213
+ return;
214
+ }
215
+ // drawer behavior
216
+ if (!context) {
217
+ // eslint-disable-next-line no-console
218
+ console.warn('[AIElementWrapper] behavior="drawer" requires a DevicProvider ancestor.');
219
+ return;
220
+ }
221
+ // For 'select' showOn, prefer selected text as label content fallback
222
+ let finalLabel = label;
223
+ if (merged.showOn === 'select') {
224
+ const txt = window.getSelection()?.toString().trim();
225
+ if (txt)
226
+ finalLabel = txt;
227
+ }
228
+ context.addReference({ label: finalLabel, content: referenceContent, data });
229
+ context.openDrawer();
230
+ }, [
231
+ onActivate,
232
+ behavior,
233
+ assistantId,
234
+ onError,
235
+ inline,
236
+ buildPrompt,
237
+ context,
238
+ label,
239
+ referenceContent,
240
+ data,
241
+ merged.showOn,
242
+ ]);
243
+ const closeInline = React.useCallback(() => {
244
+ setIsInlineOpen(false);
245
+ inline.reset();
246
+ }, [inline]);
247
+ React.useImperativeHandle(ref, () => ({
248
+ activate: handleActivate,
249
+ close: closeInline,
250
+ }), [handleActivate, closeInline]);
251
+ // Click outside to close inline tooltip
252
+ React.useEffect(() => {
253
+ if (!isInlineOpen)
254
+ return;
255
+ const handler = (e) => {
256
+ const t = tooltipRef.current;
257
+ const c = containerRef.current;
258
+ const tr = triggerRef.current;
259
+ const target = e.target;
260
+ if (t && !t.contains(target) &&
261
+ c && !c.contains(target) &&
262
+ (!tr || !tr.contains(target))) {
263
+ closeInline();
264
+ }
265
+ };
266
+ document.addEventListener('mousedown', handler);
267
+ return () => document.removeEventListener('mousedown', handler);
268
+ }, [isInlineOpen, closeInline]);
269
+ // Anchor for trigger: selection rect (when showOn='select') else container rect
270
+ const triggerAnchor = merged.showOn === 'select' ? selectionRect : containerRect;
271
+ // Tooltip anchor: container rect (or selection if select mode)
272
+ const tooltipAnchor = merged.showOn === 'select' && selectionRect ? selectionRect : containerRect;
273
+ const triggerStyle = React.useMemo(() => {
274
+ if (!triggerAnchor)
275
+ return { display: 'none' };
276
+ return {
277
+ ...placementStyle(merged.triggerPlacement, triggerAnchor),
278
+ zIndex: merged.zIndex + 1,
279
+ pointerEvents: 'auto',
280
+ };
281
+ }, [triggerAnchor, merged.triggerPlacement, merged.zIndex]);
282
+ const tooltipStyle = React.useMemo(() => {
283
+ const w = typeof merged.tooltipWidth === 'number' ? `${merged.tooltipWidth}px` : merged.tooltipWidth;
284
+ if (!tooltipAnchor)
285
+ return { display: 'none' };
286
+ return {
287
+ ...placementStyle(merged.tooltipPlacement, tooltipAnchor),
288
+ width: w,
289
+ zIndex: merged.zIndex,
290
+ };
291
+ }, [tooltipAnchor, merged.tooltipPlacement, merged.tooltipWidth, merged.zIndex]);
292
+ const renderInlineContent = () => {
293
+ if (inline.error) {
294
+ return jsxRuntime.jsx("div", { className: "devic-aiwrap-error", children: inline.error.message });
295
+ }
296
+ if (inline.isProcessing) {
297
+ return (jsxRuntime.jsxs("div", { className: "devic-aiwrap-processing", children: [jsxRuntime.jsx("span", { className: "devic-aiwrap-spinner", "aria-hidden": "true" }), jsxRuntime.jsx("span", { children: "Pensando\u2026" })] }));
298
+ }
299
+ if (inline.response) {
300
+ if (inlineRenderer)
301
+ return inlineRenderer(inline.response);
302
+ const text = typeof inline.response.content === 'string'
303
+ ? inline.response.content
304
+ : inline.response.content?.message || '';
305
+ return jsxRuntime.jsx("div", { className: "devic-aiwrap-answer", children: text });
306
+ }
307
+ return null;
308
+ };
309
+ const triggerNode = trigger ?? (jsxRuntime.jsxs("button", { type: "button", className: "devic-aiwrap-trigger", style: {
310
+ borderRadius: typeof merged.triggerBorderRadius === 'number'
311
+ ? `${merged.triggerBorderRadius}px`
312
+ : merged.triggerBorderRadius,
313
+ ...(merged.color ? { ['--devic-aiwrap-color']: merged.color } : {}),
314
+ }, children: [jsxRuntime.jsx("span", { className: "devic-aiwrap-trigger-icon", "aria-hidden": "true", children: jsxRuntime.jsx(SparklesIcon, {}) }), jsxRuntime.jsx("span", { className: "devic-aiwrap-trigger-label", children: merged.triggerLabel })] }));
315
+ const portalTarget = typeof document !== 'undefined' ? document.body : null;
316
+ return (jsxRuntime.jsxs("span", { ref: containerRef, className: `devic-aiwrap-container ${className || ''}`, style: { position: 'relative', display: 'inline-block', ...style }, "data-highlight": merged.highlightOnInteract && (isHovered || isInlineOpen) ? 'true' : 'false', onMouseEnter: () => setHoveredImmediately(true), onMouseLeave: () => setHoveredImmediately(false), children: [jsxRuntime.jsx("span", { className: "devic-aiwrap-content", children: children }), portalTarget && triggerVisible &&
317
+ reactDom.createPortal(jsxRuntime.jsx("div", { ref: triggerRef, className: "devic-aiwrap-trigger-wrapper", style: triggerStyle, onMouseEnter: () => setHoveredImmediately(true), onMouseLeave: () => setHoveredImmediately(false), onMouseDown: (e) => {
318
+ // Prevent losing the text selection when interacting with trigger
319
+ e.preventDefault();
320
+ }, onClick: (e) => {
321
+ e.stopPropagation();
322
+ handleActivate();
323
+ }, children: triggerNode }), portalTarget), portalTarget && behavior === 'inline' && isInlineOpen &&
324
+ reactDom.createPortal(jsxRuntime.jsxs("div", { ref: tooltipRef, className: "devic-aiwrap-tooltip", style: tooltipStyle, "data-placement": merged.tooltipPlacement, children: [jsxRuntime.jsxs("div", { className: "devic-aiwrap-tooltip-header", children: [jsxRuntime.jsx("span", { className: "devic-aiwrap-tooltip-label", children: label }), jsxRuntime.jsx("button", { type: "button", className: "devic-aiwrap-tooltip-close", onClick: closeInline, "aria-label": "Cerrar", children: jsxRuntime.jsx(CloseIcon, {}) })] }), jsxRuntime.jsx("div", { className: "devic-aiwrap-tooltip-body", children: renderInlineContent() })] }), portalTarget)] }));
325
+ });
326
+ function SparklesIcon() {
327
+ return (jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", xmlns: "http://www.w3.org/2000/svg", children: [jsxRuntime.jsx("path", { d: "M10 2L11.5 8.5L18 10L11.5 11.5L10 18L8.5 11.5L2 10L8.5 8.5L10 2Z", opacity: "0.95" }), jsxRuntime.jsx("path", { d: "M16 3L16.5 5L18.5 5.5L16.5 6L16 8L15.5 6L13.5 5.5L15.5 5L16 3Z", opacity: "0.6" })] }));
328
+ }
329
+ function CloseIcon() {
330
+ return (jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [jsxRuntime.jsx("line", { x1: "18", y1: "6", x2: "6", y2: "18" }), jsxRuntime.jsx("line", { x1: "6", y1: "6", x2: "18", y2: "18" })] }));
331
+ }
332
+
333
+ exports.AIElementWrapper = AIElementWrapper;
334
+ //# sourceMappingURL=AIElementWrapper.js.map