@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,289 @@
1
+ /**
2
+ * useMorphInstanceStore — Manages morph instances (1 chat = 1 instance = 1 tab).
3
+ *
4
+ * Each chat can create a MorphInstance that appears as a tab in T2.
5
+ * Within each instance, multiple artifacts can be managed (like Gemini Canvas).
6
+ *
7
+ * Model:
8
+ * Chat 1 → MorphInstance { shellType: 'iframe', artifacts: [v1.html, v2.html, style.css] }
9
+ * Chat 2 → MorphInstance { shellType: 'shell-canvas', artifacts: [diagram.flow] }
10
+ */
11
+ import { create } from 'zustand';
12
+ import { persist } from 'zustand/middleware';
13
+ import type { ShellType, MorphArtifact } from './useShellRegistry';
14
+ import { dlog } from '../lib/debugLogger';
15
+
16
+ // ── MorphInstance ──
17
+
18
+ export interface MorphInstance {
19
+ /** Unique ID — typically matches the chatId */
20
+ id: string;
21
+ /** Which chat created this instance */
22
+ sourceChatId: string;
23
+ /** Active shell type */
24
+ shellType: ShellType;
25
+ /** Tab label shown in T2 */
26
+ label: string;
27
+ /** Sub-artifacts within this instance */
28
+ artifacts: MorphArtifact[];
29
+ /** Which artifact is currently displayed */
30
+ activeArtifactIndex: number;
31
+ /** Instance-level data (shell config, etc.) */
32
+ data: Record<string, any>;
33
+ /** Creation timestamp */
34
+ createdAt: number;
35
+ }
36
+
37
+ // ── Store ──
38
+
39
+ interface MorphInstanceState {
40
+ /** All active morph instances, keyed by ID */
41
+ instances: Map<string, MorphInstance>;
42
+ /** Currently focused instance ID (shown in MorphShell) */
43
+ activeInstanceId: string | null;
44
+
45
+ // Sprint AL: Version history per instance
46
+ historyByInstance: Map<string, { stack: any[]; index: number }>;
47
+
48
+ // ── Instance lifecycle ──
49
+ /** Create or update a morph instance for a chat */
50
+ upsertInstance: (instance: Omit<MorphInstance, 'createdAt' | 'artifacts' | 'activeArtifactIndex'> & { artifacts?: MorphArtifact[] }) => void;
51
+ /** Remove a morph instance */
52
+ removeInstance: (id: string) => void;
53
+ /** Set the active (focused) instance */
54
+ setActiveInstance: (id: string | null) => void;
55
+
56
+ // ── Artifact management ──
57
+ /** Push a new artifact to an instance */
58
+ pushArtifact: (instanceId: string, artifact: Omit<MorphArtifact, 'updatedAt'>) => void;
59
+ /** Update an existing artifact's data */
60
+ updateArtifact: (instanceId: string, artifactId: string, data: Record<string, any>) => void;
61
+ /** Set the active artifact within an instance */
62
+ setActiveArtifact: (instanceId: string, index: number) => void;
63
+ /** Remove an artifact from an instance */
64
+ removeArtifact: (instanceId: string, artifactId: string) => void;
65
+
66
+ // ── Convenience ──
67
+ /** Get instance by ID */
68
+ getInstance: (id: string) => MorphInstance | undefined;
69
+ /** Get all instances as array */
70
+ getInstances: () => MorphInstance[];
71
+ /** Get the active instance */
72
+ getActiveInstance: () => MorphInstance | undefined;
73
+
74
+ // ── Sprint AL: Undo/Redo ──
75
+ undo: (instanceId?: string) => void;
76
+ redo: (instanceId?: string) => void;
77
+ canUndo: (instanceId?: string) => boolean;
78
+ canRedo: (instanceId?: string) => boolean;
79
+ getHistoryInfo: (instanceId?: string) => { current: number; total: number };
80
+ }
81
+
82
+ export const useMorphInstanceStore = create<MorphInstanceState>()(
83
+ persist(
84
+ (set, get) => ({
85
+ instances: new Map(),
86
+ activeInstanceId: null,
87
+ historyByInstance: new Map(),
88
+
89
+ upsertInstance: (partial) => {
90
+ dlog.store(`upsertInstance: ${partial.id} (${partial.shellType})`, { id: partial.id, shellType: partial.shellType, label: (partial as any).label });
91
+ set((state) => {
92
+ const instances = new Map(state.instances);
93
+ const existing = instances.get(partial.id);
94
+
95
+ // Sprint AL: Push previous state to history before update
96
+ const historyByInstance = new Map(state.historyByInstance);
97
+ if (existing?.data) {
98
+ const hist = historyByInstance.get(partial.id) || { stack: [], index: -1 };
99
+ // Truncate future history if we're not at the end
100
+ const trimmed = hist.stack.slice(0, hist.index + 1);
101
+ trimmed.push({ ...existing.data });
102
+ // Keep max 20 versions
103
+ if (trimmed.length > 20) trimmed.shift();
104
+ historyByInstance.set(partial.id, { stack: trimmed, index: trimmed.length - 1 });
105
+ }
106
+
107
+ instances.set(partial.id, {
108
+ artifacts: [],
109
+ activeArtifactIndex: 0,
110
+ createdAt: Date.now(),
111
+ ...existing,
112
+ ...partial,
113
+ });
114
+ return { instances, activeInstanceId: partial.id, historyByInstance };
115
+ });
116
+ },
117
+
118
+ removeInstance: (id) => {
119
+ set((state) => {
120
+ const instances = new Map(state.instances);
121
+ instances.delete(id);
122
+ const activeInstanceId = state.activeInstanceId === id
123
+ ? (instances.size > 0 ? instances.keys().next().value ?? null : null)
124
+ : state.activeInstanceId;
125
+ return { instances, activeInstanceId };
126
+ });
127
+ },
128
+
129
+ setActiveInstance: (id) => set({ activeInstanceId: id }),
130
+
131
+ pushArtifact: (instanceId, artifact) => {
132
+ set((state) => {
133
+ const instances = new Map(state.instances);
134
+ const instance = instances.get(instanceId);
135
+ if (!instance) return state;
136
+
137
+ const newArtifact: MorphArtifact = { ...artifact, updatedAt: Date.now() };
138
+ const artifacts = [...instance.artifacts, newArtifact];
139
+ instances.set(instanceId, {
140
+ ...instance,
141
+ artifacts,
142
+ activeArtifactIndex: artifacts.length - 1,
143
+ });
144
+ return { instances };
145
+ });
146
+ },
147
+
148
+ updateArtifact: (instanceId, artifactId, data) => {
149
+ set((state) => {
150
+ const instances = new Map(state.instances);
151
+ const instance = instances.get(instanceId);
152
+ if (!instance) return state;
153
+
154
+ const artifacts = instance.artifacts.map((a) =>
155
+ a.id === artifactId ? { ...a, data: { ...a.data, ...data }, updatedAt: Date.now() } : a
156
+ );
157
+ instances.set(instanceId, { ...instance, artifacts });
158
+ return { instances };
159
+ });
160
+ },
161
+
162
+ setActiveArtifact: (instanceId, index) => {
163
+ set((state) => {
164
+ const instances = new Map(state.instances);
165
+ const instance = instances.get(instanceId);
166
+ if (!instance) return state;
167
+
168
+ instances.set(instanceId, {
169
+ ...instance,
170
+ activeArtifactIndex: Math.max(0, Math.min(index, instance.artifacts.length - 1)),
171
+ });
172
+ return { instances };
173
+ });
174
+ },
175
+
176
+ removeArtifact: (instanceId, artifactId) => {
177
+ set((state) => {
178
+ const instances = new Map(state.instances);
179
+ const instance = instances.get(instanceId);
180
+ if (!instance) return state;
181
+
182
+ const artifacts = instance.artifacts.filter((a) => a.id !== artifactId);
183
+ instances.set(instanceId, {
184
+ ...instance,
185
+ artifacts,
186
+ activeArtifactIndex: Math.min(instance.activeArtifactIndex, Math.max(0, artifacts.length - 1)),
187
+ });
188
+ return { instances };
189
+ });
190
+ },
191
+
192
+ getInstance: (id) => get().instances.get(id),
193
+ getInstances: () => Array.from(get().instances.values()),
194
+ getActiveInstance: () => {
195
+ const { instances, activeInstanceId } = get();
196
+ return activeInstanceId ? instances.get(activeInstanceId) : undefined;
197
+ },
198
+
199
+ // Sprint AL: Undo/Redo
200
+ undo: (instanceId) => {
201
+ const id = instanceId || get().activeInstanceId;
202
+ if (!id) return;
203
+ set((state) => {
204
+ const hist = state.historyByInstance.get(id);
205
+ if (!hist || hist.index < 0) return state;
206
+ const instances = new Map(state.instances);
207
+ const inst = instances.get(id);
208
+ if (!inst) return state;
209
+ // Save current state as "future"
210
+ const historyByInstance = new Map(state.historyByInstance);
211
+ const restoredData = hist.stack[hist.index];
212
+ dlog.store(`undo: ${id} → version ${hist.index}/${hist.stack.length}`, { instanceId: id });
213
+ instances.set(id, { ...inst, data: { ...restoredData } });
214
+ historyByInstance.set(id, { ...hist, index: hist.index - 1 });
215
+ return { instances, historyByInstance };
216
+ });
217
+ },
218
+ redo: (instanceId) => {
219
+ const id = instanceId || get().activeInstanceId;
220
+ if (!id) return;
221
+ set((state) => {
222
+ const hist = state.historyByInstance.get(id);
223
+ if (!hist || hist.index >= hist.stack.length - 1) return state;
224
+ const instances = new Map(state.instances);
225
+ const inst = instances.get(id);
226
+ if (!inst) return state;
227
+ const historyByInstance = new Map(state.historyByInstance);
228
+ const nextIndex = hist.index + 1;
229
+ const restoredData = hist.stack[nextIndex];
230
+ dlog.store(`redo: ${id} → version ${nextIndex + 1}/${hist.stack.length}`, { instanceId: id });
231
+ instances.set(id, { ...inst, data: { ...restoredData } });
232
+ // If redo to last item, also need to push current as future
233
+ historyByInstance.set(id, { ...hist, index: nextIndex });
234
+ return { instances, historyByInstance };
235
+ });
236
+ },
237
+ canUndo: (instanceId) => {
238
+ const id = instanceId || get().activeInstanceId;
239
+ if (!id) return false;
240
+ const hist = get().historyByInstance.get(id);
241
+ return !!hist && hist.index >= 0;
242
+ },
243
+ canRedo: (instanceId) => {
244
+ const id = instanceId || get().activeInstanceId;
245
+ if (!id) return false;
246
+ const hist = get().historyByInstance.get(id);
247
+ return !!hist && hist.index < hist.stack.length - 1;
248
+ },
249
+ getHistoryInfo: (instanceId) => {
250
+ const id = instanceId || get().activeInstanceId;
251
+ if (!id) return { current: 0, total: 0 };
252
+ const hist = get().historyByInstance.get(id);
253
+ if (!hist) return { current: 0, total: 0 };
254
+ return { current: hist.index + 2, total: hist.stack.length + 1 };
255
+ },
256
+ }),
257
+ {
258
+ name: 'decido-morph-instances',
259
+ storage: {
260
+ getItem: (name) => {
261
+ const raw = localStorage.getItem(name);
262
+ if (!raw) return null;
263
+ const parsed = JSON.parse(raw);
264
+ // Rehydrate Map from array
265
+ if (parsed.state?.instances) {
266
+ parsed.state.instances = new Map(parsed.state.instances);
267
+ }
268
+ return parsed;
269
+ },
270
+ setItem: (name, value) => {
271
+ // Serialize Map to array
272
+ const toStore = {
273
+ ...value,
274
+ state: {
275
+ ...value.state,
276
+ instances: Array.from(value.state.instances.entries()),
277
+ },
278
+ };
279
+ localStorage.setItem(name, JSON.stringify(toStore));
280
+ },
281
+ removeItem: (name) => localStorage.removeItem(name),
282
+ },
283
+ partialize: (state) => ({
284
+ instances: state.instances,
285
+ activeInstanceId: state.activeInstanceId,
286
+ } as any),
287
+ }
288
+ )
289
+ );
@@ -0,0 +1,103 @@
1
+ import { create } from 'zustand';
2
+ import React from 'react';
3
+ import { dlog } from '../lib/debugLogger';
4
+
5
+ // ─── Morphological Stage Types ───
6
+
7
+ export type MorphStageType = 'workbench' | 'liquid' | 'artifact' | 'custom';
8
+
9
+ export interface MorphStage {
10
+ /** Type of stage to render */
11
+ type: MorphStageType;
12
+ /** Label for breadcrumbs / header */
13
+ label?: string;
14
+ /** Data payload — UI schema, artifact data, component props */
15
+ data?: any;
16
+ /** For 'custom' type — the registered component ID */
17
+ componentId?: string;
18
+ /** Source node ID that triggered this stage (for traceability) */
19
+ sourceNodeId?: string;
20
+ }
21
+
22
+ // ─── Component Registry for 'custom' type ───
23
+ const componentRegistry = new Map<string, React.ComponentType<any>>();
24
+
25
+ interface MorphologyState {
26
+ /** Currently active stage (what renders in the canvas) */
27
+ activeStage: MorphStage | null;
28
+ /** Navigation history for breadcrumb / back nav */
29
+ stageHistory: MorphStage[];
30
+
31
+ // ─── Actions ───
32
+ /** Replace the active stage directly */
33
+ setStage: (stage: MorphStage | null) => void;
34
+ /** Push a new stage (saves current to history) */
35
+ pushStage: (stage: MorphStage) => void;
36
+ /** Pop back to the previous stage */
37
+ popStage: () => void;
38
+ /** Clear all stages and history */
39
+ clearStages: () => void;
40
+ }
41
+
42
+ export const useMorphologyStore = create<MorphologyState>((set, get) => ({
43
+ activeStage: null,
44
+ stageHistory: [],
45
+
46
+ setStage: (stage) => {
47
+ dlog.morph(`setStage → ${stage?.type || 'null'}${stage?.label ? ` (${stage.label})` : ''}`, stage);
48
+ set({ activeStage: stage });
49
+ },
50
+
51
+ pushStage: (stage) => {
52
+ const { activeStage, stageHistory } = get();
53
+ dlog.morph(`pushStage → ${stage.type}${stage.label ? ` (${stage.label})` : ''} | depth: ${stageHistory.length + 1}`, { stage, previousStage: activeStage?.type });
54
+ const newHistory = activeStage
55
+ ? [...stageHistory, activeStage]
56
+ : stageHistory;
57
+ set({ activeStage: stage, stageHistory: newHistory });
58
+ },
59
+
60
+ popStage: () => {
61
+ const { stageHistory, activeStage } = get();
62
+ if (stageHistory.length === 0) {
63
+ dlog.morph('popStage → null (history empty)', { poppedStage: activeStage?.type }, 'warn');
64
+ set({ activeStage: null });
65
+ return;
66
+ }
67
+ const prev = stageHistory[stageHistory.length - 1];
68
+ dlog.morph(`popStage → ${prev.type}${prev.label ? ` (${prev.label})` : ''} | depth: ${stageHistory.length - 1}`, { poppedStage: activeStage?.type, restoredStage: prev.type });
69
+ set({
70
+ activeStage: prev,
71
+ stageHistory: stageHistory.slice(0, -1)
72
+ });
73
+ },
74
+
75
+ clearStages: () => {
76
+ dlog.morph('clearStages → all stages cleared', { previousDepth: get().stageHistory.length });
77
+ set({ activeStage: null, stageHistory: [] });
78
+ },
79
+ }));
80
+
81
+ // ─── Component Registry API ───
82
+
83
+ /**
84
+ * Register a custom component that can be rendered via morph nodes.
85
+ * Example: registerMorphComponent('AdminWorkbench', AdminWorkbench)
86
+ */
87
+ export function registerMorphComponent(id: string, component: React.ComponentType<any>) {
88
+ componentRegistry.set(id, component);
89
+ }
90
+
91
+ /**
92
+ * Retrieve a registered custom component by ID.
93
+ */
94
+ export function getMorphComponent(id: string): React.ComponentType<any> | undefined {
95
+ return componentRegistry.get(id);
96
+ }
97
+
98
+ /**
99
+ * Get all registered component IDs (for UI dropdowns).
100
+ */
101
+ export function getRegisteredMorphComponents(): string[] {
102
+ return Array.from(componentRegistry.keys());
103
+ }
@@ -0,0 +1,236 @@
1
+ import { create } from 'zustand';
2
+ import { persist, createJSONStorage, StateStorage } from 'zustand/middleware';
3
+ import { get, set as idbSet, del } from 'idb-keyval';
4
+
5
+ // Re-export all types for backward compat
6
+ export type { StepType, PlaygroundLog, ChatMessageType, ChatMessageSender, ChatMessage, SavedSequence, ChatInstance } from './playgroundTypes';
7
+ import type { StepType, PlaygroundLog, ChatMessage, SavedSequence, ChatInstance } from './playgroundTypes';
8
+
9
+ const idbStorage: StateStorage = {
10
+ getItem: async (name: string): Promise<string | null> => (await get(name)) || null,
11
+ setItem: async (name: string, value: string): Promise<void> => { await idbSet(name, value); },
12
+ removeItem: async (name: string): Promise<void> => { await del(name); },
13
+ };
14
+
15
+ interface PlaygroundState {
16
+ // 1. Core State
17
+ isBooting: boolean;
18
+ setIsBooting: (val: boolean) => void;
19
+ step: StepType;
20
+ setStep: (val: StepType) => void;
21
+ selectedProfile: string | null;
22
+ setSelectedProfile: (val: string | null) => void;
23
+ prototypeBrand: string;
24
+ setPrototypeBrand: (val: string | ((prev: string) => string)) => void;
25
+
26
+ activeArtifactData: any;
27
+ setActiveArtifactData: (val: any) => void;
28
+
29
+ // Canvas & UI Integration
30
+ demoState: string;
31
+ setDemoState: (val: string) => void;
32
+ showCanvas: boolean;
33
+ setShowCanvas: (val: boolean) => void;
34
+ showChat: boolean;
35
+ setShowChat: (val: boolean) => void;
36
+
37
+ // 2. UI Toggles
38
+ isMuted: boolean;
39
+ setIsMuted: (val: boolean | ((prev: boolean) => boolean)) => void;
40
+ selectedVoice: string;
41
+ setSelectedVoice: (val: string) => void;
42
+ isFullscreen: boolean;
43
+ setIsFullscreen: (val: boolean) => void;
44
+ isVoiceActive: boolean;
45
+ setIsVoiceActive: (val: boolean) => void;
46
+ isSidebarOpen: boolean;
47
+ setIsSidebarOpen: (val: boolean) => void;
48
+ isTerminalOpen: boolean;
49
+ setIsTerminalOpen: (val: boolean) => void;
50
+ inputValue: string;
51
+ setInputValue: (val: string) => void;
52
+ isCreatorMode: boolean;
53
+ setIsCreatorMode: (val: boolean) => void;
54
+ creatorViewMode: 'timeline' | 'graph';
55
+ setCreatorViewMode: (val: 'timeline' | 'graph') => void;
56
+
57
+ // 4. Logs Management
58
+ logs: PlaygroundLog[];
59
+ addLog: (msg: string, type?: string) => void;
60
+ setLogs: (val: PlaygroundLog[] | ((prev: PlaygroundLog[]) => PlaygroundLog[])) => void;
61
+
62
+ // 5. Timelines
63
+ // Moved to useTimelineStore
64
+
65
+ // 6. Saved Sequences
66
+ savedSequences: SavedSequence[];
67
+ addSavedSequence: (seq: SavedSequence) => void;
68
+ removeSavedSequence: (id: string) => void;
69
+
70
+ // 7. Chat Messages (per-instance)
71
+ chatMessagesByInstance: Record<string, ChatMessage[]>;
72
+ addChatMessage: (msg: Omit<ChatMessage, 'id' | 'timestamp'>) => void;
73
+ upsertChatMessage: (id: string, msg: ChatMessage) => void;
74
+ clearChatMessages: () => void;
75
+ getChatMessages: () => ChatMessage[];
76
+
77
+ // 8. Chat Instances (Sidebar History)
78
+ chatInstances: ChatInstance[];
79
+ activeChatId: string | null;
80
+ addChatInstance: (title?: string) => string;
81
+ removeChatInstance: (id: string) => void;
82
+ renameChatInstance: (id: string, title: string) => void;
83
+ setActiveChatId: (id: string | null) => void;
84
+ }
85
+
86
+ export const usePlaygroundStore = create<PlaygroundState>()(
87
+ persist(
88
+ (set) => ({
89
+ // 1. Core State
90
+ isBooting: true,
91
+ setIsBooting: (val) => set({ isBooting: val }),
92
+ step: 'chat',
93
+ setStep: (val) => set({ step: val }),
94
+ selectedProfile: null,
95
+ setSelectedProfile: (val) => set({ selectedProfile: val }),
96
+ prototypeBrand: 'decido',
97
+ setPrototypeBrand: (val) => set((state) => ({ prototypeBrand: typeof val === 'function' ? val(state.prototypeBrand) : val })),
98
+
99
+ activeArtifactData: null,
100
+ setActiveArtifactData: (val) => set({ activeArtifactData: val }),
101
+
102
+ // Canvas & UI Integration
103
+ demoState: 'idle',
104
+ setDemoState: (val) => set({ demoState: val }),
105
+ showCanvas: false,
106
+ setShowCanvas: (val) => set({ showCanvas: val }),
107
+ showChat: true,
108
+ setShowChat: (val) => set({ showChat: val }),
109
+
110
+ // 2. UI Toggles
111
+ isMuted: false,
112
+ setIsMuted: (val) => set((state) => ({ isMuted: typeof val === 'function' ? val(state.isMuted) : val })),
113
+ selectedVoice: 'Kore',
114
+ setSelectedVoice: (val) => set({ selectedVoice: val }),
115
+ isFullscreen: false,
116
+ setIsFullscreen: (val) => set({ isFullscreen: val }),
117
+ isVoiceActive: false,
118
+ setIsVoiceActive: (val) => set({ isVoiceActive: val }),
119
+ isSidebarOpen: false,
120
+ setIsSidebarOpen: (val) => set({ isSidebarOpen: val }),
121
+ isTerminalOpen: false,
122
+ setIsTerminalOpen: (val) => set({ isTerminalOpen: val }),
123
+ inputValue: '',
124
+ setInputValue: (val) => set({ inputValue: val }),
125
+ isCreatorMode: false,
126
+ setIsCreatorMode: (val) => set({ isCreatorMode: val }),
127
+ creatorViewMode: 'graph',
128
+ setCreatorViewMode: (val) => set({ creatorViewMode: val }),
129
+
130
+ // 4. Logs Management
131
+ logs: [],
132
+ addLog: (msg: string, type: string = 'info') =>
133
+ set((state) => ({
134
+ logs: [...state.logs.slice(-49), { time: new Date().toLocaleTimeString([], { hour12: false }), msg, type }]
135
+ })),
136
+ setLogs: (val) => set((state) => ({ logs: typeof val === 'function' ? val(state.logs) : val })),
137
+
138
+ // 5. Timelines
139
+ // Moved to useTimelineStore
140
+
141
+ // 6. Saved Sequences
142
+ savedSequences: [],
143
+ addSavedSequence: (seq) => set((state) => ({ savedSequences: [...state.savedSequences, seq] })),
144
+ removeSavedSequence: (id) => set((state) => ({ savedSequences: state.savedSequences.filter(s => s.id !== id) })),
145
+
146
+ // 7. Chat Messages (per-instance isolation)
147
+ chatMessagesByInstance: {},
148
+ addChatMessage: (msg) => set((state) => {
149
+ const chatId = state.activeChatId || '_default';
150
+ const existing = state.chatMessagesByInstance[chatId] || [];
151
+ const newMsg = { ...msg, id: Math.random().toString(36).substring(2, 9), timestamp: Date.now() } as ChatMessage;
152
+ const updated = { ...state.chatMessagesByInstance, [chatId]: [...existing, newMsg] };
153
+ // Auto-update instance preview & count
154
+ const chatInstances = state.chatInstances.map(c => {
155
+ if (c.id === chatId) {
156
+ const preview = msg.sender === 'user' ? msg.text.slice(0, 60) : c.preview;
157
+ const title = c.title === 'Nueva conversación' && msg.sender === 'user' ? msg.text.slice(0, 40) : c.title;
158
+ return { ...c, preview, title, messageCount: (c.messageCount || 0) + 1, updatedAt: Date.now() };
159
+ }
160
+ return c;
161
+ });
162
+ return { chatMessagesByInstance: updated, chatInstances };
163
+ }),
164
+ upsertChatMessage: (id, msg) => set((state) => {
165
+ const chatId = state.activeChatId || '_default';
166
+ const existing = state.chatMessagesByInstance[chatId] || [];
167
+ const idx = existing.findIndex(m => m.id === id);
168
+ let updated: ChatMessage[];
169
+ if (idx >= 0) {
170
+ updated = [...existing];
171
+ updated[idx] = { ...updated[idx], ...msg };
172
+ } else {
173
+ updated = [...existing, msg];
174
+ }
175
+ return { chatMessagesByInstance: { ...state.chatMessagesByInstance, [chatId]: updated } };
176
+ }),
177
+ clearChatMessages: () => set((state) => {
178
+ const chatId = state.activeChatId || '_default';
179
+ return { chatMessagesByInstance: { ...state.chatMessagesByInstance, [chatId]: [] } };
180
+ }),
181
+ getChatMessages: () => {
182
+ const state = usePlaygroundStore.getState();
183
+ const chatId = state.activeChatId || '_default';
184
+ return state.chatMessagesByInstance[chatId] || [];
185
+ },
186
+
187
+ // 8. Chat Instances (Sidebar History)
188
+ chatInstances: [],
189
+ activeChatId: null,
190
+ addChatInstance: (title?: string) => {
191
+ const id = Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
192
+ const now = Date.now();
193
+ const model = localStorage.getItem('decido_gemini_model') || undefined;
194
+ const shellType = localStorage.getItem('decido_selected_shell') || undefined;
195
+ set((state) => ({
196
+ chatInstances: [{ id, title: title || 'Nueva conversación', createdAt: now, updatedAt: now, model, shellType }, ...state.chatInstances],
197
+ activeChatId: id
198
+ }));
199
+ return id;
200
+ },
201
+ removeChatInstance: (id: string) => set((state) => {
202
+ const { [id]: _, ...rest } = state.chatMessagesByInstance;
203
+ return {
204
+ chatInstances: state.chatInstances.filter(c => c.id !== id),
205
+ activeChatId: state.activeChatId === id ? (state.chatInstances.find(c => c.id !== id)?.id ?? null) : state.activeChatId,
206
+ chatMessagesByInstance: rest,
207
+ };
208
+ }),
209
+ renameChatInstance: (id: string, title: string) => set((state) => ({
210
+ chatInstances: state.chatInstances.map(c => c.id === id ? { ...c, title, updatedAt: Date.now() } : c)
211
+ })),
212
+ setActiveChatId: (id: string | null) => set({ activeChatId: id }),
213
+ }),
214
+ {
215
+ name: 'playground-storage',
216
+ storage: createJSONStorage(() => idbStorage),
217
+ partialize: (state) => ({
218
+ showChat: state.showChat,
219
+ logs: state.logs,
220
+ inputValue: state.inputValue,
221
+ prototypeBrand: state.prototypeBrand,
222
+ isCreatorMode: state.isCreatorMode,
223
+ isMuted: state.isMuted,
224
+ selectedVoice: state.selectedVoice,
225
+ isTerminalOpen: state.isTerminalOpen,
226
+ isSidebarOpen: state.isSidebarOpen,
227
+ step: state.step,
228
+ selectedProfile: state.selectedProfile,
229
+ savedSequences: state.savedSequences,
230
+ chatMessagesByInstance: state.chatMessagesByInstance,
231
+ chatInstances: state.chatInstances,
232
+ activeChatId: state.activeChatId
233
+ }),
234
+ }
235
+ )
236
+ );