# Phase 4 Plan 2: Design React JamTrack Architecture

<objective>
Design comprehensive React component architecture, Redux state structure, and implementation roadmap for Phase 5 JamTrack migration.
</objective>

<execution_context>
@.planning/codebase/JAMTRACK_LEGACY.md
@.planning/codebase/JAMTRACK_API.md
@.planning/codebase/JAMTRACK_REACT_PATTERNS.md
@.planning/phases/03-backing-track-finalization/03-03-SUMMARY.md
@jam-ui/src/components/client/JKSessionBackingTrackPlayer.js
@jam-ui/src/store/features/mediaSlice.js
@jam-ui/src/store/features/sessionUISlice.js
@jam-ui/src/hooks/useMediaActions.js
</execution_context>

<context>
## Background

**Completed Work:**
- Phase 3: Backing Track Player with Redux integration
- Plan 04-01: Legacy documentation and API reference

**Established Patterns:**
- Component structure: Modal → Player → Session View
- Redux slices: mediaSlice (data), sessionUISlice (UI state), activeSessionSlice (session data)
- Async operations: Redux thunks wrapping jamClient calls
- Real-time updates: WebSocket → Redux dispatch
- Error handling: Type-specific errors with retry capabilities

## Phase 4 Plan 2 Goal

Create detailed architecture design for JamTrack React components that:
1. Follows established Backing Track patterns
2. Handles JamTrack-specific complexity (mixdown selection, download/sync, JMEP)
3. Defines clear Redux state structure
4. Provides actionable implementation roadmap for Phase 5

## Key Challenges

1. **Mixdown Complexity**: JamTracks support multiple playback modes (master, custom mixes, individual stems)
2. **Download/Sync State**: 8-state synchronization engine must translate to React/Redux
3. **JMEP Loading**: Tempo/pitch modifications require special handling
4. **Sample Rate Handling**: fqId format depends on native client sample rate
5. **WebSocket Integration**: JAM_TRACK_CHANGES real-time updates for playback state
</context>

<tasks>
### Task 1: Design Component Structure

**type:** auto

**files:**
- CREATE `.planning/phases/04-jamtrack-research-design/COMPONENT_DESIGN.md`

**action:**
Design complete React component architecture for JamTrack functionality:

1. **JKSessionJamTrackPlayer Component** (NEW - primary deliverable)
   - Purpose: Full-featured JamTrack player with playback controls
   - Rendering modes: Modal and Popup (follow Backing Track pattern)
   - Props interface:
     - `isOpen`, `onClose`, `jamTrack`, `jamClient`, `session`, `currentUser`, `isPopup`
   - State management:
     - Local state: isPlaying, isPaused, currentPosition, duration, isLoading, error, selectedMixdown
     - Redux state: jamTrackState, mixdowns, downloadState
   - Sub-components:
     - Mixdown selector dropdown (master/custom mixes/stems)
     - Playback controls (play/pause/stop)
     - Seek bar with position display
     - Download/sync progress indicator
     - Error banner with retry

2. **JKSessionJamTrackModal Component** (EXISTS - may need updates)
   - Current: Selection UI with search/pagination
   - Potential updates: Add download state indicators, mixdown preview
   - Integration: Callback pattern → dispatch loadJamTrack

3. **JKSessionJamTrackStems Component** (EXISTS - verify completeness)
   - Purpose: Display JamTrack stem tracks in session mixer view
   - Props: jamTrackStems, mixerHelper
   - Verify: Supports all mixer operations (volume, pan, mute, solo)

4. **Component Hierarchy**
   ```
   JKSessionScreen
   ├── JKSessionJamTrackModal (selection)
   │   └── onSelect → dispatch loadJamTrack()
   ├── JKSessionJamTrackPlayer (playback controls)
   │   ├── MixdownSelector
   │   ├── PlaybackControls
   │   ├── SeekBar
   │   └── DownloadProgress
   └── JKSessionJamTrackStems (mixer view)
       └── SessionTrackVU, SessionTrackGain (per stem)
   ```

5. **Props vs Redux Decision Matrix**
   | Data | Storage | Rationale |
   |------|---------|-----------|
   | jamClient | Props | Non-serializable |
   | session, currentUser | Props | Parent context |
   | isOpen, isPopup | Props | Parent controls visibility |
   | jamTrack data | Redux (media.jamTracks) | WebSocket updates |
   | jamTrackState | Redux (media.jamTrackState) | Real-time playback state |
   | selectedMixdown | Local state | Player-specific UI state |
   | downloadState | Redux (media.downloadState) | Shared across components |
   | error | Local state | Player-specific errors |

