@decido/shell 1.0.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 (208) hide show
  1. package/.turbo/turbo-build.log +13 -0
  2. package/package.json +65 -0
  3. package/src/AgentPlayer.tsx +105 -0
  4. package/src/DecidoPlayer.tsx +117 -0
  5. package/src/bridge/BridgeAgent.ts +443 -0
  6. package/src/components/DecidoIcon.tsx +56 -0
  7. package/src/components/JsonTreeEditor.tsx +117 -0
  8. package/src/components/PanelSplitter.tsx +71 -0
  9. package/src/components/PluginErrorBoundary.tsx +69 -0
  10. package/src/components/SafeLiquidUI.tsx +114 -0
  11. package/src/components/TransientLayer.tsx +92 -0
  12. package/src/components/agent/AgentChat.tsx +134 -0
  13. package/src/components/chat-extensions/IntentCatalogPanel.tsx +81 -0
  14. package/src/components/chat-extensions/chatSlashCommands.ts +101 -0
  15. package/src/components/controls/CreatorInputBar.tsx +144 -0
  16. package/src/components/controls/OSToolbar.tsx +90 -0
  17. package/src/components/controls/TimelineTape.tsx +43 -0
  18. package/src/components/debug/ActionTimelineTab.tsx +111 -0
  19. package/src/components/debug/CSSInspectorTab.tsx +436 -0
  20. package/src/components/debug/ExportTab.tsx +192 -0
  21. package/src/components/debug/FlowHealthTab.tsx +86 -0
  22. package/src/components/debug/LogsTab.tsx +110 -0
  23. package/src/components/debug/MorphStackTab.tsx +241 -0
  24. package/src/components/debug/NetworkTab.tsx +173 -0
  25. package/src/components/debug/PerformanceTab.tsx +171 -0
  26. package/src/components/debug/ProfilesTab.tsx +238 -0
  27. package/src/components/debug/ReplayTab.tsx +70 -0
  28. package/src/components/debug/StoresTab.tsx +255 -0
  29. package/src/components/debug/TopologyTab.tsx +59 -0
  30. package/src/components/debug/debugConfig.tsx +66 -0
  31. package/src/components/playground/DebugPanel.tsx +112 -0
  32. package/src/components/playground/HeaderCenterControls.tsx +92 -0
  33. package/src/components/playground/KeyframeListItem.tsx +70 -0
  34. package/src/components/playground/PlaygroundAppSidebar.tsx +171 -0
  35. package/src/components/playground/PlaygroundBottomControls.tsx +132 -0
  36. package/src/components/playground/PlaygroundCanvas.tsx +87 -0
  37. package/src/components/playground/PlaygroundChat.tsx +236 -0
  38. package/src/components/playground/PlaygroundErrorBoundary.tsx +63 -0
  39. package/src/components/playground/PlaygroundFloatingInput.tsx +352 -0
  40. package/src/components/playground/PlaygroundHeader.tsx +222 -0
  41. package/src/components/playground/PlaygroundSidebar.tsx +136 -0
  42. package/src/components/playground/PlaygroundTerminal.tsx +44 -0
  43. package/src/components/playground/SuggestionCards.tsx +29 -0
  44. package/src/components/playground/demos/ClinicaAINode.tsx +221 -0
  45. package/src/components/playground/demos/FinanceAINode.tsx +226 -0
  46. package/src/components/playground/demos/KiaAcademyNode.tsx +250 -0
  47. package/src/components/playground/demos/KiaBotNode.tsx +207 -0
  48. package/src/components/playground/demos/KiaCampaignNode.tsx +191 -0
  49. package/src/components/playground/demos/KiaComplianceNode.tsx +140 -0
  50. package/src/components/playground/demos/KiaCustomerJourneyNode.tsx +220 -0
  51. package/src/components/playground/demos/KiaCyberNode.tsx +203 -0
  52. package/src/components/playground/demos/KiaDashboardNode.tsx +399 -0
  53. package/src/components/playground/demos/KiaEmbudoOverviewNode.tsx +168 -0
  54. package/src/components/playground/demos/KiaExecutiveNode.tsx +169 -0
  55. package/src/components/playground/demos/KiaGamificationNode.tsx +229 -0
  56. package/src/components/playground/demos/KiaIntelligenceHubNode.tsx +165 -0
  57. package/src/components/playground/demos/KiaInventoryNode.tsx +183 -0
  58. package/src/components/playground/demos/KiaLeadScoringNode.tsx +226 -0
  59. package/src/components/playground/demos/KiaLiveSimulationNode.tsx +177 -0
  60. package/src/components/playground/demos/KiaMultiDealerNode.tsx +223 -0
  61. package/src/components/playground/demos/KiaNPSVoiceNode.tsx +214 -0
  62. package/src/components/playground/demos/KiaOmnichannelNode.tsx +162 -0
  63. package/src/components/playground/demos/KiaPBIBudgetNode.tsx +152 -0
  64. package/src/components/playground/demos/KiaPBIConversionNode.tsx +206 -0
  65. package/src/components/playground/demos/KiaPBIFunnelNode.tsx +184 -0
  66. package/src/components/playground/demos/KiaPBIOwnershipNode.tsx +113 -0
  67. package/src/components/playground/demos/KiaPBIPartnerNode.tsx +143 -0
  68. package/src/components/playground/demos/KiaPBIPreciosNode.tsx +120 -0
  69. package/src/components/playground/demos/KiaPBIRuntNode.tsx +205 -0
  70. package/src/components/playground/demos/KiaPartnerScoreNode.tsx +206 -0
  71. package/src/components/playground/demos/KiaPredictiveNode.tsx +226 -0
  72. package/src/components/playground/demos/KiaShowroomNode.tsx +194 -0
  73. package/src/components/playground/demos/KiaStoreNode.tsx +215 -0
  74. package/src/components/playground/demos/KiaSustainabilityNode.tsx +173 -0
  75. package/src/components/playground/demos/KiaUsedVehiclesNode.tsx +163 -0
  76. package/src/components/playground/demos/KiaWorkshopNode.tsx +221 -0
  77. package/src/components/playground/demos/SmartCityNode.tsx +205 -0
  78. package/src/components/playground/demos/kia_campaign_manifest.json +112 -0
  79. package/src/components/playground/input-parts/AIModelSelector.tsx +156 -0
  80. package/src/components/playground/input-parts/InputActions.tsx +80 -0
  81. package/src/components/playground/input-parts/InputToolbar.tsx +245 -0
  82. package/src/components/playground/input-parts/ResourceLibraryPanel.tsx +287 -0
  83. package/src/components/playground/sidebarDsdIO.ts +82 -0
  84. package/src/components/settings/SettingsPanel.tsx +267 -0
  85. package/src/components/shell/AppHeader.tsx +9 -0
  86. package/src/components/shell/AppShell.tsx +139 -0
  87. package/src/components/shell/ArtifactBar.tsx +97 -0
  88. package/src/components/shell/BootScreen.tsx +19 -0
  89. package/src/components/shell/CenterComposite.tsx +87 -0
  90. package/src/components/shell/CodeEditorPanel.tsx +88 -0
  91. package/src/components/shell/GlobalOverlays.tsx +228 -0
  92. package/src/components/shell/LayoutConfigurator.tsx +209 -0
  93. package/src/components/shell/LayoutGrid.tsx +178 -0
  94. package/src/components/shell/MorphShell.tsx +368 -0
  95. package/src/components/shell/PluginViewer.tsx +147 -0
  96. package/src/components/shell/ShellNexusPreview.tsx +458 -0
  97. package/src/components/shell/SlotRenderer.tsx +115 -0
  98. package/src/components/shell/TabBar.tsx +94 -0
  99. package/src/components/shell/TemplateLibrary.tsx +195 -0
  100. package/src/components/shell/layoutConstants.ts +35 -0
  101. package/src/components/shell/morphStageMeta.ts +15 -0
  102. package/src/components/shell/shells/BuiltInShells.tsx +443 -0
  103. package/src/components/shell/shells/DatawayChatShell.tsx +42 -0
  104. package/src/components/shell/shells/TokenPreview.tsx +339 -0
  105. package/src/components/shell/shells/bootShells.ts +31 -0
  106. package/src/components/shells/CreatorShell.tsx +37 -0
  107. package/src/components/shells/DecidoShell.tsx +447 -0
  108. package/src/components/shells/ExperimentalChatShell.tsx +245 -0
  109. package/src/components/shells/UserCanvas.tsx +44 -0
  110. package/src/components/studio/BlueprintManagerPanel.tsx +137 -0
  111. package/src/components/studio/DependencyTreePanel.tsx +192 -0
  112. package/src/components/studio/NodePalette.tsx +92 -0
  113. package/src/components/studio/NodePropertiesPanel.tsx +81 -0
  114. package/src/components/studio/ReactFlowEditor.tsx +242 -0
  115. package/src/components/studio/TimelineEditor.tsx +122 -0
  116. package/src/components/studio/TimelineKeyframeCard.tsx +99 -0
  117. package/src/components/studio/VariablePanel.tsx +181 -0
  118. package/src/components/studio/blueprint/BlueprintCard.tsx +82 -0
  119. package/src/components/studio/editor/CanvasContextMenu.tsx +107 -0
  120. package/src/components/studio/editor/EditorToolbar.tsx +80 -0
  121. package/src/components/studio/editor/StageContentRenderer.tsx +134 -0
  122. package/src/components/studio/editor/TrackPropertyEditors.tsx +133 -0
  123. package/src/components/studio/editor/TreeNodeItem.tsx +91 -0
  124. package/src/components/studio/editor/edgeStyles.ts +43 -0
  125. package/src/components/studio/editor/editorKeyHandler.ts +95 -0
  126. package/src/components/studio/editor/nodeTypeRegistry.ts +137 -0
  127. package/src/components/studio/editor/paletteCatalog.tsx +84 -0
  128. package/src/components/studio/nodes/shell/InteractionNodes.tsx +82 -0
  129. package/src/components/studio/nodes/shell/LayoutControlNodes.tsx +69 -0
  130. package/src/components/studio/nodes/shell/RegisterActionNode.tsx +20 -0
  131. package/src/components/studio/nodes/shell/RegisterButtonNode.tsx +22 -0
  132. package/src/components/studio/nodes/shell/RegisterPanelNode.tsx +19 -0
  133. package/src/components/studio/nodes/shell/RegisterSidebarNode.tsx +19 -0
  134. package/src/components/studio/nodes/shell/RegisterStatusBarNode.tsx +22 -0
  135. package/src/components/studio/nodes/shell/RegisterTabNode.tsx +21 -0
  136. package/src/components/studio/nodes/shell/RegisterTopBarNode.tsx +22 -0
  137. package/src/components/studio/nodes/shell/ShellConfigNode.tsx +51 -0
  138. package/src/components/studio/nodes/shell/ShellNodeBase.tsx +100 -0
  139. package/src/components/studio/nodes/shell/ThemeNodes.tsx +51 -0
  140. package/src/components/studio/nodes/shell/index.ts +12 -0
  141. package/src/components/widgets/BroadcastWidget.tsx +93 -0
  142. package/src/components/widgets/MarketplaceWidget.tsx +298 -0
  143. package/src/components/widgets/McpToolsWidget.tsx +231 -0
  144. package/src/components/widgets/OpsDashboard.tsx +59 -0
  145. package/src/components/widgets/QuickActionsWidget.tsx +60 -0
  146. package/src/components/widgets/UsageWidget.tsx +112 -0
  147. package/src/components/widgets/WidgetRenderer.tsx +892 -0
  148. package/src/components/widgets/WidgetSlotPanel.tsx +213 -0
  149. package/src/config/IconRegistry.ts +126 -0
  150. package/src/contexts/NetworkProvider.tsx +162 -0
  151. package/src/core/AIDirector.ts +71 -0
  152. package/src/core/EventBus.ts +37 -0
  153. package/src/core/PluginContext.tsx +141 -0
  154. package/src/hooks/listeners/useUIStateListener.ts +59 -0
  155. package/src/hooks/listeners/useWhatsAppListener.ts +110 -0
  156. package/src/hooks/morphBridge.ts +82 -0
  157. package/src/hooks/useAIModelSelector.ts +144 -0
  158. package/src/hooks/useAgentStream.ts +220 -0
  159. package/src/hooks/useAutoUpdater.ts +89 -0
  160. package/src/hooks/useBootSequence.ts +20 -0
  161. package/src/hooks/useExportDSD.ts +53 -0
  162. package/src/hooks/useFullscreen.ts +35 -0
  163. package/src/hooks/useGeminiStream.ts +282 -0
  164. package/src/hooks/useIntentLens.ts +224 -0
  165. package/src/hooks/useKeyboardShortcuts.ts +69 -0
  166. package/src/hooks/useLoggerBridge.ts +32 -0
  167. package/src/hooks/useMcpClient.ts +112 -0
  168. package/src/hooks/useNexusaiDeploy.ts +118 -0
  169. package/src/hooks/usePlaybackEngine.ts +21 -0
  170. package/src/hooks/usePlaygroundCommander.ts +475 -0
  171. package/src/hooks/usePluginEngine.ts +165 -0
  172. package/src/hooks/useScreenRecorder.ts +73 -0
  173. package/src/hooks/useShellKeyboard.ts +40 -0
  174. package/src/hooks/useShellShortcuts.ts +118 -0
  175. package/src/hooks/useSoundEffects.ts +35 -0
  176. package/src/hooks/useStudioConfig.ts +72 -0
  177. package/src/hooks/useSystemBoot.ts +84 -0
  178. package/src/hooks/useSystemTelemetry.ts +62 -0
  179. package/src/index.ts +97 -0
  180. package/src/lib/debugLogger.ts +80 -0
  181. package/src/lib/networkInterceptor.ts +100 -0
  182. package/src/mocks/decido.tsx +41 -0
  183. package/src/plugins/pluginAPI.ts +190 -0
  184. package/src/store/McpStore.ts +69 -0
  185. package/src/store/UpdaterStore.ts +60 -0
  186. package/src/store/engine.ts +392 -0
  187. package/src/store/index.ts +4 -0
  188. package/src/store/layoutPresets.ts +66 -0
  189. package/src/store/playgroundTypes.ts +98 -0
  190. package/src/store/useActionTimelineStore.ts +48 -0
  191. package/src/store/useDebugPanelStore.ts +98 -0
  192. package/src/store/useDebugProfileStore.ts +130 -0
  193. package/src/store/useLayoutStore.ts +205 -0
  194. package/src/store/useMorphInstanceStore.ts +289 -0
  195. package/src/store/useMorphologyStore.ts +103 -0
  196. package/src/store/usePlaygroundStore.ts +236 -0
  197. package/src/store/useShellRegistry.ts +123 -0
  198. package/src/store/useSuggestionsStore.ts +57 -0
  199. package/src/store/useThemeStore.ts +399 -0
  200. package/src/store/useUIComponentStore.ts +179 -0
  201. package/src/types/DecidoStoryDefinition.ts +43 -0
  202. package/src/utils/ai/ai-architect.ts +92 -0
  203. package/src/utils/ai/ai-code.ts +187 -0
  204. package/src/utils/ai/ai-core.ts +50 -0
  205. package/src/utils/ai/ai-media.ts +292 -0
  206. package/src/utils/layoutGraph.ts +67 -0
  207. package/tsconfig.json +17 -0
  208. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,141 @@
