# WP Agentic Writer: Document Update Summary ## Recommended Updates & Improvements ### 1. **Flow 3: Image Generation - Add Format Conversion** **Current State:** Stores only JPEG **Recommendation:** Add WebP/AVIF conversion after generation ```php // After generating JPEG, auto-convert to next-gen formats private static function generate_image_variants($temp_filepath, $image_model, $prompt) { // 1. Generate initial JPEG (existing flow) // 2. Convert to WebP + AVIF (NEW) self::convert_to_webp($temp_filepath); self::convert_to_avif($temp_filepath); // 3. Return all variants with format preference return [ 'jpg' => $temp_filepath, 'webp' => str_replace('.jpg', '.webp', $temp_filepath), 'avif' => str_replace('.jpg', '.avif', $temp_filepath) ]; } ``` **Benefits:** - Users see faster image variants - Better performance on modern browsers - Up to 40-60% smaller files --- ### 2. **Flow 4: Media Upload - Optimize Before Commit** **Current State:** Direct sideload without optimization **Recommendation:** Add image optimization before WordPress upload ```php public static function sideload_image_to_media($temp_filepath, $post_id, $alt_text) { // 1. Optimize image (compress, resize if needed) $optimized_path = self::optimize_image_before_upload($temp_filepath); // 2. Proceed with sideload $attachment_id = media_handle_sideload(/* ... */); // 3. Return optimized attachment return $attachment_id; } // Uses: ShortPixel API or local imagick/gd private static function optimize_image_before_upload($filepath) { // Option A: Local ImageMagick/GD for fast compression // Option B: External API (ShortPixel, Imagify) for advanced algorithms } ``` **Benefits:** - Smaller images in WP Media Library - Faster downloads for site visitors - Better Core Web Vitals --- ### 3. **Flow 5: Temp Management - Add Offloading Option** **Current State:** Local filesystem only **Recommendation:** Add cloud offloading for large operations ```php // Config: Use local or cloud temp storage define('AGENTIC_TEMP_STORAGE', 'local'); // or 's3', 'r2', 'bunny' private static function get_temp_storage_handler() { $storage_type = get_option('agentic_temp_storage_type', 'local'); switch($storage_type) { case 's3': return new S3TempStorage(/* AWS credentials */); case 'r2': return new CloudflareR2TempStorage(/* R2 credentials */); case 'bunny': return new BunnyCDNTempStorage(/* Bunny API key */); default: return new LocalTempStorage(); } } ``` **Benefits:** - Scales for high-volume image generation - No disk space constraints - Automatic cleanup via cloud service --- ### 4. **Error Handling & Retry Logic** **Current State:** Minimal error handling **Recommendation:** Add robust retry + fallback strategies ```php /** * Resilient image generation with retry logic */ private static function generate_with_retry($prompt, $model, $max_retries = 3) { for ($attempt = 1; $attempt <= $max_retries; $attempt++) { try { return self::call_image_api($model, $prompt); } catch (TimeoutException $e) { if ($attempt === $max_retries) { // Last attempt: return cached/previous variant return self::get_fallback_image($model, $prompt); } sleep($attempt * 2); // Exponential backoff } catch (RateLimitException $e) { // Switch to slower, cheaper model $model = self::get_fallback_model($model); sleep(5); } } } /** * Cost estimation with usage tracking */ private static function track_generation_cost($model, $usage) { // Store: tokens, cost per image, cumulative cost // Alert if monthly budget exceeded update_option('agentic_monthly_generation_cost', get_option('agentic_monthly_generation_cost', 0) + $usage['cost'] ); } ``` --- ### 5. **Admin Interface Enhancements** **Current State:** Basic image library table **Recommendations:** a) **Add real-time generation progress** - WebSocket updates instead of polling - Show: variant 2/3 generated, cost so far, ETA b) **Add cost analytics dashboard** - Cost per post, per model, trend graph - Budget alerts + consumption warnings - Compare model costs c) **Batch operations** - Regenerate all images for post - Export all temps as ZIP - Auto-optimize + commit all in one click --- ### 6. **Security & Permission Checks** **Current State:** Basic `edit_post` check **Recommendations:** ```php /** * Add granular permission checks */ private static function check_user_image_permissions($user_id, $action) { // Check: Can user generate images? (rate limit check) // Check: Can user commit to this post? // Check: Monthly generation quota not exceeded? if (!user_can_generate_images($user_id)) { return new WP_Error('quota_exceeded', 'Generation limit reached'); } } /** * Sanitize all image prompts before API call */ private static function sanitize_image_prompt($prompt) { // Remove: potentially harmful instructions // Limit: length to 1000 chars // Log: all prompts for audit trail return apply_filters('agentic_sanitize_image_prompt', $prompt); } ``` --- ### 7. **Database Indexes & Performance** **Current State:** Basic indexes **Recommendations:** ```sql -- Add composite index for faster queries CREATE INDEX idx_post_image_status ON wp_agentic_images(post_id, agent_image_id, status); -- Add index for cost tracking CREATE INDEX idx_generation_date_cost ON wp_agentic_images_variants(created_at, cost); -- For analytics queries CREATE INDEX idx_model_generation_time ON wp_agentic_images_variants(image_model_used, generation_time); ``` --- ### 8. **Configuration & Feature Flags** **New Settings Panel Section:** ```php 'generation_settings' => [ 'max_variants_per_generate' => 3, 'variant_formats' => ['jpg', 'webp', 'avif'], 'enable_auto_optimize' => true, 'temp_storage_type' => 'local|s3|r2|bunny', 'cleanup_old_temps_days' => 7, 'max_generation_cost_per_post' => 5.00, 'image_models' => ['sourceful/riverflow-v2-max', 'sdxl-turbo'], 'enable_cost_tracking' => true, 'enable_user_notifications' => true, ] ``` --- ## Implementation Priority **Phase 1 (Critical):** - Add error handling + retry logic - Optimize images before commit - Add cost tracking **Phase 2 (Important):** - WebP/AVIF conversion - Enhanced admin analytics - Database performance indexes **Phase 3 (Nice-to-have):** - Cloud temp storage offloading - Real-time progress WebSockets - Batch operations UI --- ## Next Steps 1. Review these recommendations 2. Clarify which sections to update first 3. I can generate updated flows with code examples 4. Test integration with your current WP Agentic Writer setup