6. **Comparison to Backing Track Player**
   | Feature | Backing Track | JamTrack | Notes |
   |---------|---------------|----------|-------|
   | File selection | Native dialog | Modal selection | Different patterns |
   | Playback controls | play/pause/stop/seek | Same + mixdown selector | JamTrack adds dropdown |
   | Duration loading | Single async call | May need sync check | JamTrack download state |
   | Volume control | SessionSetTrackVolumeData | Same (per stem) | Mixer integration |
   | Loop control | SessionSetBackingTrackFileLoop | TBD if supported | Check jamClient API |
   | Error types | file, network, playback, general | Same + download, sync | JamTrack adds download errors |

**verify:**
- COMPONENT_DESIGN.md created with all 6 sections
- Component hierarchy diagram included
- Props interfaces defined with types
- Redux vs local state decisions documented
- Comparison table to Backing Track complete

**done:**
Component architecture designed with clear interfaces and data flow patterns.

---

### Task 2: Design Redux State Structure

**type:** auto

**files:**
- CREATE `.planning/phases/04-jamtrack-research-design/REDUX_DESIGN.md`

**action:**
Design comprehensive Redux state structure for JamTrack functionality:

1. **mediaSlice Extensions**
   ```javascript
   {
     backingTracks: [],        // Existing
     jamTracks: [],            // Existing - extend structure
     recordedTracks: [],       // Existing
     metronome: null,          // Existing

     // NEW: JamTrack-specific state
     jamTrackState: {
       isPlaying: false,
       isPaused: false,
       currentPositionMs: 0,
       durationMs: 0,
       selectedMixdownId: null,
       playbackMode: 'master'  // 'master' | 'custom-mix' | 'stem'
     },

     // NEW: Download/sync state
     downloadState: {
       jamTrackId: null,
       mixdownId: null,
       state: 'idle',  // 'idle' | 'checking' | 'downloading' | 'keying' | 'synchronized' | 'error'
       progress: 0,    // 0-100
       error: null
     },

     // Existing loading states
     loading: {
       backingTrack: false,
       jamTrack: false,        // Extend to include download state
       metronome: false,
       closing: false
     }
   }
   ```

2. **activeSessionSlice Extensions**
   ```javascript
   {
     selectedJamTrack: null,   // Existing - full JamTrack object
     jamTrackStems: [],        // Existing - stem track array

     // NEW: Mixdown data
     availableMixdowns: [],    // User's custom mixes
     activeMixdown: null       // Currently playing mixdown
   }
   ```

3. **sessionUISlice Extensions**
   ```javascript
   {
     modals: {
       jamTrack: false,        // Existing
       backingTrack: false,    // Existing
       metronome: false,       // Existing

       // NEW: JamTrack-specific modals
       jamTrackPlayer: false   // Player modal visibility
     },

     // NEW: JamTrack UI state
     jamTrackUI: {
       showMixdownSelector: true,
       showDownloadProgress: true,
       playerMode: 'modal'     // 'modal' | 'popup'
     }
   }
   ```

4. **Async Thunks**
   - `loadJamTrack({ jamTrack, mixdownId?, jamClient })` - Load and play JamTrack
   - `downloadJamTrack({ jamTrackId, mixdownId, jamClient })` - Download with progress
   - `checkJamTrackSync({ jamTrackId, jamClient })` - Check download/key state
   - `loadJMEP({ jamTrack, jmepData, jamClient })` - Load tempo/pitch modifications
   - `seekJamTrack({ positionMs, jamClient })` - Seek playback
   - `closeJamTrack({ jamClient })` - Stop and clean up

5. **Reducers**
   - `setJamTracks(state, action)` - From MIXER_CHANGES WebSocket
   - `updateJamTrackState(state, action)` - From JAM_TRACK_CHANGES WebSocket
   - `setDownloadState(state, action)` - Progress updates during download
   - `setAvailableMixdowns(state, action)` - User's custom mixes
   - `setActiveMixdown(state, action)` - Selected mixdown