1
+ import { createContext, useContext, ReactNode, useSyncExternalStore } from 'react';
2
+ import { MaciaPlugin } from '@decido/plugin-engine';
3
+ import { useShellStore } from '../store/engine';
4
+
5
+ /**
6
+ * Interface for the state slices and resources
7
+ * that the Shell provides to any rendered Plugin Widget.
8
+ */
9
+ export interface ShellPluginContextType {
10
+ // Info about the plugin owning the current render tree
11
+ pluginId: string;
12
+ pluginDetails?: MaciaPlugin;
13
+
14
+ // A unified key-value bridge for plugins to store local reactive state
15
+ // without spinning up their own Zustand instances globally.
16
+ // E.g., Redis plugin can use this to store "messages" just for its session.
17
+ setContextState: (key: string, value: any) => void;
18
+ getContextState: <T>(key: string, defaultValue?: T) => T | undefined;
19
+
20
+ // Ability to request shell actions
21
+ openOverlay: (widgetId: string, position: { x: number, y: number }) => void;
22
+ closeOverlay: (overlayId: string) => void;
23
+ }
24
+
25
+ // Internal store strictly for isolated context states
26
+ // Using a simple event emitter pattern so we can plug it into useSyncExternalStore
27
+ class PluginStateStore {
28
+ private state: Record<string, any> = {};
29
+ private listeners = new Set<() => void>();
30
+
31
+ set(key: string, value: any) {
32
+ this.state = { ...this.state, [key]: value };
33
+ this.listeners.forEach(l => l());
34
+ }
35
+
36
+ get<T>(key: string, defaultValue?: T): T | undefined {
37
+ return key in this.state ? this.state[key] as T : defaultValue;
38
+ }
39
+
40
+ getSnapshot() {
41
+ return this.state;
42
+ }
43
+
44
+ subscribe(listener: () => void) {
45
+ this.listeners.add(listener);
46
+ return () => this.listeners.delete(listener);
47
+ }
48
+ }
49
+
50
+ const _pluginStores = new Map<string, PluginStateStore>();
51
+
52
+ const PluginContext = createContext<ShellPluginContextType | null>(null);
53
+
54
+ interface PluginProviderProps {
55
+ pluginId: string;
56
+ children: ReactNode;
57
+ }
58
+
59
+ /**
60
+ * Wraps a plugin's widget tree to provide it Context access.
61
+ */
62
+ export function ShellPluginProvider({ pluginId, children }: PluginProviderProps) {
63
+ const plugins = useShellStore(state => state.plugins);
64
+ const openTransientOverlay = useShellStore(state => state.openTransientOverlay);
65
+ const closeTransientOverlay = useShellStore(state => state.closeTransientOverlay);
66
+
67
+ // Initial setup for this plugin's local state dictionary if empty
68
+ if (!_pluginStores.has(pluginId)) {
69
+ _pluginStores.set(pluginId, new PluginStateStore());
70
+ }
71
+
72
+ const store = _pluginStores.get(pluginId)!;
73
+
74
+ const setContextState = (key: string, value: any) => {
75
+ store.set(key, value);
76
+ };
77
+
78
+ const getContextState = <T,>(key: string, defaultValue?: T): T | undefined => {
79
+ return store.get<T>(key, defaultValue);
80
+ };
81
+
82
+ const openOverlay = (widgetId: string, position: { x: number, y: number }) => {
83
+ openTransientOverlay({ widgetId, position });
84
+ };
85
+
86
+ const value: ShellPluginContextType = {
87
+ pluginId,
88
+ pluginDetails: plugins.get(pluginId),
89
+ setContextState,
90
+ getContextState,
91
+ openOverlay,
92
+ closeOverlay: closeTransientOverlay
93
+ };
94
+
95
+ return (
96
+ <PluginContext.Provider value={value}>
97
+ {children}
98
+ </PluginContext.Provider>
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Hook for widgets to access the generic shell-provided boundaries.
104
+ */
105
+ export function usePluginContext() {
106
+ const ctx = useContext(PluginContext);
107
+ if (!ctx) {
108
+ throw new Error("usePluginContext must be used within a ShellPluginProvider. Only call this inside MaciaWidgets components.");
109
+ }
110
+ return ctx;
111
+ }
112
+
113
+ /**
114
+ * Hook for widgets to subscribe Reactively to a piece of state owned by the plugin
115
+ */
116
+
117
+ export function usePluginState<T>(key: string, defaultValue?: T): [T, (val: T | ((prev: T) => T)) => void] {
118
+ const ctx = usePluginContext();
119
+ const store = _pluginStores.get(ctx.pluginId);
120
+
121
+ if (!store) throw new Error("Plugin store not initialized");
122
+
123
+ const stateSnapshot = useSyncExternalStore(
124
+ (listener) => store.subscribe(listener),
125
+ () => store.getSnapshot()
126
+ );
127
+
128
+ const value = key in stateSnapshot ? stateSnapshot[key] as T : (defaultValue as T);
129
+
130
+ const setter = (val: T | ((prev: T) => T)) => {
131
+ if (typeof val === 'function') {
132
+ // TypeScript tricky casting for generics and functions
133
+ const fn = val as (prev: T) => T;
134
+ ctx.setContextState(key, fn(value));
135
+ } else {
136
+ ctx.setContextState(key, val);
137
+ }
138
+ };
139
+
140
+ return [value, setter];
141
+ }
@@ -0,0 +1,59 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { usePlaygroundStore } from '../../store/usePlaygroundStore';
3
+ import { useTimelineStore } from '@decido/engine';
4
+ import { useEngineStore } from '@decido/engine';
5
+ import { playSound } from '../useSoundEffects';
6
+
7
+ export const useUIStateListener = () => {
8
+ const activeTimelineId = usePlaygroundStore(state => state.prototypeBrand);
9
+ const timelines = useTimelineStore(state => state.timelines);
10
+ const activeNodeIds = useEngineStore(state => state.activeNodeIds);
11
+
12
+ // Leer del nuevo Store Global
13
+ const { addLog, addChatMessage, isMuted, demoState, setDemoState, showCanvas, setShowCanvas } = usePlaygroundStore();
14
+
15
+ const processedNodes = useRef<Set<string>>(new Set());
16
+
17
+ useEffect(() => {
18
+ if (activeNodeIds.length === 0) {
19
+ processedNodes.current.clear();
20
+ setDemoState('idle');
21
+ }
22
+ }, [activeNodeIds, setDemoState]);
23
+
24
+ useEffect(() => {
25
+ const blueprint = timelines[activeTimelineId]?.blueprint || { nodes: timelines[activeTimelineId]?.keyframes ||[] };
26
+ if (!blueprint || activeNodeIds.length === 0) return;
27
+
28
+ const activeUINodes = blueprint.nodes.filter(
29
+ (n: any) => activeNodeIds.includes(n.id) && n.track === 'ui'
30
+ );
31
+
32
+ activeUINodes.forEach((node: any) => {
33
+ if (!processedNodes.current.has(node.id)) {
34
+ processedNodes.current.add(node.id);
35
+
36
+ const newState = node.state || 'idle';
37
+ setDemoState(newState);
38
+
39
+ if (node.canvas !== undefined) {
40
+ setShowCanvas(node.canvas);
41
+ }
42
+
43
+ addLog(`🔀 System Authored Transition: UI Context [${newState}]`, 'system');
44
+
45
+ if (newState.includes('whatsapp') && !newState.includes('resolved') && !newState.includes('idle')) {
46
+ addChatMessage({ type: 'alert', sender: 'system', text: 'Alerta de SLA Crítico detectada vía integración.'});
47
+ } else if (newState.includes('analyzing')) {
48
+ addChatMessage({ type: 'workflow', sender: 'system', text: 'Analizando información contextual...'});
49
+ }
50
+
51
+ if (newState.includes('alert')) playSound('alert', isMuted);
52
+ else playSound('beep', isMuted);
53
+ }
54
+ });
55
+
56
+ },[activeNodeIds, activeTimelineId, timelines, isMuted, addLog, addChatMessage, setDemoState, setShowCanvas]);
57
+
58
+ return { demoState, setDemoState, showCanvas, setShowCanvas };
59
+ };
@@ -0,0 +1,110 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { io } from 'socket.io-client';
3
+ import { usePlaygroundStore } from '../../store/usePlaygroundStore';
4
+ import { playSound } from '../useSoundEffects';
5
+
6
+ const SOCKET_URL = (import.meta as any).env?.VITE_API_BASE_URL || 'http://localhost:3001';
7
+
8
+ export const useWhatsAppListener = () => {
9
+ const { addChatMessage, isMuted } = usePlaygroundStore();
10
+ const processedMessages = useRef<Set<string>>(new Set());
11
+
12
+ useEffect(() => {
13
+ const socket = io(SOCKET_URL, {
14
+ reconnectionAttempts: 5,
15
+ reconnectionDelay: 2000,
16
+ });
17
+
18
+ const handleWhatsAppMessage = (payload: any) => {
19
+ if (payload) {
20
+ const { wamid, from, type, timestamp, name, content } = payload;
21
+
22
+ // Prevent double-processing the same WAMID
23
+ if (wamid && processedMessages.current.has(wamid)) return;
24
+ if (wamid) processedMessages.current.add(wamid);
25
+
26
+ const ts = parseInt(timestamp);
27
+ const date = new Date(ts > 10000000000 ? ts : ts * 1000);
28
+
29
+ // Construct a custom UI schema for the 'ui-artifact' message
30
+ const schema = {
31
+ type: "div",
32
+ props: { className: "w-full outline-hidden bg-transparent flex flex-col p-4 gap-3 border-l-4 border-l-[#25D366]" },
33
+ children: [
34
+ {
35
+ type: "div",
36
+ props: { className: "flex items-center gap-3 border-b border-white/5 pb-3" },
37
+ children: [
38
+ {
39
+ type: "div",
40
+ props: { className: "flex items-center justify-center p-2 bg-[#25D366]/20 rounded-full text-[#25D366] w-8 h-8 font-bold text-xs" },
41
+ children: "WA"
42
+ },
43
+ {
44
+ type: "div",
45
+ props: { className: "flex flex-col" },
46
+ children: [
47
+ {
48
+ type: "span",
49
+ props: { className: "font-semibold text-text-primary text-xs" },
50
+ children: name ? `${name}` : `${from}`
51
+ },
52
+ {
53
+ type: "span",
54
+ props: { className: "text-[#25D366] text-[10px] uppercase font-mono tracking-wider" },
55
+ children: `Recibido a las ${date.toLocaleTimeString()}`
56
+ }
57
+ ]
58
+ }
59
+ ]
60
+ },
61
+ {
62
+ type: "p",
63
+ props: { className: "text-text-secondary leading-relaxed bg-black/20 p-3 rounded-lg border border-white/5" },
64
+ children: content || "Mensaje interactivo o multimedia (Abrir WhatsApp Studio para ver)"
65
+ },
66
+ {
67
+ type: "button",
68
+ props: { className: "mt-2 w-full py-2 bg-[#25D366]/20 hover:bg-[#25D366]/30 text-[#25D366] rounded-lg transition-colors text-xs font-bold border border-[#25D366]/20 flex items-center justify-center gap-2" },
69
+ children: "Abrir WhatsApp Studio",
70
+ onAction: {
71
+ command: "studio:openPlugin",
72
+ payload: { pluginId: "chameleon", view: "discovery_admin" }
73
+ }
74
+ },
75
+ {
76
+ type: "button",
77
+ props: { className: "mt-1 w-full py-2 bg-surface-secondary hover:bg-surface-tertiary text-text-secondary rounded-lg transition-colors text-xs font-medium border border-border-default flex items-center justify-center gap-2" },
78
+ children: "Ver Kanban de Pedidos",
79
+ onAction: {
80
+ command: "studio:openPlugin",
81
+ payload: { pluginId: "chameleon", view: "enterprise_kanban" }
82
+ }
83
+ }
84
+ ]
85
+ };
86
+
87
+ // Add to main chat as a system agent message but with a custom specialized card
88
+ addChatMessage({
89
+ type: 'ui-artifact',
90
+ sender: 'agent',
91
+ text: `Nuevo mensaje de WhatsApp de ${name || from}`,
92
+ actorId: 'whatsapp',
93
+ actorName: 'WhatsApp Gateway',
94
+ uiSchema: JSON.stringify(schema),
95
+ });
96
+ }
97
+ };
98
+
99
+ socket.on('wa:message_received', handleWhatsAppMessage);
100
+
101
+ socket.on('connect', () => {
102
+ console.log('[WhatsApp Listener] Conectado al backend para mensajes globales:', socket.id);
103
+ });
104
+
105
+ return () => {
106
+ socket.off('wa:message_received', handleWhatsAppMessage);
107
+ socket.disconnect();
108
+ };
109
+ }, [addChatMessage, isMuted]);
110
+ };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * morphBridge — Bridges chat responses to the MorphInstance system.
3
+ *
4
+ * When the AI generates visual content (graphs, UI artifacts, components),
5
+ * this bridge auto-creates a MorphInstance tab in MorphShell.
6
+ */
7
+ import { useMorphInstanceStore } from '../store/useMorphInstanceStore';
8
+ import { usePlaygroundStore } from '../store/usePlaygroundStore';
9
+ import type { ShellType, MorphArtifact } from '../store/useShellRegistry';
10
+
11
+ interface BridgeOptions {
12
+ /** Unique ID for this instance (typically chatId or generated) */
13
+ chatId: string;
14
+ /** Shell type to render */
15
+ shellType: ShellType;
16
+ /** Tab label shown in MorphShell */
17
+ label: string;
18
+ /** Shell-level data (config, payload, etc.) */
19
+ data?: Record<string, any>;
20
+ /** Optional artifact to push immediately */
21
+ artifact?: {
22
+ id: string;
23
+ name: string;
24
+ shellType?: ShellType;
25
+ version?: number;
26
+ data: Record<string, any>;
27
+ };
28
+ }
29
+
30
+ /**
31
+ * Creates or updates a MorphInstance and optionally pushes an artifact.
32
+ * Also ensures the canvas is visible.
33
+ */
34
+ export function bridgeToMorph(opts: BridgeOptions): void {
35
+ const { chatId, shellType, label, data = {}, artifact } = opts;
36
+
37
+ // 1. Upsert the MorphInstance
38
+ useMorphInstanceStore.getState().upsertInstance({
39
+ id: chatId,
40
+ sourceChatId: chatId,
41
+ shellType,
42
+ label,
43
+ data,
44
+ });
45
+
46
+ // 2. Push artifact if provided
47
+ if (artifact) {
48
+ useMorphInstanceStore.getState().pushArtifact(chatId, {
49
+ id: artifact.id,
50
+ name: artifact.name,
51
+ shellType: artifact.shellType || shellType,
52
+ version: artifact.version || 1,
53
+ data: artifact.data,
54
+ });
55
+ }
56
+
57
+ // 3. Ensure canvas is visible
58
+ usePlaygroundStore.getState().setShowCanvas(true);
59
+
60
+ console.log(`[MorphBridge] 🌀 ${shellType} instance "${label}" → tab ${chatId}`);
61
+ }
62
+
63
+ /**
64
+ * Detects the appropriate shell type from content/intent.
65
+ */
66
+ export function detectShellType(content: string | Record<string, any>): ShellType {
67
+ if (typeof content === 'string') {
68
+ // HTML content → iframe
69
+ if (/<html|<div|<body|<script/i.test(content)) return 'iframe';
70
+ // Markdown
71
+ if (/^#{1,6}\s|^\*\*|^\- \[/m.test(content)) return 'markdown';
72
+ // Default
73
+ return 'markdown';
74
+ }
75
+
76
+ // Object with artifact type
77
+ if (content.artifact) return 'iframe';
78
+ if (content.schema) return 'iframe';
79
+ if (content.keyframes || content.nodes) return 'shell-canvas';
80
+
81
+ return 'markdown';
82
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * useAIModelSelector — Dynamic multi-provider model selector
3
+ *
4
+ * Replaces hardcoded GEMINI_MODELS list with live provider data
5
+ * from InferenceRouter. Groups models by provider (local vs cloud),
6
+ * shows availability status, and persists selection in localStorage.
7
+ */
8
+
9
+ import { useState, useEffect, useMemo, useCallback } from 'react';
10
+ import {
11
+ getAllProviders,
12
+ getProviderStatuses,
13
+ } from '@decido/kernel-bridge';
14
+
15
+ // ─── Types ──────────────────────────────────────────────────
16
+
17
+ export interface AIModel {
18
+ id: string;
19
+ label: string;
20
+ provider: string;
21
+ tag: string;
22
+ isLocal: boolean;
23
+ }
24
+
25
+ export interface AIProviderGroup {
26
+ provider: string;
27
+ label: string;
28
+ icon: string;
29
+ color: string;
30
+ isLocal: boolean;
31
+ models: AIModel[];
32
+ status: 'online' | 'offline' | 'unknown';
33
+ }
34
+
35
+ // ─── Well-known models per provider ─────────────────────────
36
+
37
+ const KNOWN_MODELS: Record<string, AIModel[]> = {
38
+ ollama: [
39
+ { id: 'qwen2.5:7b', label: 'Qwen 2.5 7B', provider: 'ollama', tag: 'local', isLocal: true },
40
+ { id: 'llama3.1:8b', label: 'Llama 3.1 8B', provider: 'ollama', tag: 'local', isLocal: true },
41
+ { id: 'codellama:7b', label: 'CodeLlama 7B', provider: 'ollama', tag: 'code', isLocal: true },
42
+ { id: 'mistral:7b', label: 'Mistral 7B', provider: 'ollama', tag: 'local', isLocal: true },
43
+ ],
44
+ gemini: [
45
+ { id: 'gemini-3-flash-preview', label: '3.0 Flash', provider: 'gemini', tag: 'fast', isLocal: false },
46
+ { id: 'gemini-3.1-pro-preview', label: '3.1 Pro', provider: 'gemini', tag: 'smart', isLocal: false },
47
+ { id: 'gemini-3.1-flash-lite-preview', label: '3.1 Flash Lite', provider: 'gemini', tag: 'stable', isLocal: false },
48
+ ],
49
+ anthropic: [
50
+ { id: 'claude-sonnet-4-20250514', label: 'Sonnet 4', provider: 'anthropic', tag: 'balanced', isLocal: false },
51
+ { id: 'claude-3-5-haiku-20241022', label: '3.5 Haiku', provider: 'anthropic', tag: 'fast', isLocal: false },
52
+ ],
53
+ openai: [
54
+ { id: 'gpt-4o', label: 'GPT-4o', provider: 'openai', tag: 'smart', isLocal: false },
55
+ { id: 'gpt-4o-mini', label: 'GPT-4o Mini', provider: 'openai', tag: 'fast', isLocal: false },
56
+ ],
57
+ };
58
+
59
+ const PROVIDER_META: Record<string, { label: string; icon: string; color: string; isLocal: boolean }> = {
60
+ ollama: { label: 'Ollama', icon: '🦙', color: '#10b981', isLocal: true },
61
+ gemini: { label: 'Gemini', icon: '✨', color: '#3b82f6', isLocal: false },
62
+ anthropic: { label: 'Claude', icon: '🧠', color: '#a855f7', isLocal: false },
63
+ openai: { label: 'OpenAI', icon: '⚡', color: '#06b6d4', isLocal: false },
64
+ mlx: { label: 'MLX', icon: '🍎', color: '#f59e0b', isLocal: true },
65
+ };
66
+
67
+ const STORAGE_KEY = 'decido_ai_model';
68
+
69
+ // ─── Hook ───────────────────────────────────────────────────
70
+
71
+ export function useAIModelSelector() {
72
+ const [selectedModelId, setSelectedModelId] = useState(
73
+ () => localStorage.getItem(STORAGE_KEY) || 'gemini-3-flash-preview'
74
+ );
75
+ const [providerStatuses, setProviderStatuses] = useState<Record<string, 'online' | 'offline' | 'unknown'>>({});
76
+
77
+ // Check provider statuses periodically
78
+ useEffect(() => {
79
+ let mounted = true;
80
+ const check = async () => {
81
+ try {
82
+ const statuses = await getProviderStatuses();
83
+ if (!mounted) return;
84
+ const map: Record<string, 'online' | 'offline' | 'unknown'> = {};
85
+ for (const [id, status] of Object.entries(statuses)) {
86
+ map[id] = status === 'available' ? 'online' : 'offline';
87
+ }
88
+ setProviderStatuses(map);
89
+ } catch {
90
+ // kernel-bridge not initialized yet — fine
91
+ }
92
+ };
93
+ check();
94
+ const timer = setInterval(check, 30_000);
95
+ return () => { mounted = false; clearInterval(timer); };
96
+ }, []);
97
+
98
+ // Build provider groups
99
+ const providerGroups = useMemo<AIProviderGroup[]>(() => {
100
+ return Object.entries(KNOWN_MODELS).map(([id, models]) => {
101
+ const meta = PROVIDER_META[id] || { label: id, icon: '🤖', color: '#888', isLocal: false };
102
+ return {
103
+ provider: id,
104
+ label: meta.label,
105
+ icon: meta.icon,
106
+ color: meta.color,
107
+ isLocal: meta.isLocal,
108
+ models,
109
+ status: providerStatuses[id] || 'unknown',
110
+ };
111
+ });
112
+ }, [providerStatuses]);
113
+
114
+ // Current selection info
115
+ const selectedModel = useMemo(() => {
116
+ for (const group of providerGroups) {
117
+ const found = group.models.find(m => m.id === selectedModelId);
118
+ if (found) return { model: found, group };
119
+ }
120
+ // Fallback: create an entry for unknown model
121
+ return {
122
+ model: { id: selectedModelId, label: selectedModelId, provider: 'unknown', tag: '', isLocal: false },
123
+ group: providerGroups[0] || null,
124
+ };
125
+ }, [selectedModelId, providerGroups]);
126
+
127
+ const selectModel = useCallback((modelId: string) => {
128
+ setSelectedModelId(modelId);
129
+ localStorage.setItem(STORAGE_KEY, modelId);
130
+ // Sync to window.__DECIDO__ if available
131
+ if (typeof window !== 'undefined' && (window as any).__DECIDO__) {
132
+ (window as any).__DECIDO__.selectedModel = modelId;
133
+ }
134
+ }, []);
135
+
136
+ return {
137
+ selectedModelId,
138
+ selectedModel: selectedModel.model,
139
+ selectedProvider: selectedModel.group,
140
+ providerGroups,
141
+ selectModel,
142
+ providerStatuses,
143
+ };
144
+ }