@e-llm-studio/instant-learning 1.3.15-alpha.1 → 1.3.15-alpha.2

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 (33) hide show
  1. package/dist/cjs/features/LearningManagement/LearningManagement.js +27 -0
  2. package/dist/cjs/features/LearningManagement/LearningManagement.js.map +1 -1
  3. package/dist/cjs/features/LearningManagement/LearningTemplateLayout.js +4 -2
  4. package/dist/cjs/features/LearningManagement/LearningTemplateLayout.js.map +1 -1
  5. package/dist/cjs/features/LearningManagement/RuleContent/RuleContent.js +11 -1
  6. package/dist/cjs/features/LearningManagement/RuleContent/RuleContent.js.map +1 -1
  7. package/dist/cjs/features/LearningManagement/components/InstantLearningModalDynamic.js +102 -28
  8. package/dist/cjs/features/LearningManagement/components/InstantLearningModalDynamic.js.map +1 -1
  9. package/dist/cjs/schema-driven/components/PromptTextEditorField.js +24 -10
  10. package/dist/cjs/schema-driven/components/PromptTextEditorField.js.map +1 -1
  11. package/dist/cjs/schema-driven/utils/PayloadUtils.js +0 -21
  12. package/dist/cjs/schema-driven/utils/PayloadUtils.js.map +1 -1
  13. package/dist/features/LearningManagement/LearningManagement.js +27 -0
  14. package/dist/features/LearningManagement/LearningManagement.js.map +1 -1
  15. package/dist/features/LearningManagement/LearningTemplateLayout.js +4 -2
  16. package/dist/features/LearningManagement/LearningTemplateLayout.js.map +1 -1
  17. package/dist/features/LearningManagement/RuleContent/RuleContent.js +11 -1
  18. package/dist/features/LearningManagement/RuleContent/RuleContent.js.map +1 -1
  19. package/dist/features/LearningManagement/components/InstantLearningModalDynamic.js +103 -29
  20. package/dist/features/LearningManagement/components/InstantLearningModalDynamic.js.map +1 -1
  21. package/dist/schema-driven/components/PromptTextEditorField.js +24 -10
  22. package/dist/schema-driven/components/PromptTextEditorField.js.map +1 -1
  23. package/dist/schema-driven/utils/PayloadUtils.js +1 -21
  24. package/dist/schema-driven/utils/PayloadUtils.js.map +1 -1
  25. package/dist/types/src/features/LearningManagement/LearningManagement.d.ts +6 -1
  26. package/dist/types/src/features/LearningManagement/LearningManagement.d.ts.map +1 -1
  27. package/dist/types/src/features/LearningManagement/LearningTemplateLayout.d.ts +4 -0
  28. package/dist/types/src/features/LearningManagement/LearningTemplateLayout.d.ts.map +1 -1
  29. package/dist/types/src/features/LearningManagement/RuleContent/RuleContent.d.ts +4 -0
  30. package/dist/types/src/features/LearningManagement/RuleContent/RuleContent.d.ts.map +1 -1
  31. package/dist/types/src/features/LearningManagement/components/InstantLearningModalDynamic.d.ts.map +1 -1
  32. package/dist/types/src/schema-driven/components/PromptTextEditorField.d.ts.map +1 -1
  33. package/package.json +4 -4
