Commit Graph

211 Commits

Author SHA1 Message Date
peptiderepo
7d61c8c76d feat: add Image B toggle to disable second image generation (v0.4.6)
New toggle in Images settings controls whether the source-data-based
second image is generated. Disabling saves one image gen call + one
LLM prompt rewrite per article. Defaults to enabled.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 22:08:06 +07:00
peptiderepo
ca8fe1bfba feat: add Analysis & Editor Instructions settings (v0.4.5)
Two new textareas in Content settings let admins provide custom
instructions for the analysis and chief editor LLM stages, matching
the Writing Instructions field added in v0.4.4. All three pipeline
stages now have user-controllable system prompt customization.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 17:13:49 +07:00
peptiderepo
b0cc93669d feat: add Writing Instructions setting for LLM system prompt (v0.4.4)
New textarea in Content settings lets admins provide custom instructions
appended to the writer's system prompt. Steers style, structure, voice,
and formatting without editing code.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 17:01:54 +07:00
peptiderepo
65560ea0b5 fix: tolerate markdown-fenced JSON from LLM responses (v0.4.3)
Models like GPT 5.1 Nano ignore response_format: json_object and wrap
their JSON in ```json fences or add preamble text. New Json_Extractor
utility tries: (1) direct decode, (2) strip markdown fences, (3) find
outermost { ... } substring. Applied to analyzer and chief editor
parsers. Raw response logged on parse failure for debugging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 15:40:37 +07:00
peptiderepo
3e1e5efe09 fix: word-wrap title column and tighten custom column widths (v0.4.2)
Title column was compressed to ~30px making post titles unreadable.
Give title 35% min-width with word-wrap, trim model columns to 100px
with text-overflow ellipsis, cost column to 55px.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 14:27:49 +07:00
peptiderepo
499dcc931d fix: set minimum column widths for model/cost columns
Columns were crushed to 1-char width by WordPress's auto-layout.
Added 120px for model columns and 60px for cost.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 14:23:07 +07:00
peptiderepo
0a15e266cd feat: add Writing Model, Image Model, and Cost columns to posts list
v0.4.1 — Three new columns on the WordPress Posts admin page showing
which LLM wrote each article, which model generated its featured image,
and the total API cost. Model names shortened for compact display with
full ID in tooltip. Cost queries the generation_log table, skipping
the DB hit entirely for non-generated posts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 14:21:02 +07:00
peptiderepo
9e74b596d1 chore: bump version to 0.4.0
Semantic dedup, LLM topic avoidance, featured image fix, chained-job
race condition fix, stall detection fix.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 14:14:02 +07:00
peptiderepo
281c8cd89c feat: semantic dedup + LLM-aware topic avoidance
Two-pronged fix for repeated article topics:

1. Feed last 30 days of published article titles into the LLM analysis
   prompt with explicit "avoid these" instruction. Zero cost — just
   extra context in an existing API call.

2. Replace keyword-overlap dedup (60% word match) with embedding-based
   cosine similarity via sentence-transformers/all-MiniLM-L12-v2 on
   OpenRouter. Catches rephrasings that keyword matching misses
   (e.g. "BPC-157 dosing" vs "how much BPC-157 to take"). Falls back
   to keyword matching if the embedding API is unavailable.

   Cost: ~$0.00001 per generation run ($0.02/M tokens, ~500 tokens/run).

New files:
- class-semantic-dedup.php — Embedding cosine similarity + keyword fallback
- class-open-router-embedding-provider.php — OpenRouter /embeddings client

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 13:35:26 +07:00
peptiderepo
00cfb39253 Fix race condition causing duplicate article generation
The status poller's orphan-recovery logic re-scheduled cron events for
articles already being generated. During the ~90s generation window, the
queue option in the DB still contained the in-progress idea because the
process only deleted/updated it AFTER generation completed.

Fix: persist the consumed queue to the DB BEFORE starting generation.
When the poller checks get_option(), it now sees either an empty queue
(for the last article) or a queue without the current idea, so orphan
recovery cannot duplicate work.

Root cause: process_next_queued_article() did array_shift on a local
variable but left the DB unchanged until after the slow LLM+image
generation finished. The poller saw the stale DB state, assumed the
cron event had died, and re-scheduled it — producing a 4th post from
3 ideas on every run.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 11:53:34 +07:00
peptiderepo
cc6979b085 Fix false stall detection for multi-article chained generation
The frontend status poller measured elapsed time from `started` (set once
at the beginning of the run) and declared a stall at 300s.  Three articles
take ~6 minutes total, so the poller always false-alarmed on article 3.

Now every stage broadcast writes `last_updated` into the transient, and
the stall check compares idle time since the last update — not since the
run started.  This lets N-article runs complete without false timeout as
long as each individual article finishes within 5 minutes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 03:40:05 +07:00
peptiderepo
ef40ce91d4 feat: chain per-article cron jobs to eliminate execution time ceiling
The pipeline previously ran all articles sequentially in a single PHP
process. On Hostinger, this timed out at ~120s — enough for 1 article
but not 2+. Now the pipeline generates article 1 in-process, then
queues articles 2..N as individual WP-Cron events. Each article gets
its own PHP process with its own execution time budget, so we can
generate any number of articles regardless of server time limits.

Architecture:
- Pipeline_Runner: orchestrate (collect+analyze+score) + first article,
  then serialize remaining ideas to wp_options and chain cron events
- Article_Worker (new): focused single-article worker extracted from
  the pipeline loop — content gen + editorial + publish
- Executor: new on_process_article_queue() handler for chained events;
  status poller re-schedules orphaned queue jobs automatically
- Article_Idea: added to_array() for queue serialization

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 03:26:37 +07:00
peptiderepo
c866637a95 fix: refresh collected_at on re-seen source items so analyzer picks them up
The collector used INSERT IGNORE which silently skipped duplicate items
without updating their collected_at timestamp. After 24 hours, these
items fell out of the analyzer's window permanently — even though they
kept appearing in the RSS feed. This caused "No new source data to
analyze" on every run once the initial batch aged out.

Switch to INSERT ... ON DUPLICATE KEY UPDATE to refresh collected_at
(plus score and comment_count, which change over time on Reddit).
The analyzer's 24-hour window now sees re-fetched items again.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 03:06:01 +07:00
peptiderepo
2300fbf1c5 fix: scope dedup to batch + recent 7 days, not all-time history
Dedup now has two narrow scopes instead of checking all posts ever:

1. Intra-batch: prevents proposing two articles on the same topic
   within a single pipeline run (keyword overlap ≥60%)
2. Recent posts: checks only posts from the last 7 days to avoid
   back-to-back similar content

Older articles are intentionally NOT checked — revisiting a topic
weeks later is fine. This prevents the dedup from becoming
increasingly aggressive as the blog grows, which was the root cause
of "no viable article ideas found" with 125 collected items.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 02:53:59 +07:00
peptiderepo
42d6d03cb3 fix: replace over-aggressive WP_Query dedup with keyword-overlap check
The old has_similar_post() used WordPress search ('s' parameter) which
matches ANY word in the query. On a niche peptide blog, every topic
shares vocabulary like "BPC-157", "peptide", "dosage" — so all 125
ideas were false-positive deduped against existing posts, producing
zero viable article ideas.

New approach: extract meaningful keywords (strip stopwords), compare
against each existing post title, and only dedup when ≥60% of the
topic's keywords overlap with a single title. Also caches the title
list per pipeline run to avoid repeated queries.

Added summary logging so we can see exactly how many ideas pass
through each filter stage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 02:52:17 +07:00
peptiderepo
d17c488ef3 feat: parallel image generation via curl_multi
Both Image A and Image B now fire concurrently through a single
generate_image_batch() call instead of sequentially. Total wall-clock
time equals the slowest image (~20s), not the sum (~40s), which
eliminates the Image B timeout problem on Hostinger where
max_execution_time killed the cron before the second request finished.

New files:
- class-open-router-image-batch.php — curl_multi orchestrator
- generate_image_batch() added to image provider interface

Pipeline refactored: prompts built upfront, single batch call, results
processed per-key. Cloudflare provider gets a sequential fallback.
Tests updated for batch API. All files under 300-line cap.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 21:10:54 +07:00
peptiderepo
c8595e05de Fix duplicate image, remove hardcoded model references
Three fixes in one:

1. Duplicate image: prepend_caption_to_post() was embedding the full
   image + caption as a <figure> block, but the theme already displays
   the featured image. Now only the caption text is prepended — no
   second copy of the image.

2. Hardcoded model names: removed all FLUX.1/FLUX.2 references from
   model-agnostic code (pipeline, prompt builder, sideloader, OpenRouter
   provider, interface, admin labels). The Cloudflare provider still
   references FLUX since it specifically wraps that model family.

3. Test alignment: OpenRouterImagePricingTest was asserting against
   removed models (flux-2-pro, seedream). Updated to match current
   COST_PER_IMAGE entries (Gemini Flash, GPT-5 Image).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 16:08:36 +07:00
peptiderepo
650d8df325 Fix false error: detect completed pipeline at 90s instead of 300s
The status endpoint waited 300 seconds before checking if the pipeline
had produced output. On Hostinger, PHP's max_execution_time kills the
cron process after ~120s. The pipeline publishes the post before images,
so the post exists but the transient never transitions to 'complete'.
The user sees "Generating…" for 5 minutes, then gives up.

Now the status endpoint proactively checks for recently-created posts
after just 90 seconds. If found, it reports success immediately. The
300-second hard-fail threshold is still there for genuinely dead runs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 16:03:01 +07:00
peptiderepo
214f57bff2 Separate comic captions from generated images
Captions were being baked into the image by the FLUX model, causing
text to get cut off at the edges. Now the LLM generates scene and
caption separately — the scene drives image gen (with explicit
"no text in the image" instruction), and the caption is inserted
as a styled <figure>/<figcaption> HTML block at the top of the post.

Changes:
- rewrite_via_llm() returns array{scene, caption} instead of string
- build_article_prompt() and build_source_prompt() return {prompt, caption}
- Style suffix v4: removes "caption text" instruction, adds "no text" directive
- Image pipeline destructures prompt/caption, stores caption in attachment meta
- prepend_caption_to_post() inserts figure+figcaption HTML into post content
- Deduplicated generate_image_a/b into shared generate_single_image()
- One-time v4 migration auto-updates existing style suffix on deploy

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 15:15:59 +07:00
peptiderepo
389cb4d380 chore: trim executor comment to stay within 300-line rule
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 14:24:34 +07:00
peptiderepo
abcc454dfe fix: increase fallback detection threshold from 180s to 300s
Pipeline with 3 articles + GPT-5 Image generation legitimately takes
3-4 minutes. The 180-second fallback was triggering before the pipeline
finished, incorrectly reporting "no content" when it was still running.
Increase to 300 seconds to give the pipeline room to complete.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 14:23:29 +07:00
peptiderepo
12654b3a45 fix: load wp-admin media functions in cron context for image sideload
media_handle_sideload() is only available in admin context. When the
pipeline runs via WP-Cron (background generation), the function is
undefined. Add require_once guards for media.php, file.php, and
image.php before calling sideload.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 14:15:53 +07:00
peptiderepo
41f1b13497 refactor: split class-executor.php into 3 focused classes (300-line rule)
Extract PRAutoBlogger_Generation_Lock (DB mutex) and
PRAutoBlogger_Ajax_Handlers (image/model/test AJAX) from the
482-line executor. Executor retains generation cron/AJAX + model
registry at 299 lines. Document background generation flow in
ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 14:08:46 +07:00
peptiderepo
4c49e8593e fix: add ignore_user_abort + fallback completion detection for cron
The WP-Cron loopback is also subject to Hostinger's 120s timeout.
Adding ignore_user_abort(true) keeps the PHP process alive after
LiteSpeed closes the connection.

Also adds fallback completion detection: if the transient is stuck
at "running" but the generation lock was released (pipeline finished),
the status endpoint now checks for recently-created posts to confirm
success and recover gracefully.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 13:59:37 +07:00
peptiderepo
b5bbc54f87 fix: move Generate Now to background processing to avoid 120s timeout
Hostinger's LiteSpeed web server kills any HTTP connection that runs
longer than 120 seconds with a 500 "Request Timeout" error. The full
pipeline (Reddit fetch → topic scoring → article generation → editorial
pass → image gen ×2) takes 120-180s, causing "Request failed: error"
on every manual generation attempt.

Architecture change:
- Generate Now AJAX handler now schedules a one-shot WP-Cron event
  and returns immediately (~100ms response time)
- New prautoblogger_manual_generation cron action runs the pipeline
  in a separate PHP process free from the connection timeout
- Pipeline progress is written to a transient at each stage
- New prautoblogger_generation_status AJAX endpoint lets the frontend
  poll progress every 5 seconds
- Frontend auto-resumes polling on page load if a generation is running
- Direct wp-cron.php loopback ensures cron fires even if DISABLE_WP_CRON
  is set (common on Hostinger)

Version bump: 0.2.9 → 0.3.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 13:52:10 +07:00
peptiderepo
b17ed4719b feat: switch to single-panel newspaper comic style for article images
Replace photography-style prompts with a comedy writer system prompt
that generates Far Side-style single-panel comic concepts with punchy
captions. The LLM rewriter now outputs a comic scene + caption line,
and the style suffix renders as classic black-ink newspaper comic on
yellowed newsprint.

Includes v3 style migration to auto-replace both the old infomercial
and the short-lived photography style in wp_options. Bumped max_tokens
to 180 to accommodate scene + caption output.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 13:20:20 +07:00
peptiderepo
1a2af595c6 fix: attach images immediately + upgrade image prompts to v2
Two fixes:

1. Image attachment: moved set_post_thumbnail() and Image B post meta
   into generate_and_attach_images() so they persist immediately after
   each image generates. Previously the caller set them after both images
   completed — if the process timed out (common with GPT-5 Image at
   ~30s/image), the featured image was never attached and Image B was
   never attempted.

2. Image prompts: replaced FLUX.1-optimized rewriter system prompt and
   90s infomercial style suffix with prompts optimized for Gemini Flash
   Image and GPT-5 Image. New style: premium scientific lifestyle
   photography with golds/teals color grading. Includes one-time migration
   to update stored style suffix.

Also logs when Image B is skipped due to missing source data (previously
silent), helping diagnose why some posts only get one image.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 12:17:05 +07:00
peptiderepo
dd406c5ba6 fix: snap aspect ratios to standard values for Gemini compatibility
Gemini image models reject arbitrary aspect ratios like 150:79
(computed via GCD from 1200×632 pixels). Replace GCD-based calculation
with a snap-to-nearest approach using 7 standard ratios (1:1, 3:2,
2:3, 4:3, 3:4, 16:9, 9:16). Also set modalities to ["image", "text"]
as required by some providers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 11:00:35 +07:00
peptiderepo
a4405a5d32 fix: remove hardcoded image model fallback
Don't silently swap to a different model when the user's selection is
unknown. Pass whatever the user configured to OpenRouter and let the
API error clearly. Fallback chain: caller hint → saved option →
PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL constant. Cost estimation for
unknown models logs a warning and uses a conservative $0.05 estimate.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:50:34 +07:00
peptiderepo
862d7e40e6 fix: update image models, handle upstream errors in HTTP 200
Three issues found in activity logs:

1. Image model IDs stale — FLUX and Seedream removed from OpenRouter.
   Updated to current models: Gemini 2.5/3.1 Flash Image, Gemini 3 Pro
   Image, GPT-5 Image/Mini. Default changed to gemini-2.5-flash-image.

2. openrouter/free router wraps upstream 429 errors in HTTP 200 body
   with error object. Both text and image response parsers now detect
   this pattern and surface a proper RuntimeException.

3. Image request used modalities: ["image"] but Gemini needs
   ["image", "text"]. Updated to include both.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:47:05 +07:00
peptiderepo
cf3d97c0c3 fix: handle null content in OpenRouter response parser
Some models (and the openrouter/free router) may return null content
instead of a string. The old check used isset() which returns false
for null, triggering the "unexpected response format" error.

Now: checks for choices[0].message (not content), treats null content
as empty string, and logs the actual response shape on failure so we
can diagnose what the model returned.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:23:53 +07:00
peptiderepo
2c2a2acc7d fix: recognize openrouter/free router as zero-cost
The free models router (openrouter/free) doesn't use the :free suffix,
so it needs an explicit check alongside the suffix-based one.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:20:32 +07:00
peptiderepo
58cb4ed508 feat: recognize OpenRouter :free models as zero-cost
Models with the :free suffix (e.g. google/gemini-2.5-flash-preview:free)
are served at no charge by OpenRouter. The cost estimator now returns
$0.00 for these models instead of falling through to the conservative
$10/$30 per-million-token fallback.

No changes needed in the model picker or provider — :free models use
the same API endpoint and already appear in the registry.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:17:59 +07:00
peptiderepo
358a1bbc7e fix: unblock deploy pipeline — remove wp-phpunit, simplify deploy gate
wp-phpunit ^6.0 requires PHP 8.0+ but our CI matrix includes PHP 7.4,
breaking composer install on every push. Tests only use Brain Monkey,
not wp-phpunit, so the dependency was dead weight.

Deploy workflow now uses PHP lint as its only gate. PHPCS and PHPUnit
stay in the separate ci.yml workflow where they belong.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:15:28 +07:00
peptiderepo
1968864073 fix: widen all catch blocks from \Exception to \Throwable
PHP 8.3 TypeError and Error extend \Throwable but NOT \Exception,
so catch(\Exception) silently drops them — explaining why the
generation pipeline fails at the publishing step with no activity
log entry. Now every catch in the generation path catches
\Throwable and logs the exception class name for diagnostics.

Bump to v0.2.7.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:12:06 +07:00
peptiderepo
14e4270158 fix: preserve active tab after saving settings
The _wp_http_referer hidden field didn't include the tab parameter, so
WordPress redirected to the default (API Keys) tab after every save.
Now the JS syncs the referer with the active tab on both tab switch and
page load. Bumped to v0.2.6 to bust JS cache.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 10:00:48 +07:00
peptiderepo
d886aee1d7 fix: rename OpenRouter image files to match autoloader kebab-case convention
The autoloader splits CamelCase on lowercase→uppercase transitions, so
PRAutoBlogger_OpenRouter_Image_Provider maps to class-open-router-image-provider.php.
Files were named class-openrouter-* (missing hyphen), causing a PHP fatal
error when the pipeline tried to instantiate the provider — which killed
the process before any logging could fire.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 09:58:04 +07:00
peptiderepo
4cc9b39693 fix: model picker shows 0 image models — capability mismatch in field renderer
The field renderer still checked for the old 'cloudflare_image' capability
but the setting was changed to 'image_generation'. Updated to resolve
model name/price from the shared get_image_models() list. Bumped to
v0.2.5 to bust browser JS/CSS cache.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 09:23:39 +07:00
peptiderepo
0a68741945 feat: add OpenRouter image provider for higher-quality image generation
Replaces Cloudflare Workers AI (FLUX.1 schnell) as the default image
provider with OpenRouter, which offers FLUX.2 Pro, Seedream 3.0,
Gemini Flash Image, and GPT Image 1 at comparable or better pricing.

- New provider class (3-file split: provider, pricing, support) reuses
  the existing OpenRouter API key and Cloudflare AI Gateway
- Admin settings: new Image Provider dropdown (openrouter/cloudflare),
  model picker shows all available image models from both providers
- Image pipeline auto-selects the configured provider at construction
- Cost logging now uses actual model name instead of hardcoded flux-1-schnell
- Default model changed to black-forest-labs/flux-2-pro ($0.03/image)
- Unit tests for pricing resolution and provider response parsing

Cost impact: FLUX.2 Pro at $0.03/image vs schnell at $0.0007/image —
~43x more expensive per image, but dramatically better quality. At 2
images/article × 1 article/day = ~$1.80/month. Seedream 3.0 ($0.003)
available as a budget alternative.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 09:19:13 +07:00
peptiderepo
b5e91ba3a6 fix: wire Image B source data — was hardcoded null, never generated
Root cause: both attach_generated_images() in post-assembler and the
retroactive handler in executor passed null as source_data to the image
pipeline. The pipeline's Image B branch requires non-null source_data
to fire, so Image B was silently skipped on every article since the
feature was built.

Fix: added get_source_data_for_image() to Source_Collector to retrieve
the original Reddit post title/content by source_ids. Post-assembler
now pulls source_ids from the Article_Idea; executor pulls them from
the _prautoblogger_source_ids post meta saved by the publisher.

Also added a regression test proving Image B is skipped when source_data
is null, so this handoff gap will be caught if re-introduced.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 08:34:21 +07:00
peptiderepo
5b5286ca5b fix: remove deprecated flux-1-dev model from Cloudflare image config
FLUX.1 [dev] was removed from Cloudflare Workers AI in April 2026,
returning HTTP 400 "No route for that URI". This removes it from the
static model picker list and pricing calculations. Any saved setting
referencing flux-1-dev gracefully falls through to flux-1-schnell
via the null-coalesce in resolve_model().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 07:48:18 +07:00
peptiderepo
49aee0b446 fix: add Cloudflare token to encrypted fields list (fixes 401 on image gen)
prautoblogger_cloudflare_ai_token was missing from the $encrypted array
in sanitize_field(), so the token was stored as plaintext. On read,
decrypt() failed on the non-encrypted value and returned empty string,
causing HTTP 401 on every Cloudflare Workers AI call.

Fix: add the field to the encrypted list so future saves encrypt it.
Also add legacy plaintext detection in get_api_token() and the validator
so the existing DB value works immediately and gets auto-encrypted on
first use.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 07:24:01 +07:00
peptiderepo
51b385b938 fix: bump version to 0.2.4 to bust JS/CSS cache for model picker
The image model popup shows 0 models because LiteSpeed/browser cache
serves the old model-picker.js (pre-cloudflare_image support) since
the version query string didn't change between commits.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 03:13:10 +07:00
peptiderepo
1c1e861f2e feat: extend model picker to image model (Cloudflare FLUX)
Apply the same interactive model picker UI to the image model field.
Since Cloudflare models don't come from OpenRouter's registry, the
two FLUX models are embedded as static data in the page config and
the JS popup renders cost-per-image instead of token pricing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 03:06:17 +07:00
peptiderepo
31f303a831 feat: interactive model picker with searchable popup and pricing
Replace plain text inputs for analysis/writing/editor model fields
with a rich model picker that fetches the OpenRouter model registry
and displays a searchable popup with model name, provider, input/output
pricing per 1M tokens, and context window. Also extracts source status
and model field renderers into dedicated field classes to keep
class-admin-page.php under the 300-line cap.

New files:
- assets/js/model-picker.js — popup UI with search, filtering, caching
- assets/css/model-picker.css — popup styles matching admin design system
- includes/admin/fields/class-open-router-model-field.php — server render
- includes/admin/fields/class-source-status-field.php — extracted field

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 02:53:40 +07:00
peptiderepo
dcc8b7b183 feat: LLM-powered image prompt rewriting for FLUX.1
Replaces the rule-based prompt builder with a cheap LLM call
(analysis model via OpenRouter) that distills article content into
concise visual scene descriptions. The old rule-based method becomes
the fallback if the LLM call fails.

Key design decisions:
- System prompt teaches the LLM to describe objects/setting/lighting
  instead of abstract concepts, and to avoid faces (FLUX.1 weakness)
- Uses the analysis model (gemini-2.5-flash-lite) at ~$0.001/call
- Cost is logged to the analytics dashboard via log_api_call()
- Style suffix is still appended separately so the rewriter only
  handles scene composition

Cost impact: +~$0.001 per image on top of ~$0.0008 generation cost.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 02:06:22 +07:00
peptiderepo
0e44c52ad8 feat: add AJAX endpoint for retroactive image generation
Adds wp_ajax_prautoblogger_generate_image so images can be generated
for existing posts that were published before image gen was enabled
or fixed. Uses set_time_limit(120) to handle the Cloudflare API
latency that caused fatals when run via Code Snippets init hook.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-18 00:39:10 +07:00
peptiderepo
2a734ba596 fix: align image dimensions to FLUX.1 divisible-by-8 requirement
FLUX.1 schnell requires width and height to be divisible by 8.
The default OG image size 1200×630 has 630 % 8 = 6 remainder,
causing HTTP 400 on every image generation call.

Changes:
- Pipeline default height 630 → 632 (nearest 8-aligned value)
- Provider now rounds any dimension to nearest multiple of 8 as
  a defensive guard before sending to the API

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 23:39:51 +07:00
peptiderepo
6cf8ff62fc fix: sanitize JSON-encoded array fields without mangling
The sanitize_field() fallthrough for JSON fields starting with '['
called sanitize_text_field() which escaped quotes and brackets,
breaking json_decode() on read. This caused subreddits, topic
exclusions, and enabled sources to always read back as empty arrays.

Now properly decodes, sanitizes each item, and re-encodes as clean
JSON for all three input paths: PHP array, JSON string, or CSV.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 23:20:52 +07:00
peptiderepo
b6363d8474 fix: add Cloudflare AI token to encryption list in sanitize_field
The $encrypted array was missing prautoblogger_cloudflare_ai_token,
so saving through the admin UI stored plaintext while the read path
called decrypt() — which would fail on non-encrypted data.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 22:44:53 +07:00