6. **Selectors**
   ```javascript
   // Media selectors
   selectJamTracks(state) => state.media.jamTracks
   selectJamTrackState(state) => state.media.jamTrackState
   selectDownloadState(state) => state.media.downloadState
   selectIsJamTrackPlaying(state) => state.media.jamTrackState.isPlaying

   // Session selectors
   selectSelectedJamTrack(state) => state.activeSession.selectedJamTrack
   selectJamTrackStems(state) => state.activeSession.jamTrackStems
   selectAvailableMixdowns(state) => state.activeSession.availableMixdowns

   // UI selectors
   selectJamTrackPlayerOpen(state) => state.sessionUI.modals.jamTrackPlayer
   selectJamTrackUI(state) => state.sessionUI.jamTrackUI
   ```

7. **WebSocket Integration**
   - MIXER_CHANGES handler: Dispatch `setJamTracks(sessionMixers.mixers.jamTracks)`
   - JAM_TRACK_CHANGES handler: Dispatch `updateJamTrackState(changes)`
   - Real-time playback position updates (similar to Backing Track polling)

8. **State Machine for Download/Sync**
   | State | Description | Next States | Actions |
   |-------|-------------|-------------|---------|
   | idle | No active download | checking, downloading | User initiates download |
   | checking | Querying sync state | synchronized, downloading, error | JamTrackGetTrackDetail() |
   | downloading | Download in progress | keying, error | JamTrackDownload() with progress callback |
   | keying | Requesting encryption keys | synchronized, error | JamTrackKeysRequest() |
   | synchronized | Ready to play | idle | JamTrackPlay() success |
   | error | Download/sync failed | idle (after retry) | Show error, allow retry |

**verify:**
- REDUX_DESIGN.md created with all 8 sections
- State structure with TypeScript-style type annotations
- All thunks defined with parameters and return types
- Selector list complete
- State machine table or diagram included
- Comparison to Backing Track Redux patterns

**done:**
Redux state structure designed with clear data flow and state management patterns.

---

### Task 3: Create Phase 5 Implementation Roadmap

**type:** checkpoint:human-verify

**files:**
- CREATE `.planning/phases/04-jamtrack-research-design/IMPLEMENTATION_ROADMAP.md`

**action:**
Create detailed implementation roadmap for Phase 5 with risk analysis:

1. **Phase 5 Task Breakdown** (preliminary - will be refined during Phase 5 planning)
   - Plan 05-01: Redux State Setup (mediaSlice, activeSessionSlice, sessionUISlice extensions)
   - Plan 05-02: jamClient Integration (async thunks, download/sync state machine)
   - Plan 05-03: JKSessionJamTrackPlayer Component (player UI, playback controls, mixdown selector)
   - Plan 05-04: WebSocket Integration (MIXER_CHANGES, JAM_TRACK_CHANGES handlers)
   - Plan 05-05: Download/Sync Flow (progress UI, error handling, retry logic)
   - Plan 05-06: Testing & Edge Cases (error scenarios, network resilience, UAT)

2. **Dependency Graph**
   ```
   05-01 (Redux State) → 05-02 (jamClient Integration)
                       ↘
   05-03 (Player Component) ← 05-02
                       ↓
   05-04 (WebSocket) ← 05-02
                       ↓
   05-05 (Download/Sync) ← 05-04
                       ↓
   05-06 (Testing/UAT)
   ```

3. **Risk Analysis**
   | Risk | Likelihood | Impact | Mitigation |
   |------|------------|--------|------------|
   | Download/sync state machine complexity | High | High | Parallel implementation with feature flag, gradual rollout |
   | JMEP loading failures | Medium | Medium | Graceful degradation (play master if JMEP fails), error handling |
   | Sample rate mismatch | Medium | High | Validate sample rate early, show error if incompatible |
   | WebSocket JAM_TRACK_CHANGES integration | Low | Medium | Follow MIXER_CHANGES pattern, test with real sessions |
   | Mixdown selector UX complexity | Medium | Low | MVP: master + custom mixes, defer stem-level control |
   | Native client API changes | Low | High | Verify API methods in test environment before implementation |
   | Performance regression | Low | Medium | Reuse Backing Track polling patterns, benchmark dispatch speed |

4. **Critical Decisions Needed Before Phase 5**
   - [ ] Does jamClient support JamTrack loop functionality? (Test: `SessionSetBackingTrackFileLoop` equivalent)
   - [ ] Should download/sync happen automatically or require user confirmation?
   - [ ] MVP mixdown selector: Master + custom mixes only, or include individual stems?
   - [ ] Popup vs modal preference: Default to popup like Backing Track, or modal?
   - [ ] Error recovery strategy: Auto-retry downloads or require manual retry?