@@ -11,6 +11,7 @@ var useLearningTemplateStore = require('../../features/LearningManagement/store/
11
11
  var useParentEditEnabled = require('../hooks/useParentEditEnabled.js');
12
12
  var constants = require('../../features/LearningManagement/constants.js');
13
13
  var useEnvStore = require('../../features/LearningManagement/store/useEnvStore.js');
14
+ var useDynamicFormStore = require('../store/useDynamicFormStore.js');
14
15
 
15
16
  const VIEW_TABS = [
16
17
  { key: "text", label: "Text" },
@@ -93,7 +94,7 @@ function PromptTextEditorField(props) {
93
94
  (_c2 = (_b2 = props.uiState) == null ? void 0 : _b2.setActiveEditId) == null ? void 0 : _c2.call(_b2, null);
94
95
  };
95
96
  const handleEditWithEcgPro = () => {
96
- var _a2, _b2, _c2, _d2, _e2, _f;
97
+ var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l, _m;
97
98
  const baseModeName = useEnvStore["default"].getState().baseModeName;
98
99
  console.log("hi handleEditWithEcgPro");
99
100
  const mfApi = window.hostMicroFrontendApi;
@@ -101,13 +102,31 @@ function PromptTextEditorField(props) {
101
102
  console.error("PromptTextEditorField: mfApi is not available; cannot open Prompt Mode.");
102
103
  return;
103
104
  }
104
- console.log(props, "props in trigger moee", baseModeName);
105
+ const { globalData, variantData } = useDynamicFormStore.useDynamicFormStore.getState();
106
+ const learningTemplateState = useLearningTemplateStore.useLearningTemplateStore.getState();
107
+ const activeTier = props.tierKey || "tier_1";
108
+ const activeVariantIndex = (_a2 = props.variantIndex) != null ? _a2 : 0;
109
+ const fieldDataKey = String(((_b2 = props.schema) == null ? void 0 : _b2.data_key) || props.id || "instructionPrompt").replace(/^global\./, "");
110
+ const formValues = {
111
+ ...(_d2 = (_c2 = props.uiState) == null ? void 0 : _c2.prefilledData) != null ? _d2 : {},
112
+ ...globalData,
113
+ ...(_f = (_e2 = variantData[activeTier]) == null ? void 0 : _e2[activeVariantIndex]) != null ? _f : {},
114
+ [fieldDataKey]: props.value || "",
115
+ learningMetadata: {
116
+ ...learningTemplateState.learningMetadata,
117
+ instruction_prompt: props.value || ""
118
+ }
119
+ };
120
+ const autoOpenTeachMe = {
121
+ scopeId: (_i = (_h = (_g = props.uiState) == null ? void 0 : _g.scopeId) != null ? _h : learningTemplateState.selectedRuleSetId) != null ? _i : "",
122
+ formValues
123
+ };
105
124
  const payload = {
106
125
  modeType: "submode",
107
126
  eventType: "modeToTrigger",
108
127
  showWelcomeMessageOnTargetModeLoad: false,
109
128
  previousMode: {
110
- modeName: (_b2 = (_a2 = props.currentModeName) != null ? _a2 : baseModeName) != null ? _b2 : "Instant Learning Mode",
129
+ modeName: (_k = (_j = props.currentModeName) != null ? _j : baseModeName) != null ? _k : "Instant Learning Mode",
111
130
  additionalData: {},
112
131
  navigateToECGPro: true
113
132
  },
@@ -115,15 +134,10 @@ function PromptTextEditorField(props) {
115
134
  modeName: "eCG Pro",
116
135
  query: "",
117
136
  responseOfThisMode: null,
118
- additionalData: {
119
- prompt: props.value || "",
120
- promptSection: null,
121
- focusStep: (_c2 = props.currentStep) != null ? _c2 : null,
122
- ...(_d2 = props.modeState) != null ? _d2 : {}
123
- }
137
+ additionalData: autoOpenTeachMe
124
138
  },
125
139
  nextMode: {
126
- modeName: (_f = (_e2 = props.currentModeName) != null ? _e2 : baseModeName) != null ? _f : "Instant Learning Mode",
140
+ modeName: (_m = (_l = props.currentModeName) != null ? _l : baseModeName) != null ? _m : "Instant Learning Mode",
127
141
  queryForNextMode: "i want to use the updated prompt",
128
142
  additionalData: {
129
143
  type: "",
@@ -1 +1 @@
1
- {"version":3,"file":"PromptTextEditorField.js","sources":["../../../../src/schema-driven/components/PromptTextEditorField.tsx"],"sourcesContent":["import React, { useState, useRef, useEffect } from 'react';\nimport { Check, X, Pencil } from 'lucide-react';\nimport PromptTextEditor from '../../features/LearningManagement/components/PromptTextEditor';\nimport { Textarea } from '../../features/IL-OTJ/_components/atoms/Textarea/Textarea';\nimport { useLearningTemplateStore } from '../../features/LearningManagement/store/useLearningTemplateStore';\nimport { useParentEditEnabled } from '../hooks/useParentEditEnabled';\nimport { MF_EVENTS } from '../../features/LearningManagement/constants';\nimport useEnvStore from '../../features/LearningManagement/store/useEnvStore';\n\n// Instruction-prompt editor: read-only until its pencil is pressed, then edits\n// the value directly (no local draft copy); Apply just ends the edit session\n// and notifies the chat (the AI reflects the change), Cancel reverts to the\n// value captured when editing started.\ntype PromptViewMode = 'prompt' | 'text';\n\nconst VIEW_TABS: Array<{ key: PromptViewMode; label: string }> = [\n { key: 'text', label: 'Text' },\n { key: 'prompt', label: 'Prompt' },\n];\n\nexport default function PromptTextEditorField(props: any) {\n // Snapshot of props.value taken when editing starts — used only to detect\n // \"changed since edit began\" for the Apply-disabled state, Cancel's revert,\n // and the chat notification. No draft copy of the value itself is kept:\n // every keystroke writes straight through props.onChange (direct state),\n // so the value the outer form's Save reads is never stale.\n const editStartValueRef = useRef<string>('');\n // Presentation-only switch — both views read/write the exact same value.\n const [viewMode, setViewMode] = useState<PromptViewMode>('text');\n const backwardCompatibility = useLearningTemplateStore((state) => state.backwardCompatibility);\n const id = props.id || 'prompt-editor';\n // New UI: the parent variant owns one edit session, so this field drops its own\n // pencil/apply chrome and writes straight into the parent's draft.\n // A parent edit session says so explicitly via `hideEditControls`. When nobody\n // passes it (legacy CreateRule mounts this straight from the registry, with no\n // schema node and so no `parent_edit`), fall back to the new-UI flag.\n const parentEditEnabled = useParentEditEnabled(props.schema);\n const externallyControlled = props.hideEditControls !== undefined\n ? !!props.hideEditControls\n : parentEditEnabled;\n const isEditing = externallyControlled ? !!props.parentEditing : props.uiState?.activeEditId === id;\n const isOtherFieldEditing = !!props.uiState?.activeEditId && props.uiState.activeEditId !== id;\n const editorContainerRef = useRef<HTMLDivElement>(null);\n \n // Prevent auto-focus on mount and focus changes\n useEffect(() => {\n if (!isEditing && editorContainerRef.current) {\n const container = editorContainerRef.current;\n \n // Blur any currently focused element inside the container\n const focusedElement = container.querySelector(':focus') as HTMLElement | null;\n if (focusedElement) {\n focusedElement.blur();\n }\n \n // Add a focus event listener to prevent focus from staying on disabled editor\n const handleFocus = (e: FocusEvent) => {\n if (!isEditing) {\n e.preventDefault();\n const target = e.target as HTMLElement;\n target.blur();\n }\n };\n \n // Use capture phase to intercept focus before it propagates\n container.addEventListener('focus', handleFocus, { capture: true });\n \n return () => {\n container.removeEventListener('focus', handleFocus, { capture: true });\n };\n }\n }, [isEditing]);\n \n // Make the editor inert when not editing to prevent all interaction and focus\n useEffect(() => {\n if (editorContainerRef.current) {\n if (!isEditing) {\n // Set inert to prevent all interactions\n (editorContainerRef.current as any).inert = true;\n // Disable all focusable elements and remove them from tab order\n const focusableElements = editorContainerRef.current.querySelectorAll('input, textarea, button, a, [tabindex], [contenteditable]');\n focusableElements.forEach((element) => {\n element.setAttribute('tabindex', '-1');\n element.setAttribute('aria-hidden', 'true');\n (element as any).disabled = true;\n });\n } else {\n // Restore interactivity when editing\n (editorContainerRef.current as any).inert = false;\n const focusableElements = editorContainerRef.current.querySelectorAll('[aria-hidden=\"true\"]');\n focusableElements.forEach((element) => {\n element.removeAttribute('aria-hidden');\n const tag = element.tagName.toLowerCase();\n if (tag === 'button' || tag === 'input' || tag === 'textarea' || tag === 'a') {\n element.removeAttribute('tabindex');\n (element as any).disabled = false;\n }\n });\n }\n }\n }, [isEditing]);\n\n const handleStartEdit = () => {\n if (isOtherFieldEditing) return;\n editStartValueRef.current = props.value || '';\n props.uiState?.setActiveEditId?.(id);\n };\n\n const handleCancel = () => {\n // Revert to what it was when editing started — the only place a\n // \"discarded\" value ever existed is this ref snapshot, not a live draft.\n if ((props.value || '') !== editStartValueRef.current) {\n props.onChange(editStartValueRef.current);\n }\n props.uiState?.setActiveEditId?.(null);\n };\n\n const handleSave = () => {\n if ((props.value || '') !== editStartValueRef.current && props.uiState?.setSendMessageInChat) {\n const skId = `sk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n props.uiState.setSendMessageInChat(`__SKELETON__:${skId}:The ${props.title} has been updated through the Learning Form`);\n }\n props.uiState?.setActiveEditId?.(null);\n };\n\n // Handler for the \"Edit with eCG Pro\" button. Builds the Prompt Mode submode\n // request (same shape as ContinueWithTemplateModal's Configure Now payload) and\n // dispatches MF_EVENTS.TRIGGER_SUBMODE through the host mfApi. It does not change\n // the local view. promptSection is null because PromptTextEditor exposes no\n // section identity (its props are value/onChange/sizing/styling only).\n // const externalWorkflowMetaData = useExternalWorkflowStore((state) => state.externalWorkflowMetaData);\n const handleEditWithEcgPro = () => {\n const baseModeName = useEnvStore.getState().baseModeName;\n console.log('hi handleEditWithEcgPro')\n // if (props.readOnly || props.isAiStreaming) return;\n // Prefer the mfApi passed as a prop (threaded from TeachMePlugin); fall back to the\n // external workflow store, which TeachMePlugin also populates.\n // const mfApi = props.mfApi ;\n const mfApi = window.hostMicroFrontendApi;\n if (!mfApi || typeof mfApi.dispatch !== 'function') {\n console.error('PromptTextEditorField: mfApi is not available; cannot open Prompt Mode.');\n return;\n }\n console.log(props,'props in trigger moee',baseModeName)\n const payload = {\n modeType: 'submode',\n eventType: 'modeToTrigger',\n showWelcomeMessageOnTargetModeLoad:false,\n previousMode: {\n modeName: props.currentModeName ??baseModeName?? 'Instant Learning Mode',\n additionalData: {},\n navigateToECGPro:true\n },\n modeToTrigger: {\n modeName: 'eCG Pro',\n query: '',\n responseOfThisMode: null,\n additionalData: {\n prompt: props.value || '',\n promptSection: null,\n focusStep: props.currentStep ?? null,\n ...(props.modeState ?? {}),\n },\n },\n nextMode: {\n modeName: props.currentModeName ??baseModeName?? 'Instant Learning Mode',\n queryForNextMode: 'i want to use the updated prompt',\n additionalData: {\n type: '',\n prompt: '',\n },\n },\n };\n console.log(payload,'payload')\n mfApi.dispatch(MF_EVENTS.TRIGGER_SUBMODE, payload);\n };\n\n const isApplyBtnDisabled = (props.value || '').trim() === editStartValueRef.current.trim();\n const actionBtnStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '8px', border: '1px solid var(--il-border, #e5e7eb)', borderRadius: '8px', cursor: 'pointer', width: '36px', height: '36px', backgroundColor: 'var(--il-surface, #ffffff)' };\n const isHighlighted = props.uiState?.highlights?.get(`${props.tierKey}_${props.variantIndex}`)?.instruction_prompt || false;\n const accentHex = backwardCompatibility ? 'var(--il-primary, #2563EB)' : 'var(--il-primary, #2563EB)';\n const accentRgb = backwardCompatibility ? '37, 99, 235' : '89, 37, 220';\n\n // Single source of truth for both views — the tab strip only changes how this\n // value is rendered, never which value or which handler is in play. No draft\n // copy: both externally-controlled and pencil-gated editing write straight\n // through props.onChange, so an outer Save always reads the live value.\n const currentValue = props.value || '';\n // Invalid or omitted limits preserve the existing unlimited behavior.\n const maxLength = typeof props.maxLength === 'number'\n && Number.isFinite(props.maxLength)\n && props.maxLength >= 0\n ? Math.floor(props.maxLength)\n : undefined;\n const handleValueChange = (v: string) => props.onChange(\n maxLength === undefined ? v : v.slice(0, maxLength),\n );\n const hasReachedMaxLength = maxLength !== undefined && currentValue.length >= maxLength;\nconsole.log(\"PromptTextEditorField\",props.readOnly, props.isAiStreaming, isOtherFieldEditing)\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', width: '100%', maxWidth: '100%', boxSizing: 'border-box', minWidth: 0, marginBottom: '12px' }} data-edit-id={id}>\n <div style={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'space-between' }}>\n <span style={{ fontSize: '14px', fontWeight: 500, color: 'var(--il-foreground, #19213D)', fontFamily: '\"Plus Jakarta Sans\", sans-serif' }}>{props.required && <span style={{ color: 'var(--il-danger, #8F2C23)' }}>*</span>} {props.title}</span>\n {props.enableViewToggle && (\n <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>\n <div style={{ display: 'flex', alignItems: 'center', gap: '2px', padding: '2px', backgroundColor: 'var(--il-secondary-bg, #f1f5f9)', border: '1px solid var(--il-border, #E2E8F0)', borderRadius: '6px' }}>\n {VIEW_TABS.map(({ key, label }) => {\n const isActive = viewMode === key;\n return (\n <button\n key={key}\n type=\"button\"\n onClick={() => setViewMode(key)}\n style={{\n padding: '3px 8px',\n borderRadius: '4px',\n border: 'none',\n cursor: 'pointer',\n fontSize: '11px',\n fontWeight: 500,\n fontFamily: 'Inter, sans-serif',\n backgroundColor: isActive ? 'var(--il-surface, #ffffff)' : 'transparent',\n color: isActive ? accentHex : 'var(--il-muted, #64748B)',\n boxShadow: isActive ? '0px 1px 2px rgba(18, 18, 23, 0.05)' : 'none',\n }}\n >\n {label}\n </button>\n );\n })}\n </div>\n <button type=\"button\" onClick={handleEditWithEcgPro} style={{ padding: '3px 8px', borderRadius: '4px', border: '1px solid var(--il-border, #E2E8F0)', cursor: 'pointer', fontSize: '11px', fontWeight: 500, fontFamily: 'Inter, sans-serif', backgroundColor: 'var(--il-surface, #ffffff)', color: accentHex }}>Edit with eCG Pro</button>\n </div>\n )}\n </div>\n {/* {props.description && (\n <div style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '12px', lineHeight: '130%', color: 'var(--il-muted, #64748B)', marginBottom: '4px' }}>\n {props.description}\n </div>\n )} */}\n {/* This field builds its own header rather than going through SectionWrapper, so\n the schema `subtitle` has to be rendered explicitly here. Falls back to\n `description` to preserve what existing configs already display. */}\n {(props.subtitle || props.description) && (\n <div style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '12px', lineHeight: '130%', color: 'var(--il-muted, #64748B)', marginBottom: '4px' }}>\n {props.subtitle || props.description}\n </div>\n )}\n <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', width: '100%', maxWidth: '100%', minWidth: 0, boxSizing: 'border-box' }}>\n {/* minWidth:0 + maxWidth:100% keep the editor inside the RHS panel — without them\n its toolbar sets the flex item's base width and pushes the whole form into a\n horizontal scroll. overflow:hidden clips to the panel; the toolbar scrolls itself. */}\n <div \n ref={editorContainerRef}\n style={{ \n flex: '1 1 0%', \n minWidth: 0, maxWidth: '100%', overflow: 'hidden', boxSizing: 'border-box', \n border: isHighlighted ? `1px solid ${accentHex}` : 'none', \n borderRadius: '8px', \n boxShadow: isHighlighted ? `0 0 12px 3px rgba(${accentRgb}, 0.3)` : 'none', \n transition: 'all 0.3s',\n scrollBehavior: isEditing ? 'auto' : 'unset'\n }}\n aria-disabled={!isEditing}\n >\n <div style={{ pointerEvents: isEditing ? 'auto' : 'none', opacity: isEditing ? 1 : 0.75, maxWidth: '100%', minWidth: 0, overflow: 'hidden' }}>\n {props.enableViewToggle && viewMode === 'text' ? (\n // Same atom the Rule Description field renders through, so Text View\n // looks and behaves like any other text section.\n <Textarea\n rows={6}\n placeholder={props.placeholder || 'Enter the instruction prompt..'}\n value={currentValue}\n maxLength={maxLength}\n onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => handleValueChange(e.target.value)}\n isReadOnly={props.readOnly || props.isAiStreaming}\n inputReadOnly={!isEditing}\n isHighlighted={isHighlighted}\n errorMessage={props.errorMessage}\n />\n ) : \n (\n <PromptTextEditor\n {...props}\n value={currentValue}\n onChange={handleValueChange}\n maxLength={maxLength}\n minHeight=\"220px\"\n maxHeight=\"400px\"\n readOnly={props.readOnly || props.isAiStreaming || !isEditing}\n />\n )}\n </div>\n </div>\n {!props.readOnly && !externallyControlled && (\n <div style={{ display: 'flex', gap: '8px' }}>\n {isEditing ? (\n <>\n <button onClick={handleSave} disabled={isApplyBtnDisabled} style={{ ...actionBtnStyle, backgroundColor: 'var(--il-primary, #2563eb)', color: 'var(--il-primary-fg, white)', width: 'auto' }}><Check size={20} strokeWidth={2.5} /> Apply</button>\n <button onClick={handleCancel} style={{ ...actionBtnStyle, color: 'var(--il-danger, #dc2626)' }}><X size={20} strokeWidth={2.5} /></button>\n </>\n ) : (\n <button onClick={handleStartEdit} disabled={props.isAiStreaming || isOtherFieldEditing} style={{ ...actionBtnStyle, color: 'var(--il-muted, #64748B)' }}><Pencil size={20} /></button>\n )}\n </div>\n )}\n </div>\n {props.enableViewToggle && viewMode === 'text' && maxLength !== undefined && (\n <div\n role={hasReachedMaxLength ? 'status' : undefined}\n aria-live={hasReachedMaxLength ? 'polite' : undefined}\n style={{\n alignSelf: 'flex-end',\n color: hasReachedMaxLength ? 'var(--il-danger, #dc2626)' : 'var(--il-muted, #64748B)',\n fontFamily: 'Inter, sans-serif',\n fontSize: '12px',\n fontWeight: hasReachedMaxLength ? 600 : 400,\n marginTop: '2px',\n }}\n >\n {currentValue.length} / {maxLength} characters\n {hasReachedMaxLength\n ? ' — Maximum character limit reached'\n : ` — ${maxLength - currentValue.length} characters remaining`}\n </div>\n )}\n </div>\n );\n}\n"],"names":["useRef","useState","useLearningTemplateStore","useParentEditEnabled","useEffect","_a","_b","_c","_d","_e","useEnvStore","MF_EVENTS","jsxs","jsx","Textarea","PromptTextEditor","Fragment","Check","X","Pencil"],"mappings":";;;;;;;;;;;;;;AAeA,MAAM,SAA2D,GAAA;AAAA,EAC/D,EAAE,GAAA,EAAK,MAAQ,EAAA,KAAA,EAAO,MAAO,EAAA;AAAA,EAC7B,EAAE,GAAA,EAAK,QAAU,EAAA,KAAA,EAAO,QAAS,EAAA;AACnC,CAAA,CAAA;AAEA,SAAwB,sBAAsB,KAAY,EAAA;AApB1D,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AA0BE,EAAM,MAAA,iBAAA,GAAoBA,aAAe,EAAE,CAAA,CAAA;AAE3C,EAAA,MAAM,CAAC,QAAA,EA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A,EAAA,IAAA,EAAM,EAAI,EAAA,CAAA,EAAE,CAEjL,EAAA,CAAA;AAAA,KAEJ,EAAA,CAAA;AAAA,IACC,KAAM,CAAA,gBAAA,IAAoB,QAAa,KAAA,MAAA,IAAU,cAAc,KAC9D,CAAA,oBAAAP,eAAA;AAAA,MAAC,KAAA;AAAA,MAAA;AAAA,QACC,IAAA,EAAM,sBAAsB,QAAW,GAAA,KAAA,CAAA;AAAA,QACvC,WAAA,EAAW,sBAAsB,QAAW,GAAA,KAAA,CAAA;AAAA,QAC5C,KAAO,EAAA;AAAA,UACL,SAAW,EAAA,UAAA;AAAA,UACX,KAAA,EAAO,sBAAsB,2BAA8B,GAAA,0BAAA;AAAA,UAC3D,UAAY,EAAA,mBAAA;AAAA,UACZ,QAAU,EAAA,MAAA;AAAA,UACV,UAAA,EAAY,sBAAsB,GAAM,GAAA,GAAA;AAAA,UACxC,SAAW,EAAA,KAAA;AAAA,SACb;AAAA,QAEC,QAAA,EAAA;AAAA,UAAa,YAAA,CAAA,MAAA;AAAA,UAAO,KAAA;AAAA,UAAI,SAAA;AAAA,UAAU,aAAA;AAAA,UAClC,mBACG,GAAA,yCAAA,GACA,CAAM,QAAA,EAAA,SAAA,GAAY,aAAa,MAAM,CAAA,qBAAA,CAAA;AAAA,SAAA;AAAA,OAAA;AAAA,KAC3C;AAAA,GAEJ,EAAA,CAAA,CAAA;AAEJ;;;;"}
1
+ {"version":3,"file":"PromptTextEditorField.js","sources":["../../../../src/schema-driven/components/PromptTextEditorField.tsx"],"sourcesContent":["import React, { useState, useRef, useEffect } from 'react';\nimport { Check, X, Pencil } from 'lucide-react';\nimport PromptTextEditor from '../../features/LearningManagement/components/PromptTextEditor';\nimport { Textarea } from '../../features/IL-OTJ/_components/atoms/Textarea/Textarea';\nimport { useLearningTemplateStore } from '../../features/LearningManagement/store/useLearningTemplateStore';\nimport { useParentEditEnabled } from '../hooks/useParentEditEnabled';\nimport { MF_EVENTS } from '../../features/LearningManagement/constants';\nimport useEnvStore from '../../features/LearningManagement/store/useEnvStore';\nimport { useDynamicFormStore } from '../store/useDynamicFormStore';\n\n// Instruction-prompt editor: read-only until its pencil is pressed, then edits\n// the value directly (no local draft copy); Apply just ends the edit session\n// and notifies the chat (the AI reflects the change), Cancel reverts to the\n// value captured when editing started.\ntype PromptViewMode = 'prompt' | 'text';\n\nconst VIEW_TABS: Array<{ key: PromptViewMode; label: string }> = [\n { key: 'text', label: 'Text' },\n { key: 'prompt', label: 'Prompt' },\n];\n\nexport default function PromptTextEditorField(props: any) {\n // Snapshot of props.value taken when editing starts — used only to detect\n // \"changed since edit began\" for the Apply-disabled state, Cancel's revert,\n // and the chat notification. No draft copy of the value itself is kept:\n // every keystroke writes straight through props.onChange (direct state),\n // so the value the outer form's Save reads is never stale.\n const editStartValueRef = useRef<string>('');\n // Presentation-only switch — both views read/write the exact same value.\n const [viewMode, setViewMode] = useState<PromptViewMode>('text');\n const backwardCompatibility = useLearningTemplateStore((state) => state.backwardCompatibility);\n const id = props.id || 'prompt-editor';\n // New UI: the parent variant owns one edit session, so this field drops its own\n // pencil/apply chrome and writes straight into the parent's draft.\n // A parent edit session says so explicitly via `hideEditControls`. When nobody\n // passes it (legacy CreateRule mounts this straight from the registry, with no\n // schema node and so no `parent_edit`), fall back to the new-UI flag.\n const parentEditEnabled = useParentEditEnabled(props.schema);\n const externallyControlled = props.hideEditControls !== undefined\n ? !!props.hideEditControls\n : parentEditEnabled;\n const isEditing = externallyControlled ? !!props.parentEditing : props.uiState?.activeEditId === id;\n const isOtherFieldEditing = !!props.uiState?.activeEditId && props.uiState.activeEditId !== id;\n const editorContainerRef = useRef<HTMLDivElement>(null);\n \n // Prevent auto-focus on mount and focus changes\n useEffect(() => {\n if (!isEditing && editorContainerRef.current) {\n const container = editorContainerRef.current;\n \n // Blur any currently focused element inside the container\n const focusedElement = container.querySelector(':focus') as HTMLElement | null;\n if (focusedElement) {\n focusedElement.blur();\n }\n \n // Add a focus event listener to prevent focus from staying on disabled editor\n const handleFocus = (e: FocusEvent) => {\n if (!isEditing) {\n e.preventDefault();\n const target = e.target as HTMLElement;\n target.blur();\n }\n };\n \n // Use capture phase to intercept focus before it propagates\n container.addEventListener('focus', handleFocus, { capture: true });\n \n return () => {\n container.removeEventListener('focus', handleFocus, { capture: true });\n };\n }\n }, [isEditing]);\n \n // Make the editor inert when not editing to prevent all interaction and focus\n useEffect(() => {\n if (editorContainerRef.current) {\n if (!isEditing) {\n // Set inert to prevent all interactions\n (editorContainerRef.current as any).inert = true;\n // Disable all focusable elements and remove them from tab order\n const focusableElements = editorContainerRef.current.querySelectorAll('input, textarea, button, a, [tabindex], [contenteditable]');\n focusableElements.forEach((element) => {\n element.setAttribute('tabindex', '-1');\n element.setAttribute('aria-hidden', 'true');\n (element as any).disabled = true;\n });\n } else {\n // Restore interactivity when editing\n (editorContainerRef.current as any).inert = false;\n const focusableElements = editorContainerRef.current.querySelectorAll('[aria-hidden=\"true\"]');\n focusableElements.forEach((element) => {\n element.removeAttribute('aria-hidden');\n const tag = element.tagName.toLowerCase();\n if (tag === 'button' || tag === 'input' || tag === 'textarea' || tag === 'a') {\n element.removeAttribute('tabindex');\n (element as any).disabled = false;\n }\n });\n }\n }\n }, [isEditing]);\n\n const handleStartEdit = () => {\n if (isOtherFieldEditing) return;\n editStartValueRef.current = props.value || '';\n props.uiState?.setActiveEditId?.(id);\n };\n\n const handleCancel = () => {\n // Revert to what it was when editing started — the only place a\n // \"discarded\" value ever existed is this ref snapshot, not a live draft.\n if ((props.value || '') !== editStartValueRef.current) {\n props.onChange(editStartValueRef.current);\n }\n props.uiState?.setActiveEditId?.(null);\n };\n\n const handleSave = () => {\n if ((props.value || '') !== editStartValueRef.current && props.uiState?.setSendMessageInChat) {\n const skId = `sk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n props.uiState.setSendMessageInChat(`__SKELETON__:${skId}:The ${props.title} has been updated through the Learning Form`);\n }\n props.uiState?.setActiveEditId?.(null);\n };\n\n // Handler for the \"Edit with eCG Pro\" button. Builds the Prompt Mode submode\n // request (same shape as ContinueWithTemplateModal's Configure Now payload) and\n // dispatches MF_EVENTS.TRIGGER_SUBMODE through the host mfApi. It does not change\n // the local view. promptSection is null because PromptTextEditor exposes no\n // section identity (its props are value/onChange/sizing/styling only).\n // const externalWorkflowMetaData = useExternalWorkflowStore((state) => state.externalWorkflowMetaData);\n const handleEditWithEcgPro = () => {\n const baseModeName = useEnvStore.getState().baseModeName;\n console.log('hi handleEditWithEcgPro')\n // if (props.readOnly || props.isAiStreaming) return;\n // Prefer the mfApi passed as a prop (threaded from TeachMePlugin); fall back to the\n // external workflow store, which TeachMePlugin also populates.\n // const mfApi = props.mfApi ;\n const mfApi = window.hostMicroFrontendApi;\n if (!mfApi || typeof mfApi.dispatch !== 'function') {\n console.error('PromptTextEditorField: mfApi is not available; cannot open Prompt Mode.');\n return;\n }\n const { globalData, variantData } = useDynamicFormStore.getState();\n const learningTemplateState = useLearningTemplateStore.getState();\n const activeTier = props.tierKey || 'tier_1';\n const activeVariantIndex = props.variantIndex ?? 0;\n const fieldDataKey = String(props.schema?.data_key || props.id || 'instructionPrompt').replace(/^global\\./, '');\n const formValues = {\n ...(props.uiState?.prefilledData ?? {}),\n ...globalData,\n ...(variantData[activeTier]?.[activeVariantIndex] ?? {}),\n [fieldDataKey]: props.value || '',\n learningMetadata: {\n ...learningTemplateState.learningMetadata,\n instruction_prompt: props.value || '',\n },\n };\n const autoOpenTeachMe = {\n scopeId: props.uiState?.scopeId ?? learningTemplateState.selectedRuleSetId ?? '',\n formValues,\n };\n const payload = {\n modeType: 'submode',\n eventType: 'modeToTrigger',\n showWelcomeMessageOnTargetModeLoad:false,\n previousMode: {\n modeName: props.currentModeName ??baseModeName?? 'Instant Learning Mode',\n additionalData: {},\n navigateToECGPro:true\n },\n modeToTrigger: {\n modeName: 'eCG Pro',\n query: '',\n responseOfThisMode: null,\n additionalData: autoOpenTeachMe,\n },\n nextMode: {\n modeName: props.currentModeName ??baseModeName?? 'Instant Learning Mode',\n queryForNextMode: 'i want to use the updated prompt',\n additionalData: {\n type: '',\n prompt: '',\n },\n },\n };\n console.log(payload,'payload')\n mfApi.dispatch(MF_EVENTS.TRIGGER_SUBMODE, payload);\n };\n\n const isApplyBtnDisabled = (props.value || '').trim() === editStartValueRef.current.trim();\n const actionBtnStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '8px', border: '1px solid var(--il-border, #e5e7eb)', borderRadius: '8px', cursor: 'pointer', width: '36px', height: '36px', backgroundColor: 'var(--il-surface, #ffffff)' };\n const isHighlighted = props.uiState?.highlights?.get(`${props.tierKey}_${props.variantIndex}`)?.instruction_prompt || false;\n const accentHex = backwardCompatibility ? 'var(--il-primary, #2563EB)' : 'var(--il-primary, #2563EB)';\n const accentRgb = backwardCompatibility ? '37, 99, 235' : '89, 37, 220';\n\n // Single source of truth for both views — the tab strip only changes how this\n // value is rendered, never which value or which handler is in play. No draft\n // copy: both externally-controlled and pencil-gated editing write straight\n // through props.onChange, so an outer Save always reads the live value.\n const currentValue = props.value || '';\n // Invalid or omitted limits preserve the existing unlimited behavior.\n const maxLength = typeof props.maxLength === 'number'\n && Number.isFinite(props.maxLength)\n && props.maxLength >= 0\n ? Math.floor(props.maxLength)\n : undefined;\n const handleValueChange = (v: string) => props.onChange(\n maxLength === undefined ? v : v.slice(0, maxLength),\n );\n const hasReachedMaxLength = maxLength !== undefined && currentValue.length >= maxLength;\nconsole.log(\"PromptTextEditorField\",props.readOnly, props.isAiStreaming, isOtherFieldEditing)\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', width: '100%', maxWidth: '100%', boxSizing: 'border-box', minWidth: 0, marginBottom: '12px' }} data-edit-id={id}>\n <div style={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'space-between' }}>\n <span style={{ fontSize: '14px', fontWeight: 500, color: 'var(--il-foreground, #19213D)', fontFamily: '\"Plus Jakarta Sans\", sans-serif' }}>{props.required && <span style={{ color: 'var(--il-danger, #8F2C23)' }}>*</span>} {props.title}</span>\n {props.enableViewToggle && (\n <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>\n <div style={{ display: 'flex', alignItems: 'center', gap: '2px', padding: '2px', backgroundColor: 'var(--il-secondary-bg, #f1f5f9)', border: '1px solid var(--il-border, #E2E8F0)', borderRadius: '6px' }}>\n {VIEW_TABS.map(({ key, label }) => {\n const isActive = viewMode === key;\n return (\n <button\n key={key}\n type=\"button\"\n onClick={() => setViewMode(key)}\n style={{\n padding: '3px 8px',\n borderRadius: '4px',\n border: 'none',\n cursor: 'pointer',\n fontSize: '11px',\n fontWeight: 500,\n fontFamily: 'Inter, sans-serif',\n backgroundColor: isActive ? 'var(--il-surface, #ffffff)' : 'transparent',\n color: isActive ? accentHex : 'var(--il-muted, #64748B)',\n boxShadow: isActive ? '0px 1px 2px rgba(18, 18, 23, 0.05)' : 'none',\n }}\n >\n {label}\n </button>\n );\n })}\n </div>\n <button type=\"button\" onClick={handleEditWithEcgPro} style={{ padding: '3px 8px', borderRadius: '4px', border: '1px solid var(--il-border, #E2E8F0)', cursor: 'pointer', fontSize: '11px', fontWeight: 500, fontFamily: 'Inter, sans-serif', backgroundColor: 'var(--il-surface, #ffffff)', color: accentHex }}>Edit with eCG Pro</button>\n </div>\n )}\n </div>\n {/* {props.description && (\n <div style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '12px', lineHeight: '130%', color: 'var(--il-muted, #64748B)', marginBottom: '4px' }}>\n {props.description}\n </div>\n )} */}\n {/* This field builds its own header rather than going through SectionWrapper, so\n the schema `subtitle` has to be rendered explicitly here. Falls back to\n `description` to preserve what existing configs already display. */}\n {(props.subtitle || props.description) && (\n <div style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '12px', lineHeight: '130%', color: 'var(--il-muted, #64748B)', marginBottom: '4px' }}>\n {props.subtitle || props.description}\n </div>\n )}\n <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', width: '100%', maxWidth: '100%', minWidth: 0, boxSizing: 'border-box' }}>\n {/* minWidth:0 + maxWidth:100% keep the editor inside the RHS panel — without them\n its toolbar sets the flex item's base width and pushes the whole form into a\n horizontal scroll. overflow:hidden clips to the panel; the toolbar scrolls itself. */}\n <div \n ref={editorContainerRef}\n style={{ \n flex: '1 1 0%', \n minWidth: 0, maxWidth: '100%', overflow: 'hidden', boxSizing: 'border-box', \n border: isHighlighted ? `1px solid ${accentHex}` : 'none', \n borderRadius: '8px', \n boxShadow: isHighlighted ? `0 0 12px 3px rgba(${accentRgb}, 0.3)` : 'none', \n transition: 'all 0.3s',\n scrollBehavior: isEditing ? 'auto' : 'unset'\n }}\n aria-disabled={!isEditing}\n >\n <div style={{ pointerEvents: isEditing ? 'auto' : 'none', opacity: isEditing ? 1 : 0.75, maxWidth: '100%', minWidth: 0, overflow: 'hidden' }}>\n {props.enableViewToggle && viewMode === 'text' ? (\n // Same atom the Rule Description field renders through, so Text View\n // looks and behaves like any other text section.\n <Textarea\n rows={6}\n placeholder={props.placeholder || 'Enter the instruction prompt..'}\n value={currentValue}\n maxLength={maxLength}\n onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => handleValueChange(e.target.value)}\n isReadOnly={props.readOnly || props.isAiStreaming}\n inputReadOnly={!isEditing}\n isHighlighted={isHighlighted}\n errorMessage={props.errorMessage}\n />\n ) : \n (\n <PromptTextEditor\n {...props}\n value={currentValue}\n onChange={handleValueChange}\n maxLength={maxLength}\n minHeight=\"220px\"\n maxHeight=\"400px\"\n readOnly={props.readOnly || props.isAiStreaming || !isEditing}\n />\n )}\n </div>\n </div>\n {!props.readOnly && !externallyControlled && (\n <div style={{ display: 'flex', gap: '8px' }}>\n {isEditing ? (\n <>\n <button onClick={handleSave} disabled={isApplyBtnDisabled} style={{ ...actionBtnStyle, backgroundColor: 'var(--il-primary, #2563eb)', color: 'var(--il-primary-fg, white)', width: 'auto' }}><Check size={20} strokeWidth={2.5} /> Apply</button>\n <button onClick={handleCancel} style={{ ...actionBtnStyle, color: 'var(--il-danger, #dc2626)' }}><X size={20} strokeWidth={2.5} /></button>\n </>\n ) : (\n <button onClick={handleStartEdit} disabled={props.isAiStreaming || isOtherFieldEditing} style={{ ...actionBtnStyle, color: 'var(--il-muted, #64748B)' }}><Pencil size={20} /></button>\n )}\n </div>\n )}\n </div>\n {props.enableViewToggle && viewMode === 'text' && maxLength !== undefined && (\n <div\n role={hasReachedMaxLength ? 'status' : undefined}\n aria-live={hasReachedMaxLength ? 'polite' : undefined}\n style={{\n alignSelf: 'flex-end',\n color: hasReachedMaxLength ? 'var(--il-danger, #dc2626)' : 'var(--il-muted, #64748B)',\n fontFamily: 'Inter, sans-serif',\n fontSize: '12px',\n fontWeight: hasReachedMaxLength ? 600 : 400,\n marginTop: '2px',\n }}\n >\n {currentValue.length} / {maxLength} characters\n {hasReachedMaxLength\n ? ' — Maximum character limit reached'\n : ` — ${maxLength - currentValue.length} characters remaining`}\n </div>\n )}\n </div>\n );\n}\n"],"names":["useRef","useState","useLearningTemplateStore","useParentEditEnabled","useEffect","_a","_b","_c","_d","_e","useEnvStore","useDynamicFormStore","MF_EVENTS","jsxs","jsx","Textarea","PromptTextEditor","Fragment","Check","X","Pencil"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,SAA2D,GAAA;AAAA,EAC/D,EAAE,GAAA,EAAK,MAAQ,EAAA,KAAA,EAAO,MAAO,EAAA;AAAA,EAC7B,EAAE,GAAA,EAAK,QAAU,EAAA,KAAA,EAAO,QAAS,EAAA;AACnC,CAAA,CAAA;AAEA,SAAwB,sBAAsB,KAAY,EAAA;AArB1D,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AA2BE,EAAM,MAAA,iBAAA,GAAoBA,aAAe,EAAE,CAAA,CAAA;AAE3C,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAIC,eAAyB,MAAM,CAAA,CAAA;AAC/D,EAAA,MAAM,qBAAwB,GAAAC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AP,eAAA;AAAA,MAAC,KAAA;AAAA,MAAA;AAAA,QACC,IAAA,EAAM,sBAAsB,QAAW,GAAA,KAAA,CAAA;AAAA,QACvC,WAAA,EAAW,sBAAsB,QAAW,GAAA,KAAA,CAAA;AAAA,QAC5C,KAAO,EAAA;AAAA,UACL,SAAW,EAAA,UAAA;AAAA,UACX,KAAA,EAAO,sBAAsB,2BAA8B,GAAA,0BAAA;AAAA,UAC3D,UAAY,EAAA,mBAAA;AAAA,UACZ,QAAU,EAAA,MAAA;AAAA,UACV,UAAA,EAAY,sBAAsB,GAAM,GAAA,GAAA;AAAA,UACxC,SAAW,EAAA,KAAA;AAAA,SACb;AAAA,QAEC,QAAA,EAAA;AAAA,UAAa,YAAA,CAAA,MAAA;AAAA,UAAO,KAAA;AAAA,UAAI,SAAA;AAAA,UAAU,aAAA;AAAA,UAClC,mBACG,GAAA,yCAAA,GACA,CAAM,QAAA,EAAA,SAAA,GAAY,aAAa,MAAM,CAAA,qBAAA,CAAA;AAAA,SAAA;AAAA,OAAA;AAAA,KAC3C;AAAA,GAEJ,EAAA,CAAA,CAAA;AAEJ;;;;"}
@@ -12,26 +12,6 @@ const resolveScope = (dataKey, isVariantLevel) => ({
12
12
  });
13
13
  const isVariantWrapper = (node) => (node == null ? void 0 : node.is_repeatable_variant) === true || (node == null ? void 0 : node.bpa_ui_component) === "VariantListWrapper";
14
14
  const isRepeatableSection = (node) => (node == null ? void 0 : node.repeatable) === true || (node == null ? void 0 : node.bpa_ui_component) === "RepeatableSection";
15
- const getVariantPrefilledData = (jsonSchema, prefilledData) => {
16
- const variantData = {};
17
- const traverse = (properties, isVariantLevel = false) => {
18
- if (!properties) return;
19
- Object.values(properties).forEach((node) => {
20
- var _a, _b, _c;
21
- const dataKey = node == null ? void 0 : node.data_key;
22
- const cleanKey = dataKey == null ? void 0 : dataKey.replace("global.", "");
23
- const isVariantField = isVariantLevel && !(dataKey == null ? void 0 : dataKey.startsWith("global."));
24
- if (isVariantField && Object.prototype.hasOwnProperty.call(prefilledData, cleanKey)) {
25
- (_a = variantData.tier_1) != null ? _a : variantData.tier_1 = {};
26
- (_c = (_b = variantData.tier_1)[0]) != null ? _c : _b[0] = {};
27
- variantData.tier_1[0][cleanKey] = prefilledData[cleanKey];
28
- }
29
- if (node == null ? void 0 : node.properties) traverse(node.properties, isVariantLevel || isVariantWrapper(node));
30
- });
31
- };
32
- traverse(jsonSchema == null ? void 0 : jsonSchema.properties);
33
- return variantData;
34
- };
35
15
  const CORE_KEY_ALIASES = {
36
16
  rule_title: ["title", "ruleTitle"],
37
17
  rule_description: ["description", "variant_description"],
@@ -266,6 +246,5 @@ exports.applyResponseToStore = applyResponseToStore;
266
246
  exports.areRequiredFieldsFilled = areRequiredFieldsFilled;
267
247
  exports.buildFieldLabelMap = buildFieldLabelMap;
268
248
  exports.generatePayloadFromSchema = generatePayloadFromSchema;
269
- exports.getVariantPrefilledData = getVariantPrefilledData;
270
249
  exports.resolveSchemaRuleSetId = resolveSchemaRuleSetId;
271
250
  //# sourceMappingURL=PayloadUtils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PayloadUtils.js","sources":["../../../../src/schema-driven/utils/PayloadUtils.ts"],"sourcesContent":["// src/schema-driven/utils/PayloadUtils.ts\nimport { useDynamicFormStore } from '../store/useDynamicFormStore';\nimport { isTableValueValid } from '../helper';\nimport { stripAiReasoning } from './aiReasoning';\n/**\n * Two distinct keys per schema leaf, and they are NOT interchangeable:\n * - PROPERTY KEY — the key under `properties` (e.g. `rule_title`, `wta`). This is\n * the ON-THE-WIRE key: what we send to the AI in `ui_state` and what the AI\n * echoes back in its response JSON.\n * - data_key — the internal dynamic-store slot the RHS field reads/writes\n * (e.g. `template_title`, `whenToApply`).\n * So the round-trip is: read store by data_key → emit under property key → AI\n * responds under property key → write store by data_key.\n *\n * Which store bucket a leaf lives in, mirrored by both read (generatePayloadFromSchema)\n * and write (applyResponseToStore) so the round-trip stays symmetric:\n * - `global.`-prefixed data_key, OR a field outside a variant wrapper → global.\n * - otherwise → variant-scoped (tierKey + variantIndex).\n * The data_key is stored WITHOUT the `global.` prefix (`cleanKey`).\n */\nconst resolveScope = (dataKey: string, isVariantLevel: boolean) => ({\n cleanKey: dataKey.replace('global.', ''),\n isGlobal: dataKey.startsWith('global.') || !isVariantLevel,\n});\n/**\n * A section is the repeatable-variant container if it renders as VariantListWrapper\n * OR is explicitly flagged `is_repeatable_variant: true`. Detection MUST match what\n * VariantListField renders per variant, so the store scope (global vs variant) and\n * the UI stay in sync. Its child leaves are variant-scoped; everything else is global.\n */\nconst isVariantWrapper = (node: any): boolean =>\n node?.is_repeatable_variant === true || node?.bpa_ui_component === 'VariantListWrapper';\n\n// Unlike a normal object wrapper, a repeatable section owns one array value. Its\n// descendants are an item template, not independent top-level payload fields.\nconst isRepeatableSection = (node: any): boolean =>\n node?.repeatable === true || node?.bpa_ui_component === 'RepeatableSection';\n\nexport const getVariantPrefilledData = (jsonSchema: any, prefilledData: Record<string, any>) => {\n const variantData: Record<string, Record<number, Record<string, any>>> = {};\n\n const traverse = (properties: any, isVariantLevel = false) => {\n if (!properties) return;\n Object.values(properties).forEach((node: any) => {\n const dataKey = node?.data_key;\n const cleanKey = dataKey?.replace('global.', '');\n const isVariantField = isVariantLevel && !dataKey?.startsWith('global.');\n\n if (isVariantField && Object.prototype.hasOwnProperty.call(prefilledData, cleanKey)) {\n variantData.tier_1 ??= {};\n variantData.tier_1[0] ??= {};\n variantData.tier_1[0][cleanKey] = prefilledData[cleanKey];\n }\n\n if (node?.properties) traverse(node.properties, isVariantLevel || isVariantWrapper(node));\n });\n };\n\n traverse(jsonSchema?.properties);\n return variantData;\n};\n\n/**\n * A core leaf's value may arrive under a looser name than the property key:\n * - from the AI's `updated_fields` (e.g. `title` for `rule_title`), or\n * - from the rule-fetch API on load, which uses its own fixed field names\n * (`ruleTitle`, `description`, `whenToApply`, `whenNotToApply`).\n * Read those aliases without changing the canonical wire key we emit. Keys here\n * are the conventional property keys; a schema using different keys would extend this.\n * Shared by `applyResponseToStore` (store hydration) and `buildFieldLabelMap`\n * (chat labels) so both resolve the AI's key names the same way.\n */\nexport const CORE_KEY_ALIASES: Record<string, string[]> = {\n rule_title: ['title', 'ruleTitle'],\n rule_description: ['description', 'variant_description'],\n wta: ['whenToApply', 'when_to_apply'],\n wnta: ['whenNotToApply', 'when_not_to_apply'],\n};\n\n/**\n * Build the AI-key → user-facing-label map for the schema-driven flow.\n *\n * The C.A.R.E. response echoes schema PROPERTY KEYS (or their `CORE_KEY_ALIASES`)\n * in `updated_fields` / `identified_fields`. The chat renderer must label those\n * with the same title the RHS form shows, and the JSON owns that title\n * (`rule_title` → \"Template Title\", `rule_description` → \"Template Goal\", …),\n * so it is derived here instead of being hardcoded in the renderer.\n *\n * Every leaf that carries a `title` contributes an entry under its property key\n * plus each of its aliases, so `title`, `rule_title` and `ruleTitle` all resolve\n * to the same label. Only the schema-driven modal passes this map down; the\n * legacy flow keeps the renderer's built-in defaults.\n */\nexport const buildFieldLabelMap = (jsonSchema: any): Record<string, string> => {\n const labels: Record<string, string> = {};\n const traverseSchema = (properties: any) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // `ui_only` wrappers (sections/rows) carry no value of their own, but their\n // children do — so recurse through them and only record leaf titles.\n if (node?.data_key && node?.title) {\n labels[propKey] = node.title;\n CORE_KEY_ALIASES[propKey]?.forEach((alias) => {\n labels[alias] = node.title;\n });\n }\n if (node?.properties) traverseSchema(node.properties);\n });\n };\n traverseSchema(jsonSchema?.properties);\n return labels;\n};\n\nexport const generatePayloadFromSchema = (\n jsonSchema: any,\n tierKey: string,\n variantIndex: number\n) => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n\n // `core_field: true` leaves sit at the top level of the payload; everything\n // else is collected under `learning_metadata`.\n const rootPayload: any = {};\n const metadataProperties: any = {};\n const metadataRequired: string[] = [];\n // Property keys whose value came from the per-variant store slot (getVariantField),\n // as opposed to the global slot shared across every variant. Callers that merge this\n // metadata bag with a variant's own API-saved metadata need this to know which keys\n // must always take the live store value (e.g. instruction_prompt) vs. which are fine\n // to let the API snapshot win (e.g. category).\n const variantScopedMetadataKeys: string[] = [];\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // A repeatable node is a value-bearing array even if older DTs left\n // `ui_only: true` on it. Treat it as the array field, never as a wrapper\n // whose item-template leaves should be emitted as flat metadata.\n if (node.ui_only && !isRepeatableSection(node)) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n if (node.data_key) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n // A repeatable section owns an array under its data_key. Unlike ordinary\n // fields, its config property key may be an implementation-generated id,\n // so use the data_key as its stable wire/payload key.\n const payloadKey = isRepeatableSection(node) ? cleanKey : propKey;\n let value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey, variantIndex, cleanKey);\n // ALWAYS provide a fallback default so the AI sees the empty keys\n // (it needs the previous value to reason about the user's request).\n if (value === undefined) {\n if (node.type === 'array') value = [];\n else if (node.type === 'boolean') value = false;\n else if (node.type === 'object') value = {};\n else value = ''; // default string (incl. \\n-joined wta/wnta)\n }\n // Cognitive reasoning belongs to the core, AI-managed rule fields only.\n // Learning metadata (including `instruction_prompt`) is user-owned content\n // and can intentionally contain an `<ai_reasoning>` block, so preserve it\n // verbatim when it is sent back in `ui_state`.\n if (node.core_field && typeof value === 'string' && value.includes('<ai_reasoning>')) {\n value = stripAiReasoning(value).clean;\n }\n // Emit under the PROPERTY KEY (the AI's wire key), not the data_key.\n if (node.core_field) {\n rootPayload[payloadKey] = value;\n } else {\n metadataProperties[payloadKey] = value;\n // `required` is derived from each field's `is_required` flag in the JSON.\n if (node.is_required && !metadataRequired.includes(payloadKey)) {\n metadataRequired.push(payloadKey);\n }\n if (!isGlobal) variantScopedMetadataKeys.push(payloadKey);\n }\n }\n // Recursively traverse object properties\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // 1. Traverse global properties\n traverseSchema(schemaProperties, false);\n // 2. Traverse variant properties\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n const learningMetadata = { properties: metadataProperties, required: metadataRequired };\n return { rootPayload, learningMetadata, variantScopedMetadataKeys };\n};\n/**\n * PROPERTY KEYS that hand ownership of the ruleset id to a form field. In the\n * JSON-driven flow the Sub-Category dropdown carries it (`ruleset_id`), so\n * whichever sub-category the user picks decides which ruleset the template is\n * saved into. `scope_id` is accepted as the same thing under the BE's name.\n */\nconst RULE_SET_ID_PROPERTY_KEYS = ['ruleset_id', 'scope_id'];\n\n/** First leaf (depth-first) whose property key hands over the ruleset id. */\nconst findRuleSetIdNode = (properties: any): any => {\n if (!properties) return null;\n for (const [propKey, node] of Object.entries<any>(properties)) {\n if (RULE_SET_ID_PROPERTY_KEYS.includes(propKey) && node?.data_key) return node;\n const nested = findRuleSetIdNode(node?.properties);\n if (nested) return nested;\n }\n return null;\n};\n\n/**\n * Options for a leaf, resolved exactly like DropdownSectionField renders them:\n * host-injected `dynamicOptions[<dynamic_options_key | data_key + 'Options'>]`\n * wins when non-empty, then inline `options`, then `enum`. Keeping the two in\n * sync matters — the id we return must come from the option the user saw.\n */\nconst resolveNodeOptions = (node: any, dynamicOptions?: Record<string, any>): any[] => {\n const optionsKey = node?.dynamic_options_key || `${node?.data_key}Options`;\n const hostOptions = dynamicOptions?.[optionsKey];\n if (Array.isArray(hostOptions) && hostOptions.length > 0) return hostOptions;\n if (Array.isArray(node?.options)) return node.options;\n if (Array.isArray(node?.enum)) {\n return node.enum.map((opt: any) =>\n opt && typeof opt === 'object' ? opt : { label: String(opt), value: opt }\n );\n }\n return [];\n};\n\n/**\n * The ruleset id the SCHEMA selects, or null when it doesn't select one.\n *\n * The dynamic store holds a dropdown's `value` (e.g. `weekly_digest`), never the\n * backing id — that travels on the option itself (`{ id, label, value }`, from\n * `dynamicOptions` or from inline JSON options that carry an `id`). So: find the\n * `ruleset_id`/`scope_id` leaf, read its store value, and return the id of the\n * option currently selected in it.\n *\n * Null means \"the schema has no opinion\" and the caller keeps whatever ruleset\n * it already used — that's the case for a schema without such a leaf, nothing\n * picked yet, or an option without an id. Only GLOBAL store values are read: a\n * ruleset is a per-template choice, not a per-variant one.\n */\nexport const resolveSchemaRuleSetId = (\n jsonSchema: any,\n dynamicOptions?: Record<string, any>\n): string | null => {\n const node = findRuleSetIdNode(jsonSchema?.properties);\n if (!node) return null;\n\n // `cleanKey` — the store slot, with any `global.` data_key prefix stripped.\n const { cleanKey } = resolveScope(node.data_key, false);\n const value = useDynamicFormStore.getState().getGlobalField(cleanKey);\n if (!value) return null;\n\n // The API may hydrate a value with different casing from the dropdown option\n // (for example, `nyc` vs. `NYC`). Match strings case-insensitively, while\n // returning the option's UUID — never its display/value token.\n const normalizedValue = typeof value === 'string' ? value.trim().toLowerCase() : value;\n const selected = resolveNodeOptions(node, dynamicOptions).find((opt: any) => {\n const optionValue =\n typeof opt?.value === 'string' ? opt.value.trim().toLowerCase() : opt?.value;\n return optionValue === normalizedValue;\n });\n return selected?.id ?? null;\n};\n\nconst isFieldFilled = (value: any, node?: any): boolean => {\n if (node?.bpa_ui_component === 'TableComponent') return isTableValueValid(node, value);\n if (value === undefined || value === null) return false;\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'string') return value.trim() !== '';\n return true;\n};\n/**\n * Checks required JSON fields in the dynamic form store.\n * Optional tier/variant scopes limit validation to the data being saved.\n */\nexport const areRequiredFieldsFilled = (\n jsonSchema: any,\n tierVariantMap: Map<string, Map<number, any>>,\n activeTierKeys?: Iterable<string>,\n activeVariantIndexes?: Iterable<number>\n): boolean => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n const schemaProperties = jsonSchema?.properties;\n if (!schemaProperties) return false;\n const activeTierKeySet = activeTierKeys ? new Set(activeTierKeys) : null;\n const activeVariantIndexSet = activeVariantIndexes ? new Set(activeVariantIndexes) : null;\n let allFilled = true;\n const traverseSchema = (properties: any, tierKey?: string, variantIndex?: number) => {\n if (!properties) return;\n Object.entries(properties).forEach(([, node]: [string, any]) => {\n if (node.ui_only && isVariantWrapper(node)) return;\n if (node.data_key && node.is_required) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, tierKey !== undefined);\n const value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey as string, variantIndex as number, cleanKey);\n if (!isFieldFilled(value, node)) allFilled = false;\n }\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, tierKey, variantIndex);\n }\n });\n };\n // Global fields, checked once.\n traverseSchema(schemaProperties);\n // Variant fields, checked once per tier/variantIndex pair actually in use.\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper?.properties) {\n tierVariantMap.forEach((variantMap, tierKey) => {\n if (activeTierKeySet && !activeTierKeySet.has(tierKey)) return;\n variantMap.forEach((_config, variantIndex) => {\n if (activeVariantIndexSet && !activeVariantIndexSet.has(variantIndex)) return;\n traverseSchema(variantWrapper.properties, tierKey, variantIndex);\n });\n });\n }\n return allFilled;\n};\n/**\n * Write an AI/C.A.R.E. response back into the dynamic store.\n *\n * The AI echoes the same PROPERTY KEYS we sent in `ui_state` (e.g. `rule_title`,\n * `wta`). For every schema leaf whose property key is present in `response`, we\n * write the value into the store slot (`data_key`) the field reads from — so the\n * RHS re-renders with the AI's value and the next payload build reflects it.\n * String-typed fields that carry a list (wta/wnta) may arrive as an array; we\n * join those to a single `\\n`-separated string to match the store's string shape.\n *\n * Where each key is read depends on where the writer put it (symmetry with\n * `generatePayloadFromSchema`):\n * - core_field leaves → top level of `response` (e.g. `response.wta`).\n * - non-core (learning_metadata) → under `response.learning_metadata.properties`.\n * For non-core we also tolerate older shapes on load/edit: a flat\n * `learning_metadata[propKey]`, or the legacy `{ type, title, value }` wrapper.\n *\n * Pass `tierKey`/`variantIndex` to hydrate a specific variant; omit them for the\n * global (non-variant) flow. `read_only` and `ui_only` leaves are never written\n * (host-owned values like Category/Sub-Category must survive the round-trip).\n */\nexport const applyResponseToStore = (\n jsonSchema: any,\n response: Record<string, any> | null | undefined,\n tierKey?: string,\n variantIndex?: number,\n // `hydrateAll` writes EVERY leaf (incl. non-AI fields like Category/Sub-Category).\n // Use it for the initial load/edit hydration from the fetched rule; the default\n // (live AI updates) only touches `ai_generated: true` leaves.\n // `variantOnly` skips the global pass entirely and writes only the variant\n // section — used when loading fetched variants so the API never fills global\n // fields (title/category), which are owned by the user + C.A.R.E.\n options?: { hydrateAll?: boolean; variantOnly?: boolean }\n) => {\n if (!response || typeof response !== 'object') return;\n const { setGlobalField, setVariantField, setGlobalReasoning, setVariantReasoning } =\n useDynamicFormStore.getState();\n const canWriteVariant = !!tierKey && variantIndex !== undefined;\n // Sentinel so we can distinguish \"key absent\" from \"key present but undefined\".\n const NOT_FOUND = Symbol('not-found');\n const metadataBag = response.learning_metadata?.properties ?? response.learning_metadata;\n // Core leaves may arrive under a looser name than the property key — see the\n // shared CORE_KEY_ALIASES table at the top of this file.\n const unwrapLegacyValue = (raw: any) =>\n raw && typeof raw === 'object' && !Array.isArray(raw) && 'value' in raw ? raw.value : raw;\n // Resolve the incoming value for a leaf, honoring core vs learning_metadata\n // placement and unwrapping the legacy `{ value }` shape when present. Initial\n // edit payloads from integrations may be flat API objects, so metadata leaves\n // also accept their `data_key` from either the metadata bag or that object.\n const readIncoming = (propKey: string, node: any, isCore: boolean): any => {\n if (isCore) {\n if (Object.prototype.hasOwnProperty.call(response, propKey)) return response[propKey];\n const alias = CORE_KEY_ALIASES[propKey]?.find((key) =>\n Object.prototype.hasOwnProperty.call(response, key)\n );\n return alias ? response[alias] : NOT_FOUND;\n }\n const dataKey = node.data_key?.replace('global.', '');\n for (const source of [metadataBag, response]) {\n if (!source || typeof source !== 'object') continue;\n if (propKey in source) return unwrapLegacyValue((source as any)[propKey]);\n if (dataKey && dataKey in source) return unwrapLegacyValue((source as any)[dataKey]);\n }\n return NOT_FOUND;\n };\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // Backward compatibility for DTs that still carry `ui_only: true` on a\n // repeatable array. Its data_key is the persisted array slot.\n if (node.ui_only && !isRepeatableSection(node)) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n // A leaf is hydrated from the response when the AI/system owns its value —\n // `ai_generated: true` (incl. read_only system fields like `value_id`, a\n // pipeline-resolved id the AI echoes back — we just store + re-send it) — or on\n // `hydrateAll` (initial load/edit seeds every leaf from the fetched rule). Plain\n // user-owned leaves (not ai_generated) are set immediately from input and are\n // never waited on or overwritten by the AI. `readIncoming` returns NOT_FOUND\n // when the response omits the key, so a field the AI doesn't send is untouched.\n if (node.data_key && (node.ai_generated === true || options?.hydrateAll)) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n let incoming = readIncoming(propKey, node, !!node.core_field);\n if (incoming !== NOT_FOUND) {\n // Normalize a list-shaped payload back into a \\n-joined string for\n // string leaves (wta/wnta), whose store slot holds a single string.\n if (node.type !== 'array' && Array.isArray(incoming)) {\n incoming = incoming.join('\\n');\n }\n if (incoming !== undefined) {\n // ConditionSection leaves (wta/wnta) can hold MANY conditions, each with\n // its own inline <ai_reasoning>. A single reasoning slot can't hold N of\n // them, so we keep the raw string (tags inline) and let the field parse\n // per-condition reasoning. Learning metadata is also kept verbatim:\n // instruction prompts may intentionally use these tags as prompt content.\n // Only single-value core fields (title/goal) move their reasoning into the\n // parallel reasoning bucket.\n const isConditionField = node.bpa_ui_component === 'ConditionSection';\n let reasoningRaw: string | null = null;\n if (\n node.core_field &&\n !isConditionField &&\n typeof incoming === 'string' &&\n incoming.includes('<ai_reasoning>')\n ) {\n const stripped = stripAiReasoning(incoming);\n incoming = stripped.clean;\n reasoningRaw = stripped.raw;\n }\n // Write it into the store under the data_key.\n if (isGlobal) {\n setGlobalField(cleanKey, incoming);\n if (reasoningRaw) setGlobalReasoning(cleanKey, reasoningRaw);\n } else if (canWriteVariant) {\n setVariantField(tierKey as string, variantIndex as number, cleanKey, incoming);\n if (reasoningRaw)\n setVariantReasoning(\n tierKey as string,\n variantIndex as number,\n cleanKey,\n reasoningRaw\n );\n }\n }\n }\n }\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // Global pass — skipped for a variant-only hydrate (the API load).\n if (!options?.variantOnly) traverseSchema(schemaProperties, false);\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n};\n"],"names":["useDynamicFormStore","stripAiReasoning","isTableValueValid","_a","_b"],"mappings":";;;;;;;;AAoBA,MAAM,YAAA,GAAe,CAAC,OAAA,EAAiB,cAA6B,MAAA;AAAA,EAClE,QAAU,EAAA,OAAA,CAAQ,OAAQ,CAAA,SAAA,EAAW,EAAE,CAAA;AAAA,EACvC,QAAU,EAAA,OAAA,CAAQ,UAAW,CAAA,SAAS,KAAK,CAAC,cAAA;AAC9C,CAAA,CAAA,CAAA;AAOA,MAAM,mBAAmB,CAAC,IAAA,KAAA,CACxB,6BAAM,qBAA0B,MAAA,IAAA,IAAA,CAAQ,6BAAM,gBAAqB,MAAA,oBAAA,CAAA;AAIrE,MAAM,sBAAsB,CAAC,IAAA,KAAA,CAC3B,6BAAM,UAAe,MAAA,IAAA,IAAA,CAAQ,6BAAM,gBAAqB,MAAA,mBAAA,CAAA;AAE7C,MAAA,uBAAA,GAA0B,CAAC,UAAA,EAA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,cAAA,CAAA,IAAA,CAAK,YAAY,cAAc,CAAA,CAAA;AAAA,OAChD;AAAA,KACD,CAAA,CAAA;AAAA,GACH,CAAA;AACA,EAAM,MAAA,gBAAA,GAAA,CAAmB,UAAY,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,UAAA,CAAA,UAAA,KAAc,EAAC,CAAA;AAEpD,EAAA,IAAI,EAAC,OAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,OAAA,CAAS,WAAa,CAAA,EAAA,cAAA,CAAe,kBAAkB,KAAK,CAAA,CAAA;AACjE,EAAA,MAAM,iBAAsB,MAAO,CAAA,MAAA,CAAO,gBAAgB,CAAA,CAAE,KAAK,gBAAgB,CAAA,CAAA;AACjF,EAAI,IAAA,cAAA,IAAkB,eAAe,UAAY,EAAA;AAC/C,IAAe,cAAA,CAAA,cAAA,CAAe,YAAY,IAAI,CAAA,CAAA;AAAA,GAChD;AACF;;;;;;;;;;"}
1
+ {"version":3,"file":"PayloadUtils.js","sources":["../../../../src/schema-driven/utils/PayloadUtils.ts"],"sourcesContent":["// src/schema-driven/utils/PayloadUtils.ts\nimport { useDynamicFormStore } from '../store/useDynamicFormStore';\nimport { isTableValueValid } from '../helper';\nimport { stripAiReasoning } from './aiReasoning';\n/**\n * Two distinct keys per schema leaf, and they are NOT interchangeable:\n * - PROPERTY KEY — the key under `properties` (e.g. `rule_title`, `wta`). This is\n * the ON-THE-WIRE key: what we send to the AI in `ui_state` and what the AI\n * echoes back in its response JSON.\n * - data_key — the internal dynamic-store slot the RHS field reads/writes\n * (e.g. `template_title`, `whenToApply`).\n * So the round-trip is: read store by data_key → emit under property key → AI\n * responds under property key → write store by data_key.\n *\n * Which store bucket a leaf lives in, mirrored by both read (generatePayloadFromSchema)\n * and write (applyResponseToStore) so the round-trip stays symmetric:\n * - `global.`-prefixed data_key, OR a field outside a variant wrapper → global.\n * - otherwise → variant-scoped (tierKey + variantIndex).\n * The data_key is stored WITHOUT the `global.` prefix (`cleanKey`).\n */\nconst resolveScope = (dataKey: string, isVariantLevel: boolean) => ({\n cleanKey: dataKey.replace('global.', ''),\n isGlobal: dataKey.startsWith('global.') || !isVariantLevel,\n});\n/**\n * A section is the repeatable-variant container if it renders as VariantListWrapper\n * OR is explicitly flagged `is_repeatable_variant: true`. Detection MUST match what\n * VariantListField renders per variant, so the store scope (global vs variant) and\n * the UI stay in sync. Its child leaves are variant-scoped; everything else is global.\n */\nconst isVariantWrapper = (node: any): boolean =>\n node?.is_repeatable_variant === true || node?.bpa_ui_component === 'VariantListWrapper';\n\n// Unlike a normal object wrapper, a repeatable section owns one array value. Its\n// descendants are an item template, not independent top-level payload fields.\nconst isRepeatableSection = (node: any): boolean =>\n node?.repeatable === true || node?.bpa_ui_component === 'RepeatableSection';\n\nexport const getVariantPrefilledData = (jsonSchema: any, prefilledData: Record<string, any>) => {\n const variantData: Record<string, Record<number, Record<string, any>>> = {};\n\n const traverse = (properties: any, isVariantLevel = false) => {\n if (!properties) return;\n Object.values(properties).forEach((node: any) => {\n const dataKey = node?.data_key;\n const cleanKey = dataKey?.replace('global.', '');\n const isVariantField = isVariantLevel && !dataKey?.startsWith('global.');\n\n if (isVariantField && Object.prototype.hasOwnProperty.call(prefilledData, cleanKey)) {\n variantData.tier_1 ??= {};\n variantData.tier_1[0] ??= {};\n variantData.tier_1[0][cleanKey] = prefilledData[cleanKey];\n }\n\n if (node?.properties) traverse(node.properties, isVariantLevel || isVariantWrapper(node));\n });\n };\n\n traverse(jsonSchema?.properties);\n return variantData;\n};\n\n/**\n * A core leaf's value may arrive under a looser name than the property key:\n * - from the AI's `updated_fields` (e.g. `title` for `rule_title`), or\n * - from the rule-fetch API on load, which uses its own fixed field names\n * (`ruleTitle`, `description`, `whenToApply`, `whenNotToApply`).\n * Read those aliases without changing the canonical wire key we emit. Keys here\n * are the conventional property keys; a schema using different keys would extend this.\n * Shared by `applyResponseToStore` (store hydration) and `buildFieldLabelMap`\n * (chat labels) so both resolve the AI's key names the same way.\n */\nexport const CORE_KEY_ALIASES: Record<string, string[]> = {\n rule_title: ['title', 'ruleTitle'],\n rule_description: ['description', 'variant_description'],\n wta: ['whenToApply', 'when_to_apply'],\n wnta: ['whenNotToApply', 'when_not_to_apply'],\n};\n\n/**\n * Build the AI-key → user-facing-label map for the schema-driven flow.\n *\n * The C.A.R.E. response echoes schema PROPERTY KEYS (or their `CORE_KEY_ALIASES`)\n * in `updated_fields` / `identified_fields`. The chat renderer must label those\n * with the same title the RHS form shows, and the JSON owns that title\n * (`rule_title` → \"Template Title\", `rule_description` → \"Template Goal\", …),\n * so it is derived here instead of being hardcoded in the renderer.\n *\n * Every leaf that carries a `title` contributes an entry under its property key\n * plus each of its aliases, so `title`, `rule_title` and `ruleTitle` all resolve\n * to the same label. Only the schema-driven modal passes this map down; the\n * legacy flow keeps the renderer's built-in defaults.\n */\nexport const buildFieldLabelMap = (jsonSchema: any): Record<string, string> => {\n const labels: Record<string, string> = {};\n const traverseSchema = (properties: any) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // `ui_only` wrappers (sections/rows) carry no value of their own, but their\n // children do — so recurse through them and only record leaf titles.\n if (node?.data_key && node?.title) {\n labels[propKey] = node.title;\n CORE_KEY_ALIASES[propKey]?.forEach((alias) => {\n labels[alias] = node.title;\n });\n }\n if (node?.properties) traverseSchema(node.properties);\n });\n };\n traverseSchema(jsonSchema?.properties);\n return labels;\n};\n\nexport const generatePayloadFromSchema = (\n jsonSchema: any,\n tierKey: string,\n variantIndex: number\n) => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n\n // `core_field: true` leaves sit at the top level of the payload; everything\n // else is collected under `learning_metadata`.\n const rootPayload: any = {};\n const metadataProperties: any = {};\n const metadataRequired: string[] = [];\n // Property keys whose value came from the per-variant store slot (getVariantField),\n // as opposed to the global slot shared across every variant. Callers that merge this\n // metadata bag with a variant's own API-saved metadata need this to know which keys\n // must always take the live store value (e.g. instruction_prompt) vs. which are fine\n // to let the API snapshot win (e.g. category).\n const variantScopedMetadataKeys: string[] = [];\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // A repeatable node is a value-bearing array even if older DTs left\n // `ui_only: true` on it. Treat it as the array field, never as a wrapper\n // whose item-template leaves should be emitted as flat metadata.\n if (node.ui_only && !isRepeatableSection(node)) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n if (node.data_key) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n // A repeatable section owns an array under its data_key. Unlike ordinary\n // fields, its config property key may be an implementation-generated id,\n // so use the data_key as its stable wire/payload key.\n const payloadKey = isRepeatableSection(node) ? cleanKey : propKey;\n let value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey, variantIndex, cleanKey);\n // ALWAYS provide a fallback default so the AI sees the empty keys\n // (it needs the previous value to reason about the user's request).\n if (value === undefined) {\n if (node.type === 'array') value = [];\n else if (node.type === 'boolean') value = false;\n else if (node.type === 'object') value = {};\n else value = ''; // default string (incl. \\n-joined wta/wnta)\n }\n // Cognitive reasoning belongs to the core, AI-managed rule fields only.\n // Learning metadata (including `instruction_prompt`) is user-owned content\n // and can intentionally contain an `<ai_reasoning>` block, so preserve it\n // verbatim when it is sent back in `ui_state`.\n if (node.core_field && typeof value === 'string' && value.includes('<ai_reasoning>')) {\n value = stripAiReasoning(value).clean;\n }\n // Emit under the PROPERTY KEY (the AI's wire key), not the data_key.\n if (node.core_field) {\n rootPayload[payloadKey] = value;\n } else {\n metadataProperties[payloadKey] = value;\n // `required` is derived from each field's `is_required` flag in the JSON.\n if (node.is_required && !metadataRequired.includes(payloadKey)) {\n metadataRequired.push(payloadKey);\n }\n if (!isGlobal) variantScopedMetadataKeys.push(payloadKey);\n }\n }\n // Recursively traverse object properties\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // 1. Traverse global properties\n traverseSchema(schemaProperties, false);\n // 2. Traverse variant properties\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n const learningMetadata = { properties: metadataProperties, required: metadataRequired };\n return { rootPayload, learningMetadata, variantScopedMetadataKeys };\n};\n/**\n * PROPERTY KEYS that hand ownership of the ruleset id to a form field. In the\n * JSON-driven flow the Sub-Category dropdown carries it (`ruleset_id`), so\n * whichever sub-category the user picks decides which ruleset the template is\n * saved into. `scope_id` is accepted as the same thing under the BE's name.\n */\nconst RULE_SET_ID_PROPERTY_KEYS = ['ruleset_id', 'scope_id'];\n\n/** First leaf (depth-first) whose property key hands over the ruleset id. */\nconst findRuleSetIdNode = (properties: any): any => {\n if (!properties) return null;\n for (const [propKey, node] of Object.entries<any>(properties)) {\n if (RULE_SET_ID_PROPERTY_KEYS.includes(propKey) && node?.data_key) return node;\n const nested = findRuleSetIdNode(node?.properties);\n if (nested) return nested;\n }\n return null;\n};\n\n/**\n * Options for a leaf, resolved exactly like DropdownSectionField renders them:\n * host-injected `dynamicOptions[<dynamic_options_key | data_key + 'Options'>]`\n * wins when non-empty, then inline `options`, then `enum`. Keeping the two in\n * sync matters — the id we return must come from the option the user saw.\n */\nconst resolveNodeOptions = (node: any, dynamicOptions?: Record<string, any>): any[] => {\n const optionsKey = node?.dynamic_options_key || `${node?.data_key}Options`;\n const hostOptions = dynamicOptions?.[optionsKey];\n if (Array.isArray(hostOptions) && hostOptions.length > 0) return hostOptions;\n if (Array.isArray(node?.options)) return node.options;\n if (Array.isArray(node?.enum)) {\n return node.enum.map((opt: any) =>\n opt && typeof opt === 'object' ? opt : { label: String(opt), value: opt }\n );\n }\n return [];\n};\n\n/**\n * The ruleset id the SCHEMA selects, or null when it doesn't select one.\n *\n * The dynamic store holds a dropdown's `value` (e.g. `weekly_digest`), never the\n * backing id — that travels on the option itself (`{ id, label, value }`, from\n * `dynamicOptions` or from inline JSON options that carry an `id`). So: find the\n * `ruleset_id`/`scope_id` leaf, read its store value, and return the id of the\n * option currently selected in it.\n *\n * Null means \"the schema has no opinion\" and the caller keeps whatever ruleset\n * it already used — that's the case for a schema without such a leaf, nothing\n * picked yet, or an option without an id. Only GLOBAL store values are read: a\n * ruleset is a per-template choice, not a per-variant one.\n */\nexport const resolveSchemaRuleSetId = (\n jsonSchema: any,\n dynamicOptions?: Record<string, any>\n): string | null => {\n const node = findRuleSetIdNode(jsonSchema?.properties);\n if (!node) return null;\n\n // `cleanKey` — the store slot, with any `global.` data_key prefix stripped.\n const { cleanKey } = resolveScope(node.data_key, false);\n const value = useDynamicFormStore.getState().getGlobalField(cleanKey);\n if (!value) return null;\n\n // The API may hydrate a value with different casing from the dropdown option\n // (for example, `nyc` vs. `NYC`). Match strings case-insensitively, while\n // returning the option's UUID — never its display/value token.\n const normalizedValue = typeof value === 'string' ? value.trim().toLowerCase() : value;\n const selected = resolveNodeOptions(node, dynamicOptions).find((opt: any) => {\n const optionValue =\n typeof opt?.value === 'string' ? opt.value.trim().toLowerCase() : opt?.value;\n return optionValue === normalizedValue;\n });\n return selected?.id ?? null;\n};\n\nconst isFieldFilled = (value: any, node?: any): boolean => {\n if (node?.bpa_ui_component === 'TableComponent') return isTableValueValid(node, value);\n if (value === undefined || value === null) return false;\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'string') return value.trim() !== '';\n return true;\n};\n/**\n * Checks required JSON fields in the dynamic form store.\n * Optional tier/variant scopes limit validation to the data being saved.\n */\nexport const areRequiredFieldsFilled = (\n jsonSchema: any,\n tierVariantMap: Map<string, Map<number, any>>,\n activeTierKeys?: Iterable<string>,\n activeVariantIndexes?: Iterable<number>\n): boolean => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n const schemaProperties = jsonSchema?.properties;\n if (!schemaProperties) return false;\n const activeTierKeySet = activeTierKeys ? new Set(activeTierKeys) : null;\n const activeVariantIndexSet = activeVariantIndexes ? new Set(activeVariantIndexes) : null;\n let allFilled = true;\n const traverseSchema = (properties: any, tierKey?: string, variantIndex?: number) => {\n if (!properties) return;\n Object.entries(properties).forEach(([, node]: [string, any]) => {\n if (node.ui_only && isVariantWrapper(node)) return;\n if (node.data_key && node.is_required) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, tierKey !== undefined);\n const value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey as string, variantIndex as number, cleanKey);\n if (!isFieldFilled(value, node)) allFilled = false;\n }\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, tierKey, variantIndex);\n }\n });\n };\n // Global fields, checked once.\n traverseSchema(schemaProperties);\n // Variant fields, checked once per tier/variantIndex pair actually in use.\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper?.properties) {\n tierVariantMap.forEach((variantMap, tierKey) => {\n if (activeTierKeySet && !activeTierKeySet.has(tierKey)) return;\n variantMap.forEach((_config, variantIndex) => {\n if (activeVariantIndexSet && !activeVariantIndexSet.has(variantIndex)) return;\n traverseSchema(variantWrapper.properties, tierKey, variantIndex);\n });\n });\n }\n return allFilled;\n};\n/**\n * Write an AI/C.A.R.E. response back into the dynamic store.\n *\n * The AI echoes the same PROPERTY KEYS we sent in `ui_state` (e.g. `rule_title`,\n * `wta`). For every schema leaf whose property key is present in `response`, we\n * write the value into the store slot (`data_key`) the field reads from — so the\n * RHS re-renders with the AI's value and the next payload build reflects it.\n * String-typed fields that carry a list (wta/wnta) may arrive as an array; we\n * join those to a single `\\n`-separated string to match the store's string shape.\n *\n * Where each key is read depends on where the writer put it (symmetry with\n * `generatePayloadFromSchema`):\n * - core_field leaves → top level of `response` (e.g. `response.wta`).\n * - non-core (learning_metadata) → under `response.learning_metadata.properties`.\n * For non-core we also tolerate older shapes on load/edit: a flat\n * `learning_metadata[propKey]`, or the legacy `{ type, title, value }` wrapper.\n *\n * Pass `tierKey`/`variantIndex` to hydrate a specific variant; omit them for the\n * global (non-variant) flow. `read_only` and `ui_only` leaves are never written\n * (host-owned values like Category/Sub-Category must survive the round-trip).\n */\nexport const applyResponseToStore = (\n jsonSchema: any,\n response: Record<string, any> | null | undefined,\n tierKey?: string,\n variantIndex?: number,\n // `hydrateAll` writes EVERY leaf (incl. non-AI fields like Category/Sub-Category).\n // Use it for the initial load/edit hydration from the fetched rule; the default\n // (live AI updates) only touches `ai_generated: true` leaves.\n // `variantOnly` skips the global pass entirely and writes only the variant\n // section — used when loading fetched variants so the API never fills global\n // fields (title/category), which are owned by the user + C.A.R.E.\n options?: { hydrateAll?: boolean; variantOnly?: boolean }\n) => {\n if (!response || typeof response !== 'object') return;\n const { setGlobalField, setVariantField, setGlobalReasoning, setVariantReasoning } =\n useDynamicFormStore.getState();\n const canWriteVariant = !!tierKey && variantIndex !== undefined;\n // Sentinel so we can distinguish \"key absent\" from \"key present but undefined\".\n const NOT_FOUND = Symbol('not-found');\n const metadataBag = response.learning_metadata?.properties ?? response.learning_metadata;\n // Core leaves may arrive under a looser name than the property key — see the\n // shared CORE_KEY_ALIASES table at the top of this file.\n const unwrapLegacyValue = (raw: any) =>\n raw && typeof raw === 'object' && !Array.isArray(raw) && 'value' in raw ? raw.value : raw;\n // Resolve the incoming value for a leaf, honoring core vs learning_metadata\n // placement and unwrapping the legacy `{ value }` shape when present. Initial\n // edit payloads from integrations may be flat API objects, so metadata leaves\n // also accept their `data_key` from either the metadata bag or that object.\n const readIncoming = (propKey: string, node: any, isCore: boolean): any => {\n if (isCore) {\n if (Object.prototype.hasOwnProperty.call(response, propKey)) return response[propKey];\n const alias = CORE_KEY_ALIASES[propKey]?.find((key) =>\n Object.prototype.hasOwnProperty.call(response, key)\n );\n return alias ? response[alias] : NOT_FOUND;\n }\n const dataKey = node.data_key?.replace('global.', '');\n for (const source of [metadataBag, response]) {\n if (!source || typeof source !== 'object') continue;\n if (propKey in source) return unwrapLegacyValue((source as any)[propKey]);\n if (dataKey && dataKey in source) return unwrapLegacyValue((source as any)[dataKey]);\n }\n return NOT_FOUND;\n };\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // Backward compatibility for DTs that still carry `ui_only: true` on a\n // repeatable array. Its data_key is the persisted array slot.\n if (node.ui_only && !isRepeatableSection(node)) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n // A leaf is hydrated from the response when the AI/system owns its value —\n // `ai_generated: true` (incl. read_only system fields like `value_id`, a\n // pipeline-resolved id the AI echoes back — we just store + re-send it) — or on\n // `hydrateAll` (initial load/edit seeds every leaf from the fetched rule). Plain\n // user-owned leaves (not ai_generated) are set immediately from input and are\n // never waited on or overwritten by the AI. `readIncoming` returns NOT_FOUND\n // when the response omits the key, so a field the AI doesn't send is untouched.\n if (node.data_key && (node.ai_generated === true || options?.hydrateAll)) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n let incoming = readIncoming(propKey, node, !!node.core_field);\n if (incoming !== NOT_FOUND) {\n // Normalize a list-shaped payload back into a \\n-joined string for\n // string leaves (wta/wnta), whose store slot holds a single string.\n if (node.type !== 'array' && Array.isArray(incoming)) {\n incoming = incoming.join('\\n');\n }\n if (incoming !== undefined) {\n // ConditionSection leaves (wta/wnta) can hold MANY conditions, each with\n // its own inline <ai_reasoning>. A single reasoning slot can't hold N of\n // them, so we keep the raw string (tags inline) and let the field parse\n // per-condition reasoning. Learning metadata is also kept verbatim:\n // instruction prompts may intentionally use these tags as prompt content.\n // Only single-value core fields (title/goal) move their reasoning into the\n // parallel reasoning bucket.\n const isConditionField = node.bpa_ui_component === 'ConditionSection';\n let reasoningRaw: string | null = null;\n if (\n node.core_field &&\n !isConditionField &&\n typeof incoming === 'string' &&\n incoming.includes('<ai_reasoning>')\n ) {\n const stripped = stripAiReasoning(incoming);\n incoming = stripped.clean;\n reasoningRaw = stripped.raw;\n }\n // Write it into the store under the data_key.\n if (isGlobal) {\n setGlobalField(cleanKey, incoming);\n if (reasoningRaw) setGlobalReasoning(cleanKey, reasoningRaw);\n } else if (canWriteVariant) {\n setVariantField(tierKey as string, variantIndex as number, cleanKey, incoming);\n if (reasoningRaw)\n setVariantReasoning(\n tierKey as string,\n variantIndex as number,\n cleanKey,\n reasoningRaw\n );\n }\n }\n }\n }\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // Global pass — skipped for a variant-only hydrate (the API load).\n if (!options?.variantOnly) traverseSchema(schemaProperties, false);\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n};\n"],"names":["useDynamicFormStore","stripAiReasoning","isTableValueValid","_a","_b"],"mappings":";;;;;;;;AAoBA,MAAM,YAAA,GAAe,CAAC,OAAA,EAAiB,cAA6B,MAAA;AAAA,EAClE,QAAU,EAAA,OAAA,CAAQ,OAAQ,CAAA,SAAA,EAAW,EAAE,CAAA;AAAA,EACvC,QAAU,EAAA,OAAA,CAAQ,UAAW,CAAA,SAAS,KAAK,CAAC,cAAA;AAC9C,CAAA,CAAA,CAAA;AAOA,MAAM,mBAAmB,CAAC,IAAA,KAAA,CACxB,6BAAM,qBAA0B,MAAA,IAAA,IAAA,CAAQ,6BAAM,gBAAqB,MAAA,oBAAA,CAAA;AAIrE,MAAM,sBAAsB,CAAC,IAAA,KAAA,CAC3B,6BAAM,UAAe,MAAA,IAAA,IAAA,CAAQ,6BAAM,gBAAqB,MAAA,mBAAA,CAAA;AAoCnD,MAAM,gBAA6C,GAAA;AAAA,EACxD,UAAA,EAAY,CAAC,OAAA,EAAS,WAAW,CAAA;AAAA,EACjC,gBAAA,EAAkB,CAAC,aAAA,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A,GAAA,OAAA,CAAS,WAAa,CAAA,EAAA,cAAA,CAAe,kBAAkB,KAAK,CAAA,CAAA;AACjE,EAAA,MAAM,iBAAsB,MAAO,CAAA,MAAA,CAAO,gBAAgB,CAAA,CAAE,KAAK,gBAAgB,CAAA,CAAA;AACjF,EAAI,IAAA,cAAA,IAAkB,eAAe,UAAY,EAAA;AAC/C,IAAe,cAAA,CAAA,cAAA,CAAe,YAAY,IAAI,CAAA,CAAA;AAAA,GAChD;AACF;;;;;;;;;"}
@@ -47,6 +47,7 @@ function LearningManagement({
47
47
  cognitiveCompareCompatibility = false,
48
48
  enableChatLogs,
49
49
  initialAddChatMessage,
50
+ autoOpenTeachMe,
50
51
  modeId,
51
52
  modeDetails,
52
53
  pluginPayload,
@@ -161,6 +162,7 @@ function LearningManagement({
161
162
  isPublishedReadOnly ? `published:${version != null ? version : ""}` : "sandbox"
162
163
  ].join("|");
163
164
  const [loadedScopeRequestKey, setLoadedScopeRequestKey] = useState(null);
165
+ const autoOpenTeachMeHandledRef = useRef(null);
164
166
  useRef(null);
165
167
  const pendingScopeIdRef = useRef(null);
166
168
  const hasHydratedFromUrl = useRef(false);
@@ -225,6 +227,30 @@ function LearningManagement({
225
227
  writeQueryParams({ [QUERY_PARAM_KEYS.RULESET_ID]: selectedRuleSetId });
226
228
  }
227
229
  }, [selectedRuleSetId, writeQueryParams]);
230
+ useEffect(() => {
231
+ if (!(autoOpenTeachMe == null ? void 0 : autoOpenTeachMe.scopeId) || !(scopeTreeData == null ? void 0 : scopeTreeData.data) || isLoading || isPublishedReadOnly) return;
232
+ if (autoOpenTeachMeHandledRef.current === autoOpenTeachMe.scopeId) return;
233
+ const requestedScope = findNodeById(scopeTreeData.data, autoOpenTeachMe.scopeId);
234
+ if (!requestedScope) {
235
+ console.warn(`autoOpenTeachMe: scope '${autoOpenTeachMe.scopeId}' was not found in the loaded scope tree.`);
236
+ autoOpenTeachMeHandledRef.current = autoOpenTeachMe.scopeId;
237
+ return;
238
+ }
239
+ if (requestedScope.hasAccess === false) {
240
+ console.warn(`autoOpenTeachMe: access to scope '${autoOpenTeachMe.scopeId}' is unavailable.`);
241
+ autoOpenTeachMeHandledRef.current = autoOpenTeachMe.scopeId;
242
+ return;
243
+ }
244
+ const canCreateLearning = hasPermission("ilotj.rule.create", requestedScope.id) || hasPermission("ilotj.rule.variant.create", requestedScope.id);
245
+ if (!canCreateLearning) {
246
+ console.warn(`autoOpenTeachMe: create permission is unavailable for scope '${autoOpenTeachMe.scopeId}'.`);
247
+ autoOpenTeachMeHandledRef.current = autoOpenTeachMe.scopeId;
248
+ return;
249
+ }
250
+ autoOpenTeachMeHandledRef.current = autoOpenTeachMe.scopeId;
251
+ setSelectedRuleSetId(requestedScope.id);
252
+ setActiveSectionId(defaultSectionId);
253
+ }, [autoOpenTeachMe, scopeTreeData, isLoading, isPublishedReadOnly, setSelectedRuleSetId, defaultSectionId]);
228
254
  useEffect(() => {
229
255
  var _a2;
230
256
  if (pluginPayload == null ? void 0 : pluginPayload.learningManagement) {
@@ -818,6 +844,7 @@ function LearningManagement({
818
844
  publishedEditStatus,
819
845
  publishedVersion: isPublishedReadOnly ? version : void 0,
820
846
  initialAddChatMessage,
847
+ autoOpenTeachMe,
821
848
  menuActionsConfig: resolvedMenuActionsConfig
822
849
  }
823
850
  ) }),