# WP Agentic Writer – Master Migration Blueprint This document maps the entire 12,364-line `sidebar.js` monolith to a modular React architecture. **Rule #1 of this migration:** Do not guess UI or logic. Every component must be ported 1:1 using the exact SVG paths, class names, state transitions, and DOM interactions found in the legacy file. --- ## 1. State Inventory & Context Architecture The legacy file uses over 50 `useState` and `useRef` hooks in a single component. These must be split into specific Context Providers to avoid massive re-renders and prop drilling. ### 🗂️ `SessionContext` (Session & Tab Locking) - `currentSessionId`, `availableSessions`, `isSessionActionLoading` - `sessionLock`, `lockHeartbeatRef`, `tabIdRef` (Multi-tab concurrency locks) - `isHydratingSessionRef`, `memantoRestore`, `memantoRestoreFetchedRef` - *Dependencies:* Needs `window.beforeunload` listeners and `setInterval` for heartbeat. ### 💬 `ChatContext` (Messages & Input) - `messages`, `isLoading`, `showWelcome`, `welcomeKeywordInput`, `welcomeStartMode` - `input`, `isTextareaExpanded`, `inputRef`, `streamTargetRef` - `messagesSaveTimeoutRef`, `lastPersistedMessagesRef` - `inClarification`, `questions`, `currentQuestionIndex`, `answers`, `detectedLanguage`, `clarificationMode` - `focusKeywordSuggestions`, `selectedFocusKeyword`, `showCustomKeywordInput`, `customKeywordInput` ### 🤖 `AgentContext` (Agent Execution & Plans) - `agentMode` (chat, planning, writing) - `activeOperation`, `executionStopped`, `stopExecutionRef` - `activeAbortControllerRef`, `activeReaderRef` - `lastGenerationRequestRef`, `lastExecuteRequestRef`, `lastRefineRequestRef`, `lastChatRequestRef` - `writingState`, `isWritingStateLoading`, `currentPlanRef` - `sectionInsertIndexRef`, `activeSectionIdRef`, `sectionBlocksRef`, `blockSectionRef` ### 📝 `EditorContext` (WP Block Bridge & Locks) - `isEditorLocked`, `isRefinementLocked`, `refiningBlockIds` - `lockedEditableNodesRef`, `lockedBlockIdsRef`, `refinementDecoratedIdsRef` - `workspaceSnapshot`, `isWorkspaceCollapsed` - `aiUndoStack` (MAX_UNDO_STACK) - `pendingRefinement`, `pendingEditPlan`, `pendingDiffBlockIds` - `refineAllConfirm`, `refineAllConfirmResolverRef`, `skipRefineAllConfirmRef` ### ⚙️ `SettingsContext` (Config, Cost, SEO) - `postConfig`, `isConfigLoading`, `isConfigSaving`, `configError` - `cost`, `monthlyBudget`, `providerInfo` - `seoAudit`, `isSeoAuditing`, `isGeneratingMeta`, `activeSeoFixKey` --- ## 2. WordPress API Bridge All `wp.*` calls must be abstracted into dedicated hooks/services so components remain clean. * `wp.data.select('core/editor')`: `getCurrentPostId`, `getBlocks`, `getEditedPostAttribute` * `wp.data.dispatch('core/editor')`: `updateBlockAttributes`, `replaceBlocks`, `insertBlocks`, `removeBlocks`, `editPost` * `wp.data.subscribe`: Block mutation listeners (`blockMutationEvent`). * `wp.element`: `createElement`, `useState`, `useEffect`, `useCallback`, `useRef`, `useMemo` * `wp.components`: `Panel`, `TextControl`, `TextareaControl`, `CheckboxControl`, `Button` * **Custom DOM Manipulation:** The legacy code manipulates the DOM directly (e.g., locking `.editor-styles-wrapper [contenteditable="true"]`). This needs a safe `useEditorLock` hook. --- ## 3. UI Component Mapping Exact mapping of legacy `render*` functions to new components. *Note: Copy exact HTML structures, SVGs, and class names from legacy.* ### Layout & Shell * `AgenticWriterSidebar` → `src/components/Sidebar.jsx` * `renderGlobalStatusBar` → `src/components/shell/StatusBar.jsx` (Contains ALL main navigation icons) ### Tab: Chat (`renderChatTab`) * `renderWelcomeScreen` → `src/components/chat/WelcomeScreen.jsx` * `renderWritingEmptyState` → `src/components/chat/WritingEmptyState.jsx` * `renderFocusKeywordBar` → `src/components/chat/FocusKeywordBar.jsx` * `renderMessages` → `src/components/chat/MessageList.jsx` * `renderMessageContent` → `src/components/chat/MessageItem.jsx` * `inlineMarkdownToHtml` / `markdownToHtml` → `src/utils/markdownRenderer.js` * `renderAgentWorkspaceCard` → `src/components/chat/AgentWorkspaceCard.jsx` * `renderContextIndicator` → `src/components/chat/ContextIndicator.jsx` * `renderContextualAction` → `src/components/chat/ContextualActions.jsx` * `renderClarification` → `src/components/chat/ClarificationOverlay.jsx` * *(Chat Input)* → `src/components/chat/ChatInput.jsx` ### Tab: Config (`renderConfigTab`) * `renderConfigTab` → `src/components/config/ConfigTab.jsx` ### Tab: Cost (`renderCostTab`) * `renderCostTab` → `src/components/cost/CostTab.jsx` ### Shared / Modals / Overlays * `renderRefineAllConfirmModal` → `src/components/shared/RefineConfirmModal.jsx` * Mentions (`showMentionAutocomplete`) → `src/components/editor/MentionAutocomplete.jsx` * Slash Commands (`showSlashAutocomplete`) → `src/components/editor/SlashCommandMenu.jsx` --- ## 4. Business Logic & Feature Epics (Migration Phases) ### Epic 1: Session & Shell Initialization - [ ] Connect `wp.data` to fetch Post ID. - [ ] Implement multi-tab session locking (`acquireSessionLock`, `releaseSessionLock`, `startLockHeartbeat`). - [ ] Implement session persistence and hydration (`loadPostSessions`, `hydrateSessionStateFromMessages`, `flushOnUnload`). - [ ] Build the shell: `Sidebar`, `StatusBar` (with exact SVGs for Chat, Config, Cost, Undo, Session List). ### Epic 2: Core Chat & UI - [ ] Port `WelcomeScreen` (Exact UI: Agentic Writer title, pill buttons, focus keyword). - [ ] Port `ChatInput` (Auto-expanding textarea, slash/mention triggers). - [ ] Port `MessageList` and custom Markdown Renderer (MUST support syntax highlighting, links, lists exactly as legacy). - [ ] Implement `sendMessage` basic streaming to API. ### Epic 3: Mentions & Slash Commands - [ ] Port `extractMentionsFromText`, `resolveBlockMentions`. - [ ] Port the visual UI for `@` block selection (showing block content previews). - [ ] Port `/` command definitions (`parseInsertCommand`, `getSlashOptions`). ### Epic 4: AI Editor Actions & Undo Stack - [ ] Implement Editor Lock hook (`shouldBlockEditorInput`, blocking keydown events). - [ ] Implement `aiUndoStack` (`captureEditorSnapshot`, `pushUndoSnapshot`, `undoLastAiOperation`). - [ ] Port Refinement Actions (`handleChatRefinement`, `handleTitleRefinement`). - [ ] Port Diff rendering logic (handling insertions/replacements). ### Epic 5: The Agentic Planner - [ ] Port `streamGeneratePlan` and `executePlanFromCard`. - [ ] Port section block management (`loadSectionBlocks`, `saveSectionBlocks`, `upsertSectionBlock`). - [ ] Port workspace logic (`buildWorkspaceSnapshot`, `toggleAgentWorkspace`). ### Epic 6: SEO & Utilities - [ ] Port `runSeoAudit` and `handleSeoAuditFix`. - [ ] Port `generateMetaDescription`. - [ ] Port `savePostConfig`, `updatePostConfig`. --- ## 5. Execution Rules for Claude 1. **Never guess the DOM:** When porting a `renderX` function, grep the legacy `sidebar.js` for that function, copy its exact element structure, and translate it to JSX. 2. **Preserve CSS hooks:** Do not rename classes. If a legacy element has `.wpaw-status-icon-btn`, use exactly that. 3. **Migrate one slice at a time:** e.g., Set up Contexts first, then `StatusBar`, then `WelcomeScreen`. Do not jump around. 4. **Test integrations locally:** Verify that WordPress `wp.data` and `wp.element` resolve correctly after Webpack compilation.