5. **Success Metrics for Phase 5**
   - [ ] JamTrack loads and plays with master mix
   - [ ] Mixdown selector switches between master/custom mixes without interruption
   - [ ] Download progress shown during sync
   - [ ] Seek bar functional (drag-to-position)
   - [ ] Error handling with user feedback
   - [ ] No playback interruptions or state sync issues
   - [ ] Performance: <1ms Redux dispatch, 60fps UI updates

6. **Testing Strategy**
   - Unit tests: Redux reducers, thunks, selectors (>80% coverage)
   - Integration tests: jamClient call sequences, WebSocket message handling
   - Manual UAT: Load JamTrack, switch mixdowns, seek, pause/resume, error scenarios
   - Performance tests: Dispatch speed, polling frequency, memory leaks

7. **Comparison to Phase 3 Effort**
   | Metric | Phase 3 (Backing Track) | Phase 5 (JamTrack) Estimate |
   |--------|-------------------------|------------------------------|
   | Plans | 3 plans | 6 plans |
   | Tasks | ~10 tasks | ~18 tasks |
   | Complexity | Medium | High (download/sync state machine) |
   | New components | 1 (Player) | 1 (Player) + updates to Modal/Stems |
   | Redux state additions | 2 slices | 3 slices (more complex structure) |
   | jamClient methods | 8-10 methods | 15+ methods |
   | Known blockers | 3 deferred issues | TBD (likely 2-4 similar issues) |

**verify:**
- IMPLEMENTATION_ROADMAP.md created with all 7 sections
- Dependency graph visualized (text diagram or mermaid)
- Risk analysis complete with mitigation strategies
- Critical decisions identified
- Success metrics defined
- Testing strategy outlined

**done:**
Phase 5 implementation roadmap created with risk analysis and clear path forward.

---

### CHECKPOINT: Architecture Review and Approval

**type:** human-verify

**prompt:**
Review the architecture design created across three documents:

1. `.planning/phases/04-jamtrack-research-design/COMPONENT_DESIGN.md` - React component structure
2. `.planning/phases/04-jamtrack-research-design/REDUX_DESIGN.md` - Redux state and data flow
3. `.planning/phases/04-jamtrack-research-design/IMPLEMENTATION_ROADMAP.md` - Phase 5 implementation plan

**Verification criteria:**
- Component design follows established Backing Track patterns
- Redux state structure accommodates JamTrack-specific complexity
- Implementation roadmap is actionable and complete
- Risk analysis covers critical concerns
- Critical decisions identified for user input

**Actions:**
- If revisions needed: Specify changes to component/Redux design
- If critical decisions need answers: Answer decision questions in roadmap
- If approved: Proceed to commit Phase 4 completion

</tasks>

<verification>
Architecture design verified through:

1. **Pattern Consistency**
   - Compare component design to JKSessionBackingTrackPlayer.js
   - Verify Redux state structure follows mediaSlice patterns
   - Check thunk signatures match useMediaActions patterns

2. **Completeness Check**
   - All JamTrack-specific features addressed (mixdowns, download/sync, JMEP)
   - Error handling strategy defined
   - WebSocket integration planned
   - Performance considerations included

3. **Actionability Test**
   - Phase 5 roadmap provides clear starting point
   - Component interfaces fully defined
   - Redux state structure ready for implementation
   - Risk mitigation strategies practical

4. **Risk Coverage**
   - All high-impact risks identified
   - Mitigation strategies feasible
   - Critical decisions captured
</verification>

<success_criteria>
- [ ] COMPONENT_DESIGN.md created with complete component hierarchy
- [ ] REDUX_DESIGN.md created with state structure and thunks
- [ ] IMPLEMENTATION_ROADMAP.md created with Phase 5 breakdown
- [ ] All design documents committed to git
- [ ] User verification checkpoint passed
- [ ] Critical decisions answered or deferred to Phase 5 planning
</success_criteria>

<output>
**Artifacts:**
- `.planning/phases/04-jamtrack-research-design/COMPONENT_DESIGN.md` - Component architecture
- `.planning/phases/04-jamtrack-research-design/REDUX_DESIGN.md` - Redux state design
- `.planning/phases/04-jamtrack-research-design/IMPLEMENTATION_ROADMAP.md` - Phase 5 roadmap

**Purpose:**
Comprehensive React architecture design for JamTrack functionality, enabling Phase 5 implementation with clear component structure, Redux state management, and risk-aware implementation strategy.
</output>
