Compare commits
23 Commits
feature/op
...
claude/cos
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bac52d268 | ||
|
|
96f0248d81 | ||
|
|
19849a5eaf | ||
|
|
d9317ff567 | ||
|
|
30282035b5 | ||
|
|
6db6ffd7f5 | ||
|
|
1cdb41224b | ||
|
|
b2bc4be9c2 | ||
|
|
73ac6d12b4 | ||
|
|
61975d4551 | ||
|
|
ca82e395f4 | ||
|
|
3f60ecd0ff | ||
|
|
046d57877c | ||
|
|
c628fc8cbb | ||
|
|
6e9d2e3928 | ||
|
|
066e533f09 | ||
|
|
7924b47913 | ||
|
|
a5a370779a | ||
|
|
86f6801079 | ||
|
|
89c2bafeec | ||
|
|
1d46ace22f | ||
|
|
d465d6f1cf | ||
|
|
a8ba7a8ea9 |
35
.github/workflows/ci.yml
vendored
35
.github/workflows/ci.yml
vendored
@@ -21,7 +21,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
php: ['7.4', '8.1', '8.3']
|
||||
php: ['8.1', '8.2', '8.3']
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup PHP ${{ matrix.php }}
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
coverage: none
|
||||
- name: Syntax check all PHP files
|
||||
# Exclude .github/mu-plugins — those run on the production server (PHP 8+)
|
||||
# and may use PHP 8+ syntax (union types etc.) that 7.4 rejects.
|
||||
# and may use PHP 8+ syntax (union types etc.) that older versions reject.
|
||||
run: |
|
||||
set -e
|
||||
find . -name '*.php' \
|
||||
@@ -44,9 +44,14 @@ jobs:
|
||||
phpcs:
|
||||
name: PHPCS (WordPress standards)
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: false # now strict after PHPCS cleanup in v0.8.3
|
||||
continue-on-error: false # strict after PHPCS cleanup in v0.8.3
|
||||
permissions:
|
||||
contents: write # allows phpcbf auto-fix commits back to the PR branch
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.head_ref || github.ref_name }}
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
@@ -55,22 +60,34 @@ jobs:
|
||||
tools: composer:v2, phpcs
|
||||
- name: Install WordPress Coding Standards
|
||||
run: |
|
||||
# Allow the PHPCS composer-installer plugin (auto-registers standards).
|
||||
composer global config --no-plugins allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
|
||||
# WPCS 3.x requires PHPCSExtra (for the Universal.* and NormalizedArrays.* sniffs)
|
||||
# AND phpcsutils. Installing the installer itself lets it auto-register the standards path.
|
||||
composer global require --no-interaction \
|
||||
"dealerdirect/phpcodesniffer-composer-installer:^1.0" \
|
||||
"wp-coding-standards/wpcs:^3.0" \
|
||||
"phpcsstandards/phpcsutils:^1.0" \
|
||||
"phpcsstandards/phpcsextra:^1.0"
|
||||
- name: Run PHPCS
|
||||
- name: Auto-fix with phpcbf (commit back to branch if changed)
|
||||
# phpcbf exits 1 when it makes fixes, 0 when nothing to fix — both are success here.
|
||||
# Commits made via GITHUB_TOKEN do not trigger a new CI run (GitHub prevents loops).
|
||||
run: |
|
||||
phpcbf --standard=phpcs.xml \
|
||||
--extensions=php \
|
||||
--ignore=vendor/*,tests/*,node_modules/* \
|
||||
includes/ prautoblogger.php uninstall.php || true
|
||||
if ! git diff --quiet; then
|
||||
git config user.name "peptiderepo"
|
||||
git config user.email "peptiderepo@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -m "style: auto-fix PHPCS violations via phpcbf"
|
||||
git push
|
||||
fi
|
||||
- name: Run PHPCS (only non-auto-fixable violations can fail here)
|
||||
run: |
|
||||
phpcs --standard=phpcs.xml \
|
||||
--extensions=php \
|
||||
--ignore=vendor/*,tests/*,node_modules/* \
|
||||
--warning-severity=0 \
|
||||
--report=summary \
|
||||
--report=full \
|
||||
includes/ prautoblogger.php uninstall.php
|
||||
|
||||
phpunit:
|
||||
@@ -79,7 +96,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
php: ['7.4', '8.1', '8.3']
|
||||
php: ['8.1', '8.2', '8.3']
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup PHP ${{ matrix.php }}
|
||||
|
||||
99
.github/workflows/deploy.yml
vendored
99
.github/workflows/deploy.yml
vendored
@@ -4,21 +4,20 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: deploy-prautoblogger-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: PHP Lint Gate
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
- uses: actions/checkout@v4
|
||||
- uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.1'
|
||||
coverage: none
|
||||
|
||||
- name: PHP Lint Check
|
||||
run: |
|
||||
set -e
|
||||
@@ -29,38 +28,70 @@ jobs:
|
||||
-not -path './.github/*' \
|
||||
-print0 | xargs -0 -n1 -P4 php -l > /dev/null
|
||||
|
||||
deploy:
|
||||
deploy-staging:
|
||||
name: Deploy to Staging
|
||||
needs: validate
|
||||
name: Deploy to Production
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
environment: staging
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup SSH key
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
ssh-keyscan -p ${{ secrets.SSH_PORT }} ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts 2>/dev/null
|
||||
|
||||
- name: Deploy via rsync
|
||||
- name: Deploy via rsync → staging
|
||||
run: |
|
||||
rsync -avz --delete \
|
||||
--exclude '.git' \
|
||||
--exclude '.github' \
|
||||
--exclude 'tests' \
|
||||
--exclude 'phpunit.xml.dist' \
|
||||
--exclude 'composer.json' \
|
||||
--exclude 'composer.lock' \
|
||||
--exclude 'vendor' \
|
||||
--exclude '.distignore' \
|
||||
--exclude 'ARCHITECTURE.md' \
|
||||
--exclude 'CONVENTIONS.md' \
|
||||
--exclude '.git' --exclude '.github' \
|
||||
--exclude 'tests' --exclude 'phpunit.xml.dist' \
|
||||
--exclude 'composer.json' --exclude 'composer.lock' \
|
||||
--exclude 'vendor' --exclude '.distignore' \
|
||||
--exclude 'ARCHITECTURE.md' --exclude 'CONVENTIONS.md' \
|
||||
-e "ssh -i ~/.ssh/deploy_key -p ${{ secrets.SSH_PORT }}" \
|
||||
./ ${{ secrets.SSH_USERNAME }}@${{ secrets.SSH_HOST }}:~/domains/peptiderepo.com/public_html/staging/wp-content/plugins/prautoblogger/
|
||||
- name: Staging health check
|
||||
run: |
|
||||
sleep 5
|
||||
STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://staging.peptiderepo.com/ || echo "000")
|
||||
echo "Staging responded: HTTP $STATUS"
|
||||
[ "$STATUS" = "000" ] && echo "Warning: staging DNS may still be propagating" || true
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: rm -f ~/.ssh/deploy_key
|
||||
|
||||
smoke:
|
||||
name: Smoke tests (staging)
|
||||
needs: deploy-staging
|
||||
uses: peptiderepo/peptide-e2e/.github/workflows/smoke.yml@main
|
||||
secrets:
|
||||
STAGING_WP_ADMIN_USER: ${{ secrets.STAGING_WP_ADMIN_USER }}
|
||||
STAGING_WP_ADMIN_PASSWORD: ${{ secrets.STAGING_WP_ADMIN_PASSWORD }}
|
||||
|
||||
deploy-production:
|
||||
name: Deploy to Production
|
||||
needs: [validate, deploy-staging, smoke]
|
||||
runs-on: ubuntu-latest
|
||||
environment: production
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup SSH key
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
ssh-keyscan -p ${{ secrets.SSH_PORT }} ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts 2>/dev/null
|
||||
- name: Deploy via rsync → production
|
||||
run: |
|
||||
rsync -avz --delete \
|
||||
--exclude '.git' --exclude '.github' \
|
||||
--exclude 'tests' --exclude 'phpunit.xml.dist' \
|
||||
--exclude 'composer.json' --exclude 'composer.lock' \
|
||||
--exclude 'vendor' --exclude '.distignore' \
|
||||
--exclude 'ARCHITECTURE.md' --exclude 'CONVENTIONS.md' \
|
||||
-e "ssh -i ~/.ssh/deploy_key -p ${{ secrets.SSH_PORT }}" \
|
||||
./ ${{ secrets.SSH_USERNAME }}@${{ secrets.SSH_HOST }}:~/domains/peptiderepo.com/public_html/wp-content/plugins/prautoblogger/
|
||||
|
||||
- name: Purge LiteSpeed Cache
|
||||
run: |
|
||||
ssh -i ~/.ssh/deploy_key -p ${{ secrets.SSH_PORT }} \
|
||||
@@ -68,22 +99,20 @@ jobs:
|
||||
"cd ~/domains/peptiderepo.com/public_html && \
|
||||
wp litespeed-purge all 2>/dev/null || \
|
||||
(find wp-content/litespeed/ -type f -delete 2>/dev/null; touch .lscache_purge 2>/dev/null) || true"
|
||||
|
||||
- name: Health check
|
||||
- name: Production health check
|
||||
run: |
|
||||
sleep 5
|
||||
STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://peptiderepo.com)
|
||||
# 200 = normal healthy response.
|
||||
# 403 = peptide-starter-theme v1.5.2 CF-peer validator rejecting this
|
||||
# GHA-runner direct-to-origin request as non-Cloudflare traffic.
|
||||
# That rejection is the validator working — itself a positive
|
||||
# liveness signal. Real user traffic via Cloudflare gets 200.
|
||||
if [ "$STATUS" != "200" ] && [ "$STATUS" != "403" ]; then
|
||||
echo "ERROR: Site returned unexpected HTTP $STATUS after deploy"
|
||||
exit 1
|
||||
fi
|
||||
echo "Site is responsive (HTTP $STATUS)"
|
||||
|
||||
echo "Production healthy (HTTP $STATUS)"
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: rm -f ~/.ssh/deploy_key
|
||||
- name: Deploy summary
|
||||
run: |
|
||||
echo "## Deployment Complete" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Commit:** \`${GITHUB_SHA::7}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Deployed to:** peptiderepo.com" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -476,7 +476,7 @@ Stored on every PRAutoBlogger-generated post:
|
||||
| Reddit RSS | Primary Reddit data source — Atom feeds for subreddit hot posts | None (unauthenticated) | No known rate limit; reliable from datacenter IPs | `providers/class-reddit-json-client.php` |
|
||||
| Reddit .json | Fallback for posts + only source for comments | None (unauthenticated) | ~10 req/min (datacenter IPs often blocked) | `providers/class-reddit-json-client.php` |
|
||||
| Google Analytics 4 | Post performance metrics | OAuth2 service account | Standard GA4 limits | `core/class-ga4-client.php`, `core/class-metrics-collector.php` |
|
||||
| Runware (FLUX.1 via runware.ai) | **Default** image backend (v0.9.0+): schnell ~$0.0006/image, dev ~$0.02/image. True parallel generation via curl_multi. | API key (encrypted in wp_options) | Account-level quotas | `providers/class-runware-image-provider.php`, `providers/class-runware-image-pricing.php`, `providers/class-runware-image-support.php`, `providers/class-runware-image-batch.php` |
|
||||
| Runware (FLUX.1 via runware.ai) | **Default** image backend (v0.9.0+): schnell ~$0.0006/image, dev ~$0.02/image. True parallel generation via curl_multi. **v0.15.0: live model catalog sync** from `/v1/models` endpoint (task-based API); normalized to Image_Model_Registry shape; cached with 24h TTL; on-demand refresh via AJAX. | API key (encrypted in wp_options) | Account-level quotas | `providers/class-runware-image-provider.php`, `providers/class-runware-image-pricing.php`, `providers/class-runware-image-support.php`, `providers/class-runware-image-batch.php`, `providers/class-runware-model-catalog.php` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
122
CHANGELOG.md
122
CHANGELOG.md
@@ -5,7 +5,129 @@ All notable changes to PRAutoBlogger will be documented in this file.
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project uses [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [0.15.1] - 2026-05-14
|
||||
|
||||
### Fixed
|
||||
- Cost preview in AI Models settings tab no longer prints a WordPress database
|
||||
error notice; query now uses canonical column names (`prompt_tokens`,
|
||||
`completion_tokens`, `created_at`). Bug present since v0.11.0 (2026-04-23).
|
||||
|
||||
## [0.14.0] - 2026-04-26
|
||||
## [0.15.0] - 2026-04-26
|
||||
|
||||
### Added
|
||||
- **Live Runware Model Catalog Sync**: New `class-runware-model-catalog.php`
|
||||
fetches the live Runware model list via their `/v1` endpoint (task-based API),
|
||||
filters to `taskType=imageInference` (text-to-image only, excluding inpainting),
|
||||
normalizes to the Image_Model_Registry shape, and caches in `prautoblogger_runware_model_cache`
|
||||
with a 24-hour TTL. Fixes the pattern from v0.13.8 and v0.14.0 where the
|
||||
hardcoded Runware model list was a maintenance burden and gaps (missing models,
|
||||
wrong prices) went unnoticed until customer images generation broke.
|
||||
- Daily WP-Cron sync (`prautoblogger_sync_runware_models`) scheduled on activation
|
||||
and unscheduled on deactivation.
|
||||
- On-demand "Sync now" AJAX button in PRAdmin (Images settings section) with
|
||||
nonce protection and `manage_options` cap check. Refreshes model count and
|
||||
last-synced timestamp in the UI without full page reload.
|
||||
- Smart caching + fallback strategy: if cache is < 24h old, use it; if stale,
|
||||
trigger a sync; if sync fails, use the last-known-good cache; if no cache,
|
||||
fall back to hardcoded list (never returns empty array).
|
||||
- Pricing merge: Runware API may not expose per-image cost. The catalog pulls
|
||||
costs from `class-runware-image-pricing.php::COST_PER_IMAGE` on every sync,
|
||||
ensuring pricing data is always authoritative and up-to-date.
|
||||
- Unit tests for `PRAutoBlogger_Runware_Model_Catalog`: sync success/failure,
|
||||
fallback on API unreachable, stale cache behavior, cost merge logic.
|
||||
- `class-image-model-registry.php` refactored: `get_models()` now delegates to
|
||||
the catalog for Runware models + static OpenRouter list. Extracted fallback
|
||||
lists into private `get_runware_fallback_models()` and `get_openrouter_models()`
|
||||
for clarity.
|
||||
|
||||
### Fixed
|
||||
- Silent model list gaps no longer possible: Runware no longer depends on manual
|
||||
model list maintenance in the pricing class. The live catalog is the source of
|
||||
truth; pricing is merged in on every sync.
|
||||
|
||||
### Changed
|
||||
- `class-image-model-registry.php`: `get_models()` is now a thin wrapper around
|
||||
the catalog + OpenRouter static list. Breaking change: callers that expect a
|
||||
specific static list should note the new dynamic Runware side.
|
||||
|
||||
|
||||
### Fixed
|
||||
- Runware image generation now correctly uses the admin-selected model instead
|
||||
of silently falling back to FLUX.1 schnell (runware:100@1) for all non-schnell
|
||||
and non-dev selections. Root cause: `class-runware-image-pricing.php` only
|
||||
had 2 models in its `COST_PER_IMAGE` whitelist (schnell + dev), but the
|
||||
image model registry was expanded to 15 Runware models in v0.13.8 without a
|
||||
matching update to the pricing class. Any model ID not in the whitelist caused
|
||||
`resolve_model()` to fall back to schnell, so every Stable Diffusion, FLUX.2,
|
||||
HiDream, TwinFlow, Z-Image, Qwen-Image, Krea, and GLM-Image selection was
|
||||
silently downgraded.
|
||||
- Added all 15 Runware model IDs to `COST_PER_IMAGE` and `DEFAULT_STEPS` with
|
||||
correct per-image costs and step counts sourced from runware.ai/pricing (April 2026).
|
||||
- Added `@see` cross-reference to `class-image-model-registry.php` in pricing
|
||||
class docblock to prevent future drift.
|
||||
|
||||
## [0.13.9] - 2026-04-26
|
||||
|
||||
### Fixed
|
||||
- Model picker sort by price now works correctly for image models — previously
|
||||
\`applySort\` always read \`input_price_per_m\` (undefined on image models),
|
||||
so every image had an effective price of 0 and price sort was a no-op.
|
||||
Fix: detect image models via \`cost_per_image\` and use that field instead.
|
||||
|
||||
## [0.13.8] - 2026-04-26
|
||||
|
||||
### Added
|
||||
- Image model picker expanded from 7 to 21 models
|
||||
- New Runware text-to-image models: Stable Diffusion 3, HiDream-I1 Full/Dev/Fast,
|
||||
FLUX.1 Krea [dev], Qwen-Image, FLUX.2 [dev], FLUX.2 [klein] 9B, FLUX.2 [klein] 4B,
|
||||
GLM-Image, Z-Image, Z-Image-Turbo, TwinFlow Z-Image-Turbo
|
||||
- New OpenRouter model: openai/gpt-5.4-image-2
|
||||
- Registry now includes last-verified date and update instructions in source comment
|
||||
|
||||
|
||||
All notable changes to PRAutoBlogger will be documented in this file.
|
||||
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project uses [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [0.13.7] - 2026-04-24
|
||||
|
||||
### Fixed
|
||||
- Posts list column layout: title was set to 35% which, combined with 3 fixed-width PRAB columns, left ~50px for every remaining column (Author, Categories, Tags, Date all word-wrapping). Replaced with a balanced budget: title 22%, author 6%, categories 7%, tags 9%, date 8%, PRAB columns 85/85/50px, Peptide Topics 75px.
|
||||
|
||||
## [0.13.6] - 2026-04-24
|
||||
|
||||
### Fixed
|
||||
- Peptide Topics column still rendering vertically: WordPress posts table uses `table-layout: fixed` which ignores `min-width` entirely. Changed to explicit `width: 80px` which is respected under fixed-layout tables.
|
||||
|
||||
## [0.13.5] - 2026-04-24
|
||||
|
||||
### Fixed
|
||||
- Cost column in Posts list was always showing $0.00: a PHP `// phpcs:ignore` comment was embedded inside the SQL string literal, causing a MariaDB syntax error on every query. Moved comment above the `prepare()` call.
|
||||
- Peptide Topics column header in Posts list was being squeezed to near-zero width by the fixed-width PRAB columns. Added `min-width: 80px` to `.column-taxonomy-peptide_topic`.
|
||||
|
||||
## [0.13.4] - 2026-04-24
|
||||
|
||||
### Fixed
|
||||
- Model picker price column now consistently right-aligned. Root cause: price and description were siblings inside .ab-mp-row-meta, with description first and variable-length — this shifted price left/right per row. Fix: moved price to last position with flex-shrink: 0 so its right edge is always pinned to the row edge; capped description at max-width 200px with ellipsis; swapped column headers to match new DOM order.
|
||||
|
||||
## [0.13.3] - 2026-04-24
|
||||
|
||||
### Fixed
|
||||
- Price column header now right-aligned with `min-width: 90px` to match data cells — header and prices now track the same column edge.
|
||||
|
||||
## [0.13.2] - 2026-04-24
|
||||
|
||||
### Changed
|
||||
- Model picker: added sortable column headers (Model, Price, Context); clicking a header sorts the list ascending/descending; active column highlighted with sort arrow; sort preference persists while the picker is open.
|
||||
|
||||
## [0.12.3] — 2026-04-24
|
||||
## [0.13.1] - 2026-04-24
|
||||
|
||||
### Fixed
|
||||
- Model picker price column now right-aligned with a minimum width so values like `$0.0006/image` and `$0.0800/image` stack cleanly instead of floating at uneven offsets.
|
||||
|
||||
## [0.13.0] - 2026-04-24
|
||||
|
||||
### Added
|
||||
|
||||
@@ -142,6 +142,7 @@
|
||||
color: var(--ab-text-muted, #64748b);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
min-width: 90px; text-align: right; flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ab-mp-ctx {
|
||||
@@ -150,6 +151,7 @@
|
||||
background: var(--ab-bg, #f8fafc);
|
||||
padding: 2px 6px; border-radius: 4px;
|
||||
white-space: nowrap; min-width: 36px; text-align: center;
|
||||
max-width: 200px; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* ── Footer ─────────────────────────────────────────────────────────── */
|
||||
@@ -204,3 +206,59 @@
|
||||
.ab-mp-row { padding: 10px 14px; }
|
||||
.ab-mp-row-meta { gap: 8px; }
|
||||
}
|
||||
|
||||
/* ── Column headers (sortable) ──────────────────────────────────────── */
|
||||
.ab-mp-col-headers {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 5px 20px;
|
||||
border-bottom: 1px solid var(--ab-border, #e2e8f0);
|
||||
background: var(--ab-bg, #f8fafc);
|
||||
gap: 12px; /* must match .ab-mp-row gap */
|
||||
}
|
||||
|
||||
.ab-mp-col-headers-meta {
|
||||
display: flex; align-items: center;
|
||||
gap: 16px; /* must match .ab-mp-row-meta gap */
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ab-mp-col-header {
|
||||
display: inline-flex; align-items: center;
|
||||
font-size: 10px; font-weight: 700; text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--ab-text-muted, #64748b);
|
||||
cursor: pointer; user-select: none;
|
||||
background: none; border: none; padding: 3px 0;
|
||||
white-space: nowrap; line-height: 1.2;
|
||||
transition: color 0.1s ease;
|
||||
}
|
||||
.ab-mp-col-header:hover {
|
||||
color: var(--ab-text, #1e293b);
|
||||
}
|
||||
.ab-mp-col-header.ab-mp-col-active {
|
||||
color: var(--ab-primary, #4f46e5);
|
||||
}
|
||||
|
||||
/* "Model" header spans the left flex-1 area */
|
||||
.ab-mp-col-model {
|
||||
flex: 1; min-width: 0;
|
||||
}
|
||||
|
||||
/* "Price" header width matches .ab-mp-price */
|
||||
.ab-mp-col-price {
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 90px; justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* "Context" header width matches .ab-mp-ctx (min-width 36px + padding) */
|
||||
.ab-mp-col-ctx {
|
||||
min-width: 48px; justify-content: center; text-align: center;
|
||||
}
|
||||
|
||||
.ab-mp-sort-arrow {
|
||||
font-size: 9px; opacity: 0.5;
|
||||
transition: opacity 0.1s ease;
|
||||
}
|
||||
.ab-mp-col-header.ab-mp-col-active .ab-mp-sort-arrow {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Model picker popup for PRAutoBlogger admin settings.
|
||||
*
|
||||
* Fetches the OpenRouter model registry via AJAX, then renders a searchable
|
||||
* popup overlay when the user clicks a model-select trigger button. Shows
|
||||
* name, provider, input/output cost, and context window per model.
|
||||
* Fetches the OpenRouter model registry via AJAX, then renders a searchable,
|
||||
* sortable popup overlay when the user clicks a model-select trigger button.
|
||||
* Columns: Model, Price (in / out per 1M tokens), Context window.
|
||||
* Each column header is clickable to sort ascending/descending.
|
||||
*
|
||||
* @see admin/class-admin-page.php — Renders model_select fields and localizes config.
|
||||
* @see services/class-open-router-model-registry.php — Server-side registry source.
|
||||
@@ -11,54 +12,57 @@
|
||||
(function ($) {
|
||||
'use strict';
|
||||
|
||||
var config = window.prautobloggerAdmin || {};
|
||||
var cachedModels = null;
|
||||
var config = window.prautobloggerAdmin || {};
|
||||
var cachedModels = null;
|
||||
var fetchInProgress = null;
|
||||
|
||||
// Persists across open/close so the user's preferred sort is remembered.
|
||||
var sortState = { col: 'name', dir: 'asc' };
|
||||
|
||||
/**
|
||||
* Fetch models from the server (cached after first call).
|
||||
*
|
||||
* @param {string} capability Filter capability (e.g. 'text→text').
|
||||
* @return {jQuery.Deferred} Resolves with model array.
|
||||
*/
|
||||
function fetchModels(capability) {
|
||||
function fetchModels( capability ) {
|
||||
// Image models are embedded in the page config — no AJAX needed.
|
||||
if (capability === 'image_generation') {
|
||||
if ( capability === 'image_generation' ) {
|
||||
var imgModels = config.imageModels || [];
|
||||
return $.Deferred().resolve(imgModels);
|
||||
return $.Deferred().resolve( imgModels );
|
||||
}
|
||||
|
||||
if (cachedModels) {
|
||||
return $.Deferred().resolve(filterModels(cachedModels, capability));
|
||||
if ( cachedModels ) {
|
||||
return $.Deferred().resolve( filterModels( cachedModels, capability ) );
|
||||
}
|
||||
|
||||
if (fetchInProgress) {
|
||||
return fetchInProgress.then(function () {
|
||||
return filterModels(cachedModels, capability);
|
||||
});
|
||||
if ( fetchInProgress ) {
|
||||
return fetchInProgress.then( function () {
|
||||
return filterModels( cachedModels, capability );
|
||||
} );
|
||||
}
|
||||
|
||||
fetchInProgress = $.ajax({
|
||||
url: config.ajaxUrl,
|
||||
fetchInProgress = $.ajax( {
|
||||
url: config.ajaxUrl,
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: 'prautoblogger_get_models',
|
||||
nonce: config.modelsNonce
|
||||
nonce: config.modelsNonce
|
||||
},
|
||||
timeout: 15000
|
||||
}).then(function (response) {
|
||||
} ).then( function ( response ) {
|
||||
fetchInProgress = null;
|
||||
if (response.success && Array.isArray(response.data)) {
|
||||
if ( response.success && Array.isArray( response.data ) ) {
|
||||
cachedModels = response.data;
|
||||
return filterModels(cachedModels, capability);
|
||||
return filterModels( cachedModels, capability );
|
||||
}
|
||||
cachedModels = [];
|
||||
return [];
|
||||
}, function () {
|
||||
fetchInProgress = null;
|
||||
cachedModels = [];
|
||||
cachedModels = [];
|
||||
return [];
|
||||
});
|
||||
} );
|
||||
|
||||
return fetchInProgress;
|
||||
}
|
||||
@@ -70,11 +74,49 @@
|
||||
* @param {string} capability Capability string to match.
|
||||
* @return {Array} Filtered models.
|
||||
*/
|
||||
function filterModels(models, capability) {
|
||||
if (!capability) return models;
|
||||
return models.filter(function (m) {
|
||||
return m.capabilities && m.capabilities.indexOf(capability) !== -1;
|
||||
});
|
||||
function filterModels( models, capability ) {
|
||||
if ( ! capability ) return models;
|
||||
return models.filter( function ( m ) {
|
||||
return m.capabilities && m.capabilities.indexOf( capability ) !== -1;
|
||||
} );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort a model array according to the current sortState.
|
||||
* Deprecated models always sink to the bottom regardless of column.
|
||||
*
|
||||
* @param {Array} arr Model array to sort (not mutated — returns a new array).
|
||||
* @return {Array} Sorted copy.
|
||||
*/
|
||||
function applySort( arr ) {
|
||||
var col = sortState.col;
|
||||
var dir = sortState.dir;
|
||||
|
||||
return arr.slice().sort( function ( a, b ) {
|
||||
// Deprecated always last.
|
||||
if ( a.deprecated !== b.deprecated ) {
|
||||
return a.deprecated ? 1 : -1;
|
||||
}
|
||||
|
||||
var valA, valB;
|
||||
|
||||
if ( col === 'price' ) {
|
||||
// Image models use cost_per_image; text models use input_price_per_m.
|
||||
valA = ( a.cost_per_image !== undefined ) ? a.cost_per_image : ( a.input_price_per_m || 0 );
|
||||
valB = ( b.cost_per_image !== undefined ) ? b.cost_per_image : ( b.input_price_per_m || 0 );
|
||||
} else if ( col === 'context' ) {
|
||||
valA = a.context_length || 0;
|
||||
valB = b.context_length || 0;
|
||||
} else {
|
||||
// Default: sort by model name.
|
||||
valA = ( a.name || '' ).toLowerCase();
|
||||
valB = ( b.name || '' ).toLowerCase();
|
||||
}
|
||||
|
||||
if ( valA < valB ) return dir === 'asc' ? -1 : 1;
|
||||
if ( valA > valB ) return dir === 'asc' ? 1 : -1;
|
||||
return 0;
|
||||
} );
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,11 +125,11 @@
|
||||
* @param {number} price Price per 1M tokens.
|
||||
* @return {string} Formatted string like "$0.25" or "Free".
|
||||
*/
|
||||
function formatPrice(price) {
|
||||
if (!price || price <= 0) return 'Free';
|
||||
if (price < 0.01) return '$' + price.toFixed(4);
|
||||
if (price < 1) return '$' + price.toFixed(2);
|
||||
return '$' + price.toFixed(2);
|
||||
function formatPrice( price ) {
|
||||
if ( ! price || price <= 0 ) return 'Free';
|
||||
if ( price < 0.01 ) return '$' + price.toFixed( 4 );
|
||||
if ( price < 1 ) return '$' + price.toFixed( 2 );
|
||||
return '$' + price.toFixed( 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,10 +138,10 @@
|
||||
* @param {number} ctx Context length in tokens.
|
||||
* @return {string} Formatted string like "128K" or "1M".
|
||||
*/
|
||||
function formatContext(ctx) {
|
||||
if (!ctx) return '—';
|
||||
if (ctx >= 1000000) return (ctx / 1000000).toFixed(0) + 'M';
|
||||
if (ctx >= 1000) return Math.round(ctx / 1000) + 'K';
|
||||
function formatContext( ctx ) {
|
||||
if ( ! ctx ) return '—';
|
||||
if ( ctx >= 1000000 ) return ( ctx / 1000000 ).toFixed( 0 ) + 'M';
|
||||
if ( ctx >= 1000 ) return Math.round( ctx / 1000 ) + 'K';
|
||||
return ctx.toString();
|
||||
}
|
||||
|
||||
@@ -109,45 +151,47 @@
|
||||
* @param {Object} model Normalized model record.
|
||||
* @return {string} HTML string.
|
||||
*/
|
||||
function renderModelRow(model) {
|
||||
var deprecated = model.deprecated ? ' ab-mp-deprecated' : '';
|
||||
function renderModelRow( model ) {
|
||||
var deprecated = model.deprecated ? ' ab-mp-deprecated' : '';
|
||||
var isImageModel = model.cost_per_image !== undefined && model.cost_per_image > 0;
|
||||
var priceHtml, priceTitle, metaRight;
|
||||
|
||||
if (isImageModel) {
|
||||
priceHtml = '$' + model.cost_per_image.toFixed(4) + '/image';
|
||||
if ( isImageModel ) {
|
||||
priceHtml = '$' + model.cost_per_image.toFixed( 4 ) + '/image';
|
||||
priceTitle = 'Cost per generated image';
|
||||
metaRight = model.description ? '<span class="ab-mp-ctx" title="Details">' + escHtml(model.description) + '</span>' : '';
|
||||
metaRight = model.description
|
||||
? '<span class="ab-mp-ctx" title="Details">' + escHtml( model.description ) + '</span>'
|
||||
: '';
|
||||
} else {
|
||||
priceHtml = formatPrice(model.input_price_per_m) + ' / ' + formatPrice(model.output_price_per_m);
|
||||
priceHtml = formatPrice( model.input_price_per_m ) + ' / ' + formatPrice( model.output_price_per_m );
|
||||
priceTitle = 'Input / Output per 1M tokens';
|
||||
metaRight = '<span class="ab-mp-ctx" title="Context window">' + formatContext(model.context_length) + '</span>';
|
||||
metaRight = '<span class="ab-mp-ctx" title="Context window">' + formatContext( model.context_length ) + '</span>';
|
||||
}
|
||||
|
||||
return (
|
||||
'<div class="ab-mp-row' + deprecated + '" data-model-id="' + escAttr(model.id) + '">' +
|
||||
'<div class="ab-mp-row' + deprecated + '" data-model-id="' + escAttr( model.id ) + '">' +
|
||||
'<div class="ab-mp-row-main">' +
|
||||
'<span class="ab-mp-name">' + escHtml(model.name) + '</span>' +
|
||||
'<span class="ab-mp-provider">' + escHtml(model.provider) + '</span>' +
|
||||
(model.deprecated ? '<span class="ab-mp-dep-badge">deprecated</span>' : '') +
|
||||
'<span class="ab-mp-name">' + escHtml( model.name ) + '</span>' +
|
||||
'<span class="ab-mp-provider">' + escHtml( model.provider ) + '</span>' +
|
||||
( model.deprecated ? '<span class="ab-mp-dep-badge">deprecated</span>' : '' ) +
|
||||
'</div>' +
|
||||
'<div class="ab-mp-row-meta">' +
|
||||
'<span class="ab-mp-price" title="' + priceTitle + '">' + priceHtml + '</span>' +
|
||||
metaRight +
|
||||
'<span class="ab-mp-price" title="' + priceTitle + '">' + priceHtml + '</span>' +
|
||||
'</div>' +
|
||||
'</div>'
|
||||
);
|
||||
}
|
||||
|
||||
/** Minimal HTML escaping for display. */
|
||||
function escHtml(str) {
|
||||
if (!str) return '';
|
||||
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
function escHtml( str ) {
|
||||
if ( ! str ) return '';
|
||||
return str.replace( /&/g, '&' ).replace( /</g, '<' ).replace( />/g, '>' );
|
||||
}
|
||||
|
||||
/** Escape a string for use in an HTML attribute. */
|
||||
function escAttr(str) {
|
||||
return escHtml(str).replace(/"/g, '"');
|
||||
function escAttr( str ) {
|
||||
return escHtml( str ).replace( /"/g, '"' );
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -155,16 +199,16 @@
|
||||
*
|
||||
* @param {jQuery} $trigger The .ab-mp-trigger button that was clicked.
|
||||
*/
|
||||
function openPicker($trigger) {
|
||||
var fieldId = $trigger.data('field-id');
|
||||
var capability = $trigger.data('capability') || '';
|
||||
function openPicker( $trigger ) {
|
||||
var fieldId = $trigger.data( 'field-id' );
|
||||
var capability = $trigger.data( 'capability' ) || '';
|
||||
|
||||
// Build overlay + popup structure.
|
||||
var isImageCap = capability === 'image_generation';
|
||||
var priceLabel = isImageCap ? 'Cost per generated image' : 'Prices per 1M tokens (in / out)';
|
||||
|
||||
var $overlay = $('<div class="ab-mp-overlay"></div>');
|
||||
var $popup = $(
|
||||
// ── Build overlay + popup ───────────────────────────────────────
|
||||
var $overlay = $( '<div class="ab-mp-overlay"></div>' );
|
||||
var $popup = $(
|
||||
'<div class="ab-mp-popup">' +
|
||||
'<div class="ab-mp-header">' +
|
||||
'<span class="ab-mp-title">Select Model</span>' +
|
||||
@@ -173,6 +217,13 @@
|
||||
'<div class="ab-mp-search-wrap">' +
|
||||
'<input type="text" class="ab-mp-search" placeholder="Search models…" autocomplete="off" />' +
|
||||
'</div>' +
|
||||
'<div class="ab-mp-col-headers">' +
|
||||
'<button type="button" class="ab-mp-col-header ab-mp-col-model" data-col="name">Model <span class="ab-mp-sort-arrow"></span></button>' +
|
||||
'<div class="ab-mp-col-headers-meta">' +
|
||||
'<button type="button" class="ab-mp-col-header ab-mp-col-ctx" data-col="context">Context <span class="ab-mp-sort-arrow"></span></button>' +
|
||||
'<button type="button" class="ab-mp-col-header ab-mp-col-price" data-col="price">Price (in / out) <span class="ab-mp-sort-arrow"></span></button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="ab-mp-list"><div class="ab-mp-loading">Loading models…</div></div>' +
|
||||
'<div class="ab-mp-footer">' +
|
||||
'<span class="ab-mp-count"></span>' +
|
||||
@@ -181,105 +232,132 @@
|
||||
'</div>'
|
||||
);
|
||||
|
||||
$overlay.append($popup);
|
||||
$('body').append($overlay);
|
||||
$overlay.append( $popup );
|
||||
$( 'body' ).append( $overlay );
|
||||
|
||||
var $search = $popup.find('.ab-mp-search');
|
||||
var $list = $popup.find('.ab-mp-list');
|
||||
var $count = $popup.find('.ab-mp-count');
|
||||
var allModels = [];
|
||||
var $search = $popup.find( '.ab-mp-search' );
|
||||
var $list = $popup.find( '.ab-mp-list' );
|
||||
var $count = $popup.find( '.ab-mp-count' );
|
||||
var $colHeaders = $popup.find( '.ab-mp-col-headers' );
|
||||
var allModels = [];
|
||||
var currentQuery = '';
|
||||
|
||||
// Focus search after render.
|
||||
setTimeout(function () { $search.focus(); }, 50);
|
||||
setTimeout( function () { $search.focus(); }, 50 );
|
||||
|
||||
// Fetch and render model list.
|
||||
fetchModels(capability).then(function (models) {
|
||||
allModels = models;
|
||||
renderList(models, '');
|
||||
});
|
||||
|
||||
/** Render filtered model list. */
|
||||
function renderList(models, query) {
|
||||
var filtered = models;
|
||||
if (query) {
|
||||
var q = query.toLowerCase();
|
||||
filtered = models.filter(function (m) {
|
||||
return (m.name && m.name.toLowerCase().indexOf(q) !== -1) ||
|
||||
(m.id && m.id.toLowerCase().indexOf(q) !== -1) ||
|
||||
(m.provider && m.provider.toLowerCase().indexOf(q) !== -1);
|
||||
});
|
||||
}
|
||||
|
||||
// Sort: non-deprecated first, then by provider + name.
|
||||
filtered.sort(function (a, b) {
|
||||
if (a.deprecated !== b.deprecated) return a.deprecated ? 1 : -1;
|
||||
var pa = (a.provider || '').toLowerCase();
|
||||
var pb = (b.provider || '').toLowerCase();
|
||||
if (pa !== pb) return pa < pb ? -1 : 1;
|
||||
return (a.name || '').toLowerCase().localeCompare((b.name || '').toLowerCase());
|
||||
});
|
||||
|
||||
if (filtered.length === 0) {
|
||||
$list.html('<div class="ab-mp-empty">No models found.</div>');
|
||||
} else {
|
||||
var html = '';
|
||||
for (var i = 0; i < filtered.length; i++) {
|
||||
html += renderModelRow(filtered[i]);
|
||||
// ── Sort header indicators ──────────────────────────────────────
|
||||
/** Update active-column highlight and sort arrow glyphs. */
|
||||
function updateSortHeaders() {
|
||||
$colHeaders.find( '.ab-mp-col-header' ).each( function () {
|
||||
var col = $( this ).data( 'col' );
|
||||
var $arrow = $( this ).find( '.ab-mp-sort-arrow' );
|
||||
if ( col === sortState.col ) {
|
||||
$( this ).addClass( 'ab-mp-col-active' );
|
||||
$arrow.text( sortState.dir === 'asc' ? ' ▲' : ' ▼' );
|
||||
} else {
|
||||
$( this ).removeClass( 'ab-mp-col-active' );
|
||||
$arrow.text( ' ⇅' );
|
||||
}
|
||||
$list.html(html);
|
||||
}
|
||||
$count.text(filtered.length + ' model' + (filtered.length !== 1 ? 's' : ''));
|
||||
} );
|
||||
}
|
||||
|
||||
// Search input handler (debounced).
|
||||
// ── Render ──────────────────────────────────────────────────────
|
||||
/** Render filtered + sorted model list. */
|
||||
function renderList( models, query ) {
|
||||
var filtered = models;
|
||||
if ( query ) {
|
||||
var q = query.toLowerCase();
|
||||
filtered = models.filter( function ( m ) {
|
||||
return ( m.name && m.name.toLowerCase().indexOf( q ) !== -1 ) ||
|
||||
( m.id && m.id.toLowerCase().indexOf( q ) !== -1 ) ||
|
||||
( m.provider && m.provider.toLowerCase().indexOf( q ) !== -1 );
|
||||
} );
|
||||
}
|
||||
|
||||
filtered = applySort( filtered );
|
||||
|
||||
if ( filtered.length === 0 ) {
|
||||
$list.html( '<div class="ab-mp-empty">No models found.</div>' );
|
||||
} else {
|
||||
var html = '';
|
||||
for ( var i = 0; i < filtered.length; i++ ) {
|
||||
html += renderModelRow( filtered[ i ] );
|
||||
}
|
||||
$list.html( html );
|
||||
}
|
||||
$count.text( filtered.length + ' model' + ( filtered.length !== 1 ? 's' : '' ) );
|
||||
updateSortHeaders();
|
||||
}
|
||||
|
||||
// Initial render after data loads.
|
||||
fetchModels( capability ).then( function ( models ) {
|
||||
allModels = models;
|
||||
renderList( allModels, currentQuery );
|
||||
} );
|
||||
|
||||
// ── Column header sort clicks ───────────────────────────────────
|
||||
$colHeaders.on( 'click', '.ab-mp-col-header', function () {
|
||||
var col = $( this ).data( 'col' );
|
||||
if ( sortState.col === col ) {
|
||||
sortState.dir = sortState.dir === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
sortState.col = col;
|
||||
sortState.dir = 'asc';
|
||||
}
|
||||
renderList( allModels, currentQuery );
|
||||
} );
|
||||
|
||||
// ── Search (debounced) ──────────────────────────────────────────
|
||||
var searchTimer = null;
|
||||
$search.on('input', function () {
|
||||
var q = $(this).val();
|
||||
clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(function () {
|
||||
renderList(allModels, q);
|
||||
}, 150);
|
||||
});
|
||||
$search.on( 'input', function () {
|
||||
currentQuery = $( this ).val();
|
||||
clearTimeout( searchTimer );
|
||||
searchTimer = setTimeout( function () {
|
||||
renderList( allModels, currentQuery );
|
||||
}, 150 );
|
||||
} );
|
||||
|
||||
// Select a model.
|
||||
$list.on('click', '.ab-mp-row', function () {
|
||||
var id = $(this).data('model-id');
|
||||
var model = allModels.find(function (m) { return m.id === id; });
|
||||
if (!model) return;
|
||||
// ── Select a model ──────────────────────────────────────────────
|
||||
$list.on( 'click', '.ab-mp-row', function () {
|
||||
var id = $( this ).data( 'model-id' );
|
||||
var model = null;
|
||||
for ( var i = 0; i < allModels.length; i++ ) {
|
||||
if ( allModels[ i ].id === id ) { model = allModels[ i ]; break; }
|
||||
}
|
||||
if ( ! model ) return;
|
||||
|
||||
// Update hidden input + display.
|
||||
$('#' + fieldId).val(model.id);
|
||||
$trigger.find('.ab-mp-display-name').text(model.name || model.id);
|
||||
$( '#' + fieldId ).val( model.id );
|
||||
$trigger.find( '.ab-mp-display-name' ).text( model.name || model.id );
|
||||
|
||||
var isImageModel = model.cost_per_image !== undefined && model.cost_per_image > 0;
|
||||
var priceText = isImageModel
|
||||
? '$' + model.cost_per_image.toFixed(4) + '/image'
|
||||
: formatPrice(model.input_price_per_m) + ' / ' + formatPrice(model.output_price_per_m);
|
||||
$trigger.find('.ab-mp-display-price').text(priceText);
|
||||
var priceText = isImageModel
|
||||
? '$' + model.cost_per_image.toFixed( 4 ) + '/image'
|
||||
: formatPrice( model.input_price_per_m ) + ' / ' + formatPrice( model.output_price_per_m );
|
||||
$trigger.find( '.ab-mp-display-price' ).text( priceText );
|
||||
closePicker();
|
||||
});
|
||||
} );
|
||||
|
||||
// Close handlers.
|
||||
// ── Close ───────────────────────────────────────────────────────
|
||||
function closePicker() {
|
||||
$overlay.remove();
|
||||
}
|
||||
|
||||
$popup.find('.ab-mp-close').on('click', closePicker);
|
||||
$overlay.on('click', function (e) {
|
||||
if ($(e.target).is('.ab-mp-overlay')) closePicker();
|
||||
});
|
||||
$(document).on('keydown.abModelPicker', function (e) {
|
||||
if (e.key === 'Escape') {
|
||||
$popup.find( '.ab-mp-close' ).on( 'click', closePicker );
|
||||
$overlay.on( 'click', function ( e ) {
|
||||
if ( $( e.target ).is( '.ab-mp-overlay' ) ) closePicker();
|
||||
} );
|
||||
$( document ).on( 'keydown.abModelPicker', function ( e ) {
|
||||
if ( e.key === 'Escape' ) {
|
||||
closePicker();
|
||||
$(document).off('keydown.abModelPicker');
|
||||
$( document ).off( 'keydown.abModelPicker' );
|
||||
}
|
||||
});
|
||||
} );
|
||||
}
|
||||
|
||||
// Bind click on all model picker triggers.
|
||||
$(document).on('click', '.ab-mp-trigger', function (e) {
|
||||
$( document ).on( 'click', '.ab-mp-trigger', function ( e ) {
|
||||
e.preventDefault();
|
||||
openPicker($(this));
|
||||
});
|
||||
openPicker( $( this ) );
|
||||
} );
|
||||
|
||||
})(jQuery);
|
||||
} )( jQuery );
|
||||
|
||||
@@ -6,20 +6,25 @@ declare(strict_types=1);
|
||||
*
|
||||
* Static registry of available image generation models.
|
||||
*
|
||||
* What: Returns a hardcoded list of image models for the admin model picker.
|
||||
* No API discovery — updated manually when providers add/remove models.
|
||||
* What: Returns a merged list of Runware models (from live catalog sync) and
|
||||
* OpenRouter models (static list). No API discovery for OpenRouter — updated
|
||||
* manually when new models are available.
|
||||
* As of 2026-04-26, registry includes 15 Runware models (live) + 6 OpenRouter
|
||||
* models (static), ordered cheapest-to-most-expensive within each provider.
|
||||
* Who calls it: PRAutoBlogger_Admin_Page (model picker UI + save-time provider
|
||||
* derivation) and PRAutoBlogger_Image_Pipeline (provider lookup).
|
||||
* Dependencies: None.
|
||||
* Dependencies: PRAutoBlogger_Runware_Model_Catalog (live Runware models),
|
||||
* hardcoded fallback lists for resilience.
|
||||
*
|
||||
* @see admin/class-settings-fields-extended.php — Image settings reference this registry.
|
||||
* @see core/class-image-pipeline.php — Derives provider from picked model.
|
||||
* @see providers/class-runware-image-provider.php — Runware FLUX backend.
|
||||
* @see providers/class-runware-model-catalog.php — Live model sync and caching.
|
||||
*/
|
||||
class PRAutoBlogger_Image_Model_Registry {
|
||||
|
||||
/**
|
||||
* Get all available image generation models.
|
||||
* Get all available image generation models (Runware live + OpenRouter static).
|
||||
*
|
||||
* Each entry contains:
|
||||
* - id: Model identifier used in API calls.
|
||||
@@ -35,64 +40,10 @@ class PRAutoBlogger_Image_Model_Registry {
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public static function get_models(): array {
|
||||
return array(
|
||||
array(
|
||||
'id' => 'runware:100@1',
|
||||
'name' => 'FLUX.1 schnell (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0006,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Default. Fast, very cheap, comic-friendly fidelity.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:101@1',
|
||||
'name' => 'FLUX.1 dev (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.02,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Higher fidelity FLUX. ~30x schnell cost.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'google/gemini-2.5-flash-image',
|
||||
'name' => 'Gemini 2.5 Flash Image (Nano Banana)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.005,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Mid-tier quality, proven.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'google/gemini-3.1-flash-image-preview',
|
||||
'name' => 'Gemini 3.1 Flash Image (Nano Banana 2)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.008,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Latest Google. Better quality.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'google/gemini-3-pro-image-preview',
|
||||
'name' => 'Gemini 3 Pro Image (Nano Banana Pro)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.03,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Highest quality Google. Premium.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'openai/gpt-5-image-mini',
|
||||
'name' => 'GPT-5 Image Mini',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.02,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'OpenAI budget image model.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'openai/gpt-5-image',
|
||||
'name' => 'GPT-5 Image',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.08,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'OpenAI premium. Photorealistic.', 'prautoblogger' ),
|
||||
),
|
||||
);
|
||||
$catalog = new PRAutoBlogger_Runware_Model_Catalog();
|
||||
$runware_models = $catalog->get_models();
|
||||
$openrouter_models = self::get_openrouter_models();
|
||||
return array_merge( $runware_models, $openrouter_models );
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,4 +61,204 @@ class PRAutoBlogger_Image_Model_Registry {
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Hardcoded Runware model list used as fallback when the live catalog
|
||||
* sync fails or API is unreachable. Kept in sync with actual Runware
|
||||
* pricing page (runware.ai/pricing). This is the source of truth for
|
||||
* pricing data when the Runware API doesn't expose cost information.
|
||||
*
|
||||
* Last verified: 2026-04-26. To update: check runware.ai/pricing for new
|
||||
* text-to-image models and their costs.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public static function get_runware_fallback_models(): array {
|
||||
return array(
|
||||
array(
|
||||
'id' => 'runware:100@1',
|
||||
'name' => 'FLUX.1 schnell (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0006,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Default. Fast, very cheap, comic-friendly fidelity.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:twinflow-z-image-turbo@0',
|
||||
'name' => 'TwinFlow Z-Image-Turbo (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0006,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Fast text-to-image, same cost as schnell.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:400@2',
|
||||
'name' => 'FLUX.2 klein 9B (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.00078,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'FLUX.2 compact 9B. Stronger than schnell at similar cost.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:400@4',
|
||||
'name' => 'FLUX.2 klein 4B (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0006,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'FLUX.2 compact 4B. Newer architecture at schnell price.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:5@1',
|
||||
'name' => 'Stable Diffusion 3 (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0013,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Stable Diffusion 3. Sharp text, complex scenes.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:z-image@turbo',
|
||||
'name' => 'Z-Image Turbo (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0013,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Fast photorealistic generation.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:101@1',
|
||||
'name' => 'FLUX.1 dev (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.02,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Higher fidelity FLUX.1. ~30x schnell cost.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:97@3',
|
||||
'name' => 'HiDream-I1 Fast (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0038,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'HiDream-I1 Fast. Low latency, 17B quality.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:97@2',
|
||||
'name' => 'HiDream-I1 Dev (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0045,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'HiDream-I1 Dev. Strong prompt alignment.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:z-image@0',
|
||||
'name' => 'Z-Image (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0045,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'High-quality Z-Image foundation model.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:400@1',
|
||||
'name' => 'FLUX.2 dev (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0051,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'FLUX.2 dev. Controllable open text-to-image. From $0.0051.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:108@1',
|
||||
'name' => 'Qwen-Image (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0058,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Alibaba Qwen-Image. Strong text rendering in generated images.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:97@1',
|
||||
'name' => 'HiDream-I1 Full (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.009,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'HiDream-I1 Full. 17B high-fidelity, LoRA support.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:107@1',
|
||||
'name' => 'FLUX.1 Krea dev (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0098,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'FLUX.1 Krea Dev. Photorealistic open-weight generation.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'runware:glm-image@0',
|
||||
'name' => 'GLM-Image (Runware)',
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => 0.0225,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'GLM-Image. Hybrid autoregressive+diffusion, excellent text rendering.', 'prautoblogger' ),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hardcoded OpenRouter image model list. Left static for now because
|
||||
* OpenRouter's catalog is large (hundreds of models) with noisy filtering.
|
||||
* Future iteration will add smart filtering strategy (output_modalities,
|
||||
* pricing, rate limits).
|
||||
*
|
||||
* Last verified: 2026-04-26. To update: check openrouter.ai/api/v1/models
|
||||
* filtering to output_modalities containing 'image'.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private static function get_openrouter_models(): array {
|
||||
return array(
|
||||
array(
|
||||
'id' => 'google/gemini-2.5-flash-image',
|
||||
'name' => 'Gemini 2.5 Flash Image (OpenRouter)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.005,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Mid-tier quality, proven.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'google/gemini-3.1-flash-image-preview',
|
||||
'name' => 'Gemini 3.1 Flash Image (OpenRouter)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.008,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Latest Google Flash image. Better quality.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'openai/gpt-5-image-mini',
|
||||
'name' => 'GPT-5 Image Mini (OpenRouter)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.02,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'OpenAI budget image model.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'openai/gpt-5.4-image-2',
|
||||
'name' => 'GPT-5.4 Image 2 (OpenRouter)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.02,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'OpenAI GPT-5.4 image generation.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'google/gemini-3-pro-image-preview',
|
||||
'name' => 'Gemini 3 Pro Image (OpenRouter)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.03,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'Highest quality Google image. Premium.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'openai/gpt-5-image',
|
||||
'name' => 'GPT-5 Image (OpenRouter)',
|
||||
'provider' => 'openrouter',
|
||||
'cost_per_image' => 0.08,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => __( 'OpenAI premium. Photorealistic.', 'prautoblogger' ),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,10 +111,15 @@ class PRAutoBlogger_Post_List_Columns {
|
||||
return;
|
||||
}
|
||||
echo '<style>'
|
||||
. '.wp-list-table .column-title{width:35%;word-wrap:break-word;overflow-wrap:break-word}'
|
||||
. '.column-prab_writing_model{width:100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
|
||||
. '.column-prab_image_model{width:100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
|
||||
. '.column-prab_cost{width:55px;white-space:nowrap;overflow:visible}'
|
||||
. '.wp-list-table .column-title{width:22%}'
|
||||
. '.column-author{width:6%}'
|
||||
. '.column-categories{width:7%}'
|
||||
. '.column-tags{width:9%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
|
||||
. '.column-date{width:8%}'
|
||||
. '.column-prab_writing_model{width:85px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
|
||||
. '.column-prab_image_model{width:85px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
|
||||
. '.column-prab_cost{width:50px;white-space:nowrap;overflow:visible}'
|
||||
. '.column-taxonomy-peptide_topic{width:75px}'
|
||||
. '.prab-cost-wrap{position:relative;display:inline-block}'
|
||||
. '.prab-cost-trigger{font-size:12px;color:#2271b1;text-decoration:underline;cursor:pointer}'
|
||||
. '.prab-cost-popover{display:none;position:absolute;right:0;top:100%;z-index:9999;'
|
||||
@@ -182,8 +187,9 @@ class PRAutoBlogger_Post_List_Columns {
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$rows = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT stage, model, prompt_tokens, completion_tokens, estimated_cost // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
FROM {$table} WHERE post_id = %d ORDER BY id ASC",
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT stage, model, prompt_tokens, completion_tokens, estimated_cost
|
||||
FROM {$table} WHERE post_id = %d ORDER BY id ASC",
|
||||
$post_id
|
||||
),
|
||||
ARRAY_A
|
||||
|
||||
@@ -258,6 +258,13 @@ class PRAutoBlogger_Settings_Fields_Extended {
|
||||
'default' => '1',
|
||||
'description' => __( 'When the provider rejects an image prompt as NSFW, retry once with a generic fallback scene built from the article title. Disable to fail fast if the filter gets trigger-happy.', 'prautoblogger' ),
|
||||
),
|
||||
array(
|
||||
'id' => 'prautoblogger_runware_model_catalog',
|
||||
'label' => __( 'Runware Model Catalog', 'prautoblogger' ),
|
||||
'type' => 'runware_catalog_sync',
|
||||
'section' => 'prautoblogger_images',
|
||||
'description' => __( 'Live model catalog sync status and on-demand refresh.', 'prautoblogger' ),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +130,11 @@ class PRAutoBlogger_Activator {
|
||||
wp_schedule_event( $tomorrow, 'daily', 'prautoblogger_reap_orphan_research_rows' );
|
||||
}
|
||||
}
|
||||
|
||||
// v0.15.0: daily Runware model catalog sync.
|
||||
if ( ! wp_next_scheduled( 'prautoblogger_sync_runware_models' ) ) {
|
||||
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'prautoblogger_sync_runware_models' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -151,6 +151,53 @@ class PRAutoBlogger_Ajax_Handlers {
|
||||
wp_send_json_success( $results );
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler: sync Runware model catalog on demand.
|
||||
*
|
||||
* Nonce-protected and requires manage_options capability.
|
||||
* Returns the updated cache timestamp and model count.
|
||||
*
|
||||
* Side effects: makes HTTP request to Runware API, writes WP options.
|
||||
*/
|
||||
public function on_ajax_sync_runware_models_now(): void {
|
||||
check_ajax_referer( 'prautoblogger_sync_runware_models_now', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$catalog = new PRAutoBlogger_Runware_Model_Catalog();
|
||||
$success = $catalog->sync();
|
||||
|
||||
if ( ! $success ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Catalog sync failed. Check logs for details.', 'prautoblogger' ) ) );
|
||||
return;
|
||||
}
|
||||
|
||||
$models = $catalog->get_models();
|
||||
$synced_at = $catalog->get_last_synced_at();
|
||||
$synced_at_str = $synced_at
|
||||
? wp_date( __( 'Y-m-d H:i:s', 'prautoblogger' ), $synced_at )
|
||||
: __( 'Never', 'prautoblogger' );
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'message' => __( 'Runware model catalog synced successfully.', 'prautoblogger' ),
|
||||
'model_count' => count( $models ),
|
||||
'synced_at' => $synced_at_str,
|
||||
)
|
||||
);
|
||||
} catch ( \Throwable $e ) {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'AJAX sync Runware models failed: %s (%s)', $e->getMessage(), get_class( $e ) ),
|
||||
'runware-catalog'
|
||||
);
|
||||
wp_send_json_error( array( 'message' => $e->getMessage() ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the shared model registry instance.
|
||||
*
|
||||
|
||||
1
includes/class-deactivator.php
Executable file → Normal file
1
includes/class-deactivator.php
Executable file → Normal file
@@ -39,6 +39,7 @@ class PRAutoBlogger_Deactivator {
|
||||
'prautoblogger_daily_generation',
|
||||
'prautoblogger_collect_metrics',
|
||||
'prautoblogger_reap_orphan_research_rows',
|
||||
'prautoblogger_sync_runware_models',
|
||||
);
|
||||
|
||||
foreach ( $hooks as $hook ) {
|
||||
|
||||
@@ -116,6 +116,8 @@ class PRAutoBlogger {
|
||||
|
||||
$registry = $this->executor->get_model_registry();
|
||||
add_action( 'prautoblogger_refresh_model_registry', array( $registry, 'refresh' ) );
|
||||
// v0.15.0: daily Runware model catalog sync to keep the live model list fresh.
|
||||
add_action( 'prautoblogger_sync_runware_models', array( new PRAutoBlogger_Runware_Model_Catalog(), 'sync' ) );
|
||||
|
||||
// Opik observability: async trace/span dispatch.
|
||||
add_action(
|
||||
@@ -179,6 +181,7 @@ class PRAutoBlogger {
|
||||
add_action( 'wp_ajax_prautoblogger_test_connection', array( $this->ajax_handlers, 'on_ajax_test_connection' ) );
|
||||
add_action( 'wp_ajax_prautoblogger_get_models', array( $this->ajax_handlers, 'on_ajax_get_models' ) );
|
||||
add_action( 'wp_ajax_prautoblogger_refresh_models', array( new PRAutoBlogger_Model_Registry_Refresh( $this->ajax_handlers->get_registry() ), 'handle' ) );
|
||||
add_action( 'wp_ajax_prautoblogger_sync_runware_models_now', array( $this->ajax_handlers, 'on_ajax_sync_runware_models_now' ) );
|
||||
|
||||
$review_queue = new PRAutoBlogger_Review_Queue();
|
||||
add_action( 'wp_ajax_prautoblogger_approve_post', array( $review_queue, 'on_ajax_approve_post' ) );
|
||||
|
||||
@@ -235,19 +235,19 @@ class PRAutoBlogger_Cost_Tracker {
|
||||
);
|
||||
}
|
||||
|
||||
$cutoff_time = time() - ( $days * DAY_IN_SECONDS );
|
||||
$stage_list = implode( ',', array_map( array( $wpdb, 'prepare' ), array_fill( 0, count( $stages ), '%s' ), $stages ) );
|
||||
$table_name = $wpdb->prefix . 'prautoblogger_generation_log';
|
||||
$cutoff_datetime = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );
|
||||
$stage_list = implode( ',', array_map( array( $wpdb, 'prepare' ), array_fill( 0, count( $stages ), '%s' ), $stages ) );
|
||||
$table_name = $wpdb->prefix . 'prautoblogger_generation_log';
|
||||
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Prepared stage list via array_map + prepare
|
||||
$query = $wpdb->prepare(
|
||||
"SELECT AVG(input_tokens) as avg_input,
|
||||
AVG(output_tokens) as avg_output,
|
||||
"SELECT AVG(prompt_tokens) as avg_prompt,
|
||||
AVG(completion_tokens) as avg_completion,
|
||||
COUNT(*) as sample_count
|
||||
FROM $table_name
|
||||
WHERE stage IN ( $stage_list )
|
||||
AND timestamp >= %d",
|
||||
$cutoff_time
|
||||
AND created_at >= %s",
|
||||
$cutoff_datetime
|
||||
);
|
||||
|
||||
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- phpcs pragma above
|
||||
@@ -262,8 +262,8 @@ class PRAutoBlogger_Cost_Tracker {
|
||||
}
|
||||
|
||||
return array(
|
||||
'avg_prompt_tokens' => (float) ( $result['avg_input'] ?? 0 ),
|
||||
'avg_completion_tokens' => (float) ( $result['avg_output'] ?? 0 ),
|
||||
'avg_prompt_tokens' => (float) ( $result['avg_prompt'] ?? 0 ),
|
||||
'avg_completion_tokens' => (float) ( $result['avg_completion'] ?? 0 ),
|
||||
'sample_size' => (int) ( $result['sample_count'] ?? 0 ),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,44 +6,87 @@ declare(strict_types=1);
|
||||
*
|
||||
* Pricing + model-id resolution helpers for the Runware image provider.
|
||||
*
|
||||
* Each Runware FLUX model has a flat per-image cost sourced from
|
||||
* Each Runware model has a flat per-image cost sourced from
|
||||
* runware.ai/pricing (April 2026). Unlike OpenRouter models, Runware
|
||||
* prices scale slightly with steps — the quoted rate here assumes the
|
||||
* provider's default step count (4 for schnell, 28 for dev).
|
||||
* provider's default step count for each model.
|
||||
*
|
||||
* Triggered by: PRAutoBlogger_Runware_Image_Provider, PRAutoBlogger_Runware_Image_Batch.
|
||||
* Dependencies: None — pure calculation + option reads.
|
||||
*
|
||||
* @see class-runware-image-provider.php — Primary caller.
|
||||
* @see class-runware-model-catalog.php — Live model sync; authoritative pricing source.
|
||||
* @see class-open-router-image-pricing.php — Sibling pattern for OpenRouter.
|
||||
* @see admin/class-image-model-registry.php — Source of truth for model list; keep in sync.
|
||||
*/
|
||||
class PRAutoBlogger_Runware_Image_Pricing {
|
||||
|
||||
/**
|
||||
* Flat per-image cost (USD) for each supported Runware model, April 2026.
|
||||
* Update here when Runware reprices or new models launch.
|
||||
* Update here when Runware reprices or new models launch. Must stay in
|
||||
* sync with the model list in PRAutoBlogger_Image_Model_Registry — any
|
||||
* model listed there that is absent here will silently fall back to schnell.
|
||||
*
|
||||
* Runware model IDs use `family:variant@version` form. The two FLUX
|
||||
* variants we support are the CEO-sanctioned defaults.
|
||||
* Runware model IDs use `family:variant@version` form.
|
||||
*
|
||||
* @var array<string, float>
|
||||
*/
|
||||
private const COST_PER_IMAGE = array(
|
||||
// FLUX.1 schnell — 4-step distilled. Our new default (2026-04-21).
|
||||
'runware:100@1' => 0.0006,
|
||||
// FLUX.1 dev — 28-step full model. Higher fidelity, ~30x cost.
|
||||
'runware:101@1' => 0.02,
|
||||
// FLUX.1 schnell — 4-step distilled. Default (2026-04-21).
|
||||
'runware:100@1' => 0.0006,
|
||||
// TwinFlow Z-Image-Turbo — fast text-to-image, same cost as schnell.
|
||||
'runware:twinflow-z-image-turbo@0' => 0.0006,
|
||||
// FLUX.2 klein 4B — newer architecture at schnell price.
|
||||
'runware:400@4' => 0.0006,
|
||||
// FLUX.2 klein 9B — stronger than schnell, similar cost.
|
||||
'runware:400@2' => 0.00078,
|
||||
// Stable Diffusion 3 — sharp text, complex scenes.
|
||||
'runware:5@1' => 0.0013,
|
||||
// Z-Image Turbo — fast photorealistic generation.
|
||||
'runware:z-image@turbo' => 0.0013,
|
||||
// HiDream-I1 Fast — low latency, 17B quality.
|
||||
'runware:97@3' => 0.0038,
|
||||
// HiDream-I1 Dev — strong prompt alignment.
|
||||
'runware:97@2' => 0.0045,
|
||||
// Z-Image — high-quality foundation model.
|
||||
'runware:z-image@0' => 0.0045,
|
||||
// FLUX.2 dev — controllable open text-to-image.
|
||||
'runware:400@1' => 0.0051,
|
||||
// Qwen-Image — strong text rendering in generated images.
|
||||
'runware:108@1' => 0.0058,
|
||||
// HiDream-I1 Full — 17B high-fidelity, LoRA support.
|
||||
'runware:97@1' => 0.009,
|
||||
// FLUX.1 Krea dev — photorealistic open-weight generation.
|
||||
'runware:107@1' => 0.0098,
|
||||
// FLUX.1 dev — 28-step full model. Higher fidelity, ~30x schnell cost.
|
||||
'runware:101@1' => 0.02,
|
||||
// GLM-Image — hybrid autoregressive+diffusion, excellent text rendering.
|
||||
'runware:glm-image@0' => 0.0225,
|
||||
);
|
||||
|
||||
/**
|
||||
* Default number of inference steps per model. Runware bills per image
|
||||
* at the model's standard step count; custom step counts may alter price.
|
||||
* Sources: runware.ai/models (April 2026).
|
||||
*
|
||||
* @var array<string, int>
|
||||
*/
|
||||
private const DEFAULT_STEPS = array(
|
||||
'runware:100@1' => 4,
|
||||
'runware:101@1' => 28,
|
||||
'runware:100@1' => 4,
|
||||
'runware:twinflow-z-image-turbo@0' => 4,
|
||||
'runware:400@4' => 20,
|
||||
'runware:400@2' => 20,
|
||||
'runware:5@1' => 28,
|
||||
'runware:z-image@turbo' => 4,
|
||||
'runware:97@3' => 16,
|
||||
'runware:97@2' => 28,
|
||||
'runware:z-image@0' => 28,
|
||||
'runware:400@1' => 28,
|
||||
'runware:108@1' => 20,
|
||||
'runware:97@1' => 50,
|
||||
'runware:107@1' => 28,
|
||||
'runware:101@1' => 28,
|
||||
'runware:glm-image@0' => 30,
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -77,9 +120,9 @@ class PRAutoBlogger_Runware_Image_Pricing {
|
||||
/**
|
||||
* Estimate USD cost for a single image at the given model.
|
||||
*
|
||||
* Runware FLUX pricing is flat per image at the model's standard step
|
||||
* count. Width/height are accepted for interface compatibility but do
|
||||
* not affect cost for the variants we support.
|
||||
* Runware pricing is flat per image at the model's standard step count.
|
||||
* Width/height are accepted for interface compatibility but do not affect
|
||||
* cost for the variants we support.
|
||||
*
|
||||
* @param int $width Width in pixels (unused for flat pricing).
|
||||
* @param int $height Height in pixels (unused for flat pricing).
|
||||
|
||||
298
includes/providers/class-runware-model-catalog.php
Normal file
298
includes/providers/class-runware-model-catalog.php
Normal file
@@ -0,0 +1,298 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
|
||||
*
|
||||
* Runware model catalog sync — fetches live model list via Runware's /v1 endpoint,
|
||||
* filters to text-to-image tasks, caches normalized results, and falls back to
|
||||
* hardcoded list on API failure.
|
||||
*
|
||||
* What: Syncs Runware's model catalog periodically (daily cron + on-demand AJAX),
|
||||
* caches the results in WP options, and merges pricing data from the pricing
|
||||
* class when Runware's API doesn't expose it.
|
||||
* Who triggers it: Daily cron (prautoblogger_sync_runware_models), AJAX "Sync now"
|
||||
* button in PRAdmin, and lazy-load via PRAutoBlogger_Image_Model_Registry.
|
||||
* Dependencies: PRAutoBlogger_Logger, PRAutoBlogger_Runware_Image_Pricing,
|
||||
* PRAutoBlogger_Image_Model_Registry.
|
||||
*
|
||||
* @see class-runware-image-pricing.php — Authoritative pricing source & fallback models.
|
||||
* @see admin/class-image-model-registry.php — Caller; merges Runware + OpenRouter lists.
|
||||
* @see class-prautoblogger.php — Registers daily cron + AJAX hook.
|
||||
* @see class-activator.php / class-deactivator.php — Schedule / unschedule on activation/deactivation.
|
||||
*/
|
||||
class PRAutoBlogger_Runware_Model_Catalog {
|
||||
|
||||
private const RUNWARE_API_URL = 'https://api.runware.ai/v1';
|
||||
private const CACHE_TTL_SECONDS = 86400;
|
||||
private const HTTP_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* Fetch the Runware model catalog, normalize to the Image_Model_Registry
|
||||
* shape, and write to WP options cache. Returns true on success, false on
|
||||
* API failure or parse error.
|
||||
*
|
||||
* Side effects: makes HTTP request to Runware API, writes WP options.
|
||||
* Error handling: logs via PRAutoBlogger_Logger, never throws, always
|
||||
* returns bool to allow fallback to cached list.
|
||||
*
|
||||
* @return bool True on successful fetch and cache update; false on API or parse error.
|
||||
*/
|
||||
public function sync(): bool {
|
||||
try {
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
'Runware model catalog sync: API key not configured. Using cached/fallback models.',
|
||||
'runware-catalog'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
$raw_models = $this->fetch_models_from_api( $api_key );
|
||||
if ( empty( $raw_models ) ) {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
'Runware model catalog fetch returned empty list. Using cached/fallback models.',
|
||||
'runware-catalog'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
$normalized = $this->normalize_models( $raw_models );
|
||||
$with_pricing = $this->merge_pricing( $normalized );
|
||||
|
||||
if ( empty( $with_pricing ) ) {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
'Runware model catalog normalization resulted in empty list. Using cached/fallback models.',
|
||||
'runware-catalog'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
update_option( 'prautoblogger_runware_model_cache', $with_pricing, false );
|
||||
update_option( 'prautoblogger_runware_model_cache_updated_at', time(), false );
|
||||
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf( 'Runware model catalog synced: %d models cached.', count( $with_pricing ) ),
|
||||
'runware-catalog'
|
||||
);
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'Runware model catalog sync failed: %s (%s)', $e->getMessage(), get_class( $e ) ),
|
||||
'runware-catalog'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the normalized model list, with smart caching logic:
|
||||
* - If cache is fresh (< 24h), return it.
|
||||
* - If cache is stale or absent, trigger a sync.
|
||||
* - If sync fails, return the last-known-good cache.
|
||||
* - If no cache exists, return the hardcoded fallback (never empty).
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Normalized model list.
|
||||
*/
|
||||
public function get_models(): array {
|
||||
if ( ! $this->is_stale() ) {
|
||||
$cached = get_option( 'prautoblogger_runware_model_cache', array() );
|
||||
if ( is_array( $cached ) && ! empty( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $this->sync() ) {
|
||||
$cached = get_option( 'prautoblogger_runware_model_cache', array() );
|
||||
if ( is_array( $cached ) && ! empty( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
}
|
||||
|
||||
$cached = get_option( 'prautoblogger_runware_model_cache', array() );
|
||||
if ( is_array( $cached ) && ! empty( $cached ) ) {
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
'Using stale Runware model cache (live sync failed).',
|
||||
'runware-catalog'
|
||||
);
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$fallback = PRAutoBlogger_Image_Model_Registry::get_runware_fallback_models();
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf(
|
||||
'No Runware model cache available; using hardcoded fallback (%d models).',
|
||||
count( $fallback )
|
||||
),
|
||||
'runware-catalog'
|
||||
);
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Unix timestamp of the last successful sync, or null if never synced.
|
||||
*
|
||||
* @return int|null Unix timestamp, or null if never synced.
|
||||
*/
|
||||
public function get_last_synced_at(): ?int {
|
||||
$ts = get_option( 'prautoblogger_runware_model_cache_updated_at', null );
|
||||
if ( null === $ts ) {
|
||||
return null;
|
||||
}
|
||||
$ts = (int) $ts;
|
||||
return $ts > 0 ? $ts : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cache is stale (older than 24h) or absent.
|
||||
*
|
||||
* @return bool True if cache should be refreshed; false if still fresh.
|
||||
*/
|
||||
public function is_stale(): bool {
|
||||
$updated_at = $this->get_last_synced_at();
|
||||
if ( null === $updated_at ) {
|
||||
return true;
|
||||
}
|
||||
return ( time() - $updated_at ) > self::CACHE_TTL_SECONDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the raw model list from Runware's /v1 endpoint via a models task.
|
||||
*
|
||||
* @param string $api_key Decrypted Runware API key.
|
||||
* @return array Raw model list (may be empty).
|
||||
* @throws \RuntimeException On HTTP error or malformed response.
|
||||
*/
|
||||
private function fetch_models_from_api( string $api_key ): array {
|
||||
$body = wp_json_encode(
|
||||
array(
|
||||
array(
|
||||
'taskType' => 'models',
|
||||
'apiKey' => $api_key,
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
$response = wp_remote_post(
|
||||
self::RUNWARE_API_URL,
|
||||
array(
|
||||
'timeout' => self::HTTP_TIMEOUT_SECONDS,
|
||||
'headers' => array( 'Content-Type' => 'application/json' ),
|
||||
'body' => $body,
|
||||
)
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Runware models endpoint unreachable: %s', $response->get_error_message() )
|
||||
);
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status ) {
|
||||
$raw = wp_remote_retrieve_body( $response );
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Runware models endpoint returned HTTP %d', $status )
|
||||
);
|
||||
}
|
||||
|
||||
$raw = (string) wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $raw, true );
|
||||
|
||||
if ( ! is_array( $decoded ) ) {
|
||||
throw new \RuntimeException( 'Runware models response is not valid JSON.' );
|
||||
}
|
||||
|
||||
if ( isset( $decoded['errors'] ) && is_array( $decoded['errors'] ) && ! empty( $decoded['errors'] ) ) {
|
||||
throw new \RuntimeException( 'Runware API returned an error.' );
|
||||
}
|
||||
|
||||
$data = $decoded['data'] ?? array();
|
||||
return is_array( $data ) ? $data : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize raw Runware model objects to the PRAutoBlogger_Image_Model_Registry
|
||||
* shape: id, name, provider, cost_per_image, capabilities, description.
|
||||
*
|
||||
* Filters to taskType='imageInference' (text-to-image only), excluding
|
||||
* inpainting (imageInference + requiresImage=true), img2img, video, upscalers.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $raw_models Raw API response.
|
||||
* @return array<int, array<string, mixed>> Normalized models.
|
||||
*/
|
||||
private function normalize_models( array $raw_models ): array {
|
||||
$normalized = array();
|
||||
|
||||
foreach ( $raw_models as $raw ) {
|
||||
if ( ! is_array( $raw ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$task_type = $raw['taskType'] ?? '';
|
||||
if ( 'imageInference' !== $task_type ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( isset( $raw['requiresImage'] ) && true === $raw['requiresImage'] ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$model_id = (string) ( $raw['id'] ?? '' );
|
||||
if ( '' === $model_id ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[] = array(
|
||||
'id' => $model_id,
|
||||
'name' => (string) ( $raw['name'] ?? $model_id ),
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => null,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => (string) ( $raw['description'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge pricing data from PRAutoBlogger_Runware_Image_Pricing into the
|
||||
* normalized catalog. Models without pricing data get cost_per_image=null.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $normalized Normalized models.
|
||||
* @return array<int, array<string, mixed>> Models with pricing merged.
|
||||
*/
|
||||
private function merge_pricing( array $normalized ): array {
|
||||
$pricing_table = PRAutoBlogger_Runware_Image_Pricing::get_model_costs();
|
||||
|
||||
foreach ( $normalized as &$model ) {
|
||||
$model_id = $model['id'] ?? '';
|
||||
if ( isset( $pricing_table[ $model_id ] ) ) {
|
||||
$model['cost_per_image'] = (float) $pricing_table[ $model_id ];
|
||||
}
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decrypted Runware API key from settings.
|
||||
*
|
||||
* @return string Plaintext key, or empty string if not configured.
|
||||
*/
|
||||
private function get_api_key(): string {
|
||||
$stored = (string) get_option( 'prautoblogger_runware_api_key', '' );
|
||||
if ( '' === $stored ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( PRAutoBlogger_Encryption::is_encrypted( $stored ) ) {
|
||||
$decrypted = PRAutoBlogger_Encryption::decrypt( $stored );
|
||||
return '' === $decrypted ? '' : $decrypted;
|
||||
}
|
||||
|
||||
return $stored;
|
||||
}
|
||||
}
|
||||
5
patchwork.json
Normal file
5
patchwork.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"redefinable-internals": [
|
||||
"time"
|
||||
]
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
* Plugin Name: PRAutoBlogger
|
||||
* Plugin URI: https://peptiderepo.com/prautoblogger
|
||||
* Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics.
|
||||
* Version: 0.13.0
|
||||
* Version: 0.15.1
|
||||
* Requires at least: 6.0
|
||||
* Requires PHP: 7.4
|
||||
* Author: PeptideRepo
|
||||
@@ -35,7 +35,7 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||
| Defined here so every file in the plugin can reference paths, versions,
|
||||
| and limits without magic strings.
|
||||
*/
|
||||
define( 'PRAUTOBLOGGER_VERSION', '0.13.0' );
|
||||
define( 'PRAUTOBLOGGER_VERSION', '0.15.1' );
|
||||
define( 'PRAUTOBLOGGER_DB_VERSION', '1.1.0' );
|
||||
define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ );
|
||||
define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
|
||||
|
||||
@@ -63,6 +63,9 @@ if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL' ) ) {
|
||||
if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL' ) ) {
|
||||
define( 'PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL', 'runware:100@1' );
|
||||
}
|
||||
if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_IMAGE_PROVIDER' ) ) {
|
||||
define( 'PRAUTOBLOGGER_DEFAULT_IMAGE_PROVIDER', 'runware' );
|
||||
}
|
||||
|
||||
// Default image style suffix used by ImagePromptBuilder and settings UI.
|
||||
if ( ! defined( 'PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX' ) ) {
|
||||
|
||||
@@ -113,4 +113,139 @@ class CostTrackerTest extends BaseTestCase {
|
||||
// If we get here without exception, the method worked.
|
||||
$this->assertTrue( true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: get_avg_tokens_for_stages must return the documented zero
|
||||
* shape when there is no generation history, without leaving a $wpdb
|
||||
* error behind.
|
||||
*
|
||||
* Load-bearing: asserting $wpdb->last_error === '' alongside the shape
|
||||
* is what would have caught the v0.11.0 column-name drift. The empty-
|
||||
* result fallback silently masked the failure from shape-only tests.
|
||||
*/
|
||||
public function test_get_avg_tokens_returns_zero_shape_when_no_history(): void {
|
||||
$captured_query = '';
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
function ( $sql, ...$args ) use ( &$captured_query ) {
|
||||
$captured_query = $sql;
|
||||
return $sql; // Simulate prepared SQL passthrough.
|
||||
}
|
||||
);
|
||||
// Empty result row — fallback branch.
|
||||
$this->wpdb->method( 'get_row' )->willReturn( null );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$result = $tracker->get_avg_tokens_for_stages( [ 'analysis' ], 30 );
|
||||
|
||||
$this->assertSame(
|
||||
[
|
||||
'avg_prompt_tokens' => 0.0,
|
||||
'avg_completion_tokens' => 0.0,
|
||||
'sample_size' => 0,
|
||||
],
|
||||
$result
|
||||
);
|
||||
$this->assertSame( '', $this->wpdb->last_error, 'wpdb->last_error must be empty after the query' );
|
||||
|
||||
// Schema-drift guard: query must reference canonical columns, not the
|
||||
// pre-v0.15.1 names that don't exist on wp_prautoblogger_generation_log.
|
||||
$this->assertStringContainsString( 'prompt_tokens', $captured_query );
|
||||
$this->assertStringContainsString( 'completion_tokens', $captured_query );
|
||||
$this->assertStringContainsString( 'created_at', $captured_query );
|
||||
$this->assertStringNotContainsString( 'input_tokens', $captured_query );
|
||||
$this->assertStringNotContainsString( 'output_tokens', $captured_query );
|
||||
// The bug query had `AND timestamp >= %d`; canonical query uses
|
||||
// `AND created_at >= %s`. Guard against the column reference, not the
|
||||
// bare word (a SQL comment in future code could legitimately mention
|
||||
// "timestamp" in prose).
|
||||
$this->assertStringNotContainsString( 'timestamp >=', $captured_query );
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: with seeded rows the method returns real averages and the
|
||||
* canonical SELECT aliases (avg_prompt / avg_completion) are extracted
|
||||
* correctly.
|
||||
*/
|
||||
public function test_get_avg_tokens_returns_real_averages_with_seeded_rows(): void {
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
return $sql;
|
||||
}
|
||||
);
|
||||
// Simulate three rows averaged: prompt_tokens=100, completion_tokens=50.
|
||||
$this->wpdb->method( 'get_row' )->willReturn(
|
||||
[
|
||||
'avg_prompt' => '100.0000',
|
||||
'avg_completion' => '50.0000',
|
||||
'sample_count' => '3',
|
||||
]
|
||||
);
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$result = $tracker->get_avg_tokens_for_stages( [ 'analysis' ], 30 );
|
||||
|
||||
$this->assertSame( 100.0, $result['avg_prompt_tokens'] );
|
||||
$this->assertSame( 50.0, $result['avg_completion_tokens'] );
|
||||
$this->assertSame( 3, $result['sample_size'] );
|
||||
$this->assertSame( '', $this->wpdb->last_error );
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: the days cutoff must be a MySQL DATETIME string (compared
|
||||
* against the canonical created_at column), not a unix int. Captured via
|
||||
* the prepare() callback so we can inspect the bound parameter.
|
||||
*/
|
||||
public function test_get_avg_tokens_respects_days_cutoff_as_datetime(): void {
|
||||
$captured_args = [];
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
function ( $sql, ...$args ) use ( &$captured_args ) {
|
||||
$captured_args = $args;
|
||||
return $sql;
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_row' )->willReturn( null );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$tracker->get_avg_tokens_for_stages( [ 'analysis' ], 30 );
|
||||
|
||||
// Exactly one bound param: the DATETIME cutoff.
|
||||
$this->assertCount( 1, $captured_args );
|
||||
$this->assertIsString( $captured_args[0], 'Cutoff must be a DATETIME string, not a unix int' );
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/',
|
||||
$captured_args[0]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: the stage filter is propagated into the SQL. Calling with
|
||||
* a single stage should result in exactly one prepared %s placeholder
|
||||
* for the IN ( … ) list.
|
||||
*/
|
||||
public function test_get_avg_tokens_filters_by_stage(): void {
|
||||
$stage_prepare_calls = 0;
|
||||
$main_query = '';
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
function ( $sql, ...$args ) use ( &$stage_prepare_calls, &$main_query ) {
|
||||
// The method calls $wpdb->prepare twice in two distinct shapes:
|
||||
// 1. per-stage placeholder prep (sql='%s', single arg)
|
||||
// 2. the main SELECT (sql contains 'SELECT', many tokens)
|
||||
if ( strpos( $sql, 'SELECT' ) !== false ) {
|
||||
$main_query = $sql;
|
||||
} else {
|
||||
++$stage_prepare_calls;
|
||||
}
|
||||
return $sql;
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_row' )->willReturn( null );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$tracker->get_avg_tokens_for_stages( [ 'analysis' ], 30 );
|
||||
|
||||
$this->assertSame( 1, $stage_prepare_calls, 'One stage → one per-stage prepare() call' );
|
||||
$this->assertStringContainsString( 'stage IN', $main_query );
|
||||
$this->assertStringContainsString( 'wp_prautoblogger_generation_log', $main_query );
|
||||
$this->assertSame( '', $this->wpdb->last_error );
|
||||
}
|
||||
}
|
||||
|
||||
189
tests/unit/Providers/RunwareModelCatalogTest.php
Normal file
189
tests/unit/Providers/RunwareModelCatalogTest.php
Normal file
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Runware_Model_Catalog.
|
||||
*
|
||||
* Validates live sync, fallback logic, cache staleness, and pricing merge.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Providers
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Providers;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
use Brain\Monkey\Actions;
|
||||
|
||||
class RunwareModelCatalogTest extends BaseTestCase {
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
// Mock WP options for cache simulation.
|
||||
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
|
||||
static $options = array();
|
||||
return $options[ $key ] ?? $default;
|
||||
} );
|
||||
Functions\when( 'update_option' )->alias( function ( $key, $value ) {
|
||||
static $options = array();
|
||||
$options[ $key ] = $value;
|
||||
return true;
|
||||
} );
|
||||
Functions\when( 'time' )->justReturn( 1704067200 ); // 2024-01-01 00:00:00
|
||||
}
|
||||
|
||||
/** Sync with empty or missing API key returns false. */
|
||||
public function test_sync_no_api_key(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
$this->assertFalse( $result );
|
||||
}
|
||||
|
||||
/** get_models returns fallback if no cache and sync fails. */
|
||||
public function test_get_models_fallback_on_sync_failure(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
// Should have the fallback list (15 Runware models).
|
||||
$this->assertIsArray( $models );
|
||||
$this->assertGreaterThan( 0, count( $models ) );
|
||||
|
||||
// Check at least one expected fallback model exists.
|
||||
$schnell_exists = false;
|
||||
foreach ( $models as $model ) {
|
||||
if ( 'runware:100@1' === ( $model['id'] ?? '' ) ) {
|
||||
$schnell_exists = true;
|
||||
$this->assertSame( 'FLUX.1 schnell (Runware)', $model['name'] );
|
||||
$this->assertSame( 'runware', $model['provider'] );
|
||||
break;
|
||||
}
|
||||
}
|
||||
$this->assertTrue( $schnell_exists, 'Fallback should include FLUX.1 schnell' );
|
||||
}
|
||||
|
||||
/** is_stale returns true if never synced. */
|
||||
public function test_is_stale_never_synced(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertTrue( $catalog->is_stale() );
|
||||
}
|
||||
|
||||
/** get_last_synced_at returns null if never synced. */
|
||||
public function test_get_last_synced_at_never(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertNull( $catalog->get_last_synced_at() );
|
||||
}
|
||||
|
||||
/** Fallback list is never empty. */
|
||||
public function test_get_models_never_empty(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
|
||||
// Even with no cache and failed sync, get_models should return the fallback.
|
||||
$models = $catalog->get_models();
|
||||
$this->assertIsArray( $models );
|
||||
$this->assertNotEmpty( $models );
|
||||
|
||||
// All models should have required fields.
|
||||
foreach ( $models as $model ) {
|
||||
$this->assertArrayHasKey( 'id', $model );
|
||||
$this->assertArrayHasKey( 'name', $model );
|
||||
$this->assertArrayHasKey( 'provider', $model );
|
||||
$this->assertArrayHasKey( 'capabilities', $model );
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback models have correct pricing. */
|
||||
public function test_fallback_models_have_pricing(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
$schnell = null;
|
||||
$dev = null;
|
||||
foreach ( $models as $model ) {
|
||||
if ( 'runware:100@1' === $model['id'] ) {
|
||||
$schnell = $model;
|
||||
}
|
||||
if ( 'runware:101@1' === $model['id'] ) {
|
||||
$dev = $model;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotNull( $schnell );
|
||||
$this->assertEqualsWithDelta( 0.0006, $schnell['cost_per_image'], 0.000001 );
|
||||
|
||||
$this->assertNotNull( $dev );
|
||||
$this->assertEqualsWithDelta( 0.02, $dev['cost_per_image'], 0.000001 );
|
||||
}
|
||||
|
||||
/** Fallback models all have 'image_generation' capability. */
|
||||
public function test_fallback_models_have_capabilities(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
foreach ( $models as $model ) {
|
||||
$this->assertIsArray( $model['capabilities'] );
|
||||
$this->assertContains( 'image_generation', $model['capabilities'] );
|
||||
}
|
||||
}
|
||||
|
||||
/** Happy path: successful sync caches models and get_models returns them. */
|
||||
public function test_sync_success_caches_and_returns_models(): void {
|
||||
// The mocked API response body — models must have taskType=imageInference
|
||||
// so normalize_models() doesn't filter them out.
|
||||
$fake_body = json_encode(
|
||||
array(
|
||||
'data' => array(
|
||||
array(
|
||||
'id' => 'test-model-1',
|
||||
'name' => 'Test Model 1',
|
||||
'taskType' => 'imageInference',
|
||||
),
|
||||
array(
|
||||
'id' => 'test-model-2',
|
||||
'name' => 'Test Model 2',
|
||||
'taskType' => 'imageInference',
|
||||
),
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
$fake_response = array(
|
||||
'response' => array( 'code' => 200 ),
|
||||
'body' => $fake_body,
|
||||
);
|
||||
|
||||
Functions\when( 'wp_remote_post' )->justReturn( $fake_response );
|
||||
// Alias the WP response-parsing helpers so they work against our array.
|
||||
Functions\when( 'wp_remote_retrieve_response_code' )->alias(
|
||||
function ( $r ) { return (int) ( $r['response']['code'] ?? 0 ); }
|
||||
);
|
||||
Functions\when( 'wp_remote_retrieve_body' )->alias(
|
||||
function ( $r ) { return (string) ( $r['body'] ?? '' ); }
|
||||
);
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
|
||||
// Shared options store so get_option/update_option stay in sync
|
||||
// within this test. The API key must be non-empty for sync() to proceed.
|
||||
$store = array( 'prautoblogger_runware_api_key' => 'test-api-key-plain' );
|
||||
Functions\when( 'get_option' )->alias(
|
||||
function ( $key, $default = false ) use ( &$store ) {
|
||||
return $store[ $key ] ?? $default;
|
||||
}
|
||||
);
|
||||
Functions\when( 'update_option' )->alias(
|
||||
function ( $key, $value ) use ( &$store ) {
|
||||
$store[ $key ] = $value;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
// Sync should succeed: API key present, HTTP 200, 2 imageInference models.
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
$this->assertTrue( $result, 'Sync should return true on HTTP 200 with valid models' );
|
||||
|
||||
// get_models() should now return the synced list from cache.
|
||||
$models = $catalog->get_models();
|
||||
$this->assertIsArray( $models );
|
||||
$this->assertCount( 2, $models );
|
||||
$this->assertSame( 'test-model-1', $models[0]['id'] );
|
||||
$this->assertSame( 'test-model-2', $models[1]['id'] );
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,18 @@ use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class ImageModelRegistryTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* Stub WP cache functions so the catalog class falls back to the
|
||||
* hardcoded model list without hitting get_option or update_option.
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
// Catalog checks for cached data; return false → falls back to hardcoded list.
|
||||
\Brain\Monkey\Functions\when( 'get_option' )->justReturn( false );
|
||||
// Catalog writes cache on sync; stub so it doesn't throw in tests.
|
||||
\Brain\Monkey\Functions\when( 'update_option' )->justReturn( true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Every entry returned by get_models() must carry a non-empty id and
|
||||
* a provider of 'runware' or 'openrouter' (Cloudflare Workers AI was
|
||||
@@ -99,4 +111,56 @@ class ImageModelRegistryTest extends BaseTestCase {
|
||||
\PRAutoBlogger_Image_Model_Registry::provider_for( '' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that runware:400@4 resolves to runware provider.
|
||||
*/
|
||||
public function test_provider_for_runware_400_at_4(): void {
|
||||
$this->assertSame(
|
||||
'runware',
|
||||
\PRAutoBlogger_Image_Model_Registry::provider_for( 'runware:400@4' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that runware:glm-image@0 resolves to runware provider.
|
||||
*/
|
||||
public function test_provider_for_runware_glm_image(): void {
|
||||
$this->assertSame(
|
||||
'runware',
|
||||
\PRAutoBlogger_Image_Model_Registry::provider_for( 'runware:glm-image@0' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that openai/gpt-5.4-image-2 resolves to openrouter provider.
|
||||
*/
|
||||
public function test_provider_for_gpt_5_4_image_2(): void {
|
||||
$this->assertSame(
|
||||
'openrouter',
|
||||
\PRAutoBlogger_Image_Model_Registry::provider_for( 'openai/gpt-5.4-image-2' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that get_models() returns 21 models.
|
||||
*/
|
||||
public function test_get_models_returns_21_models(): void {
|
||||
$models = \PRAutoBlogger_Image_Model_Registry::get_models();
|
||||
$this->assertCount( 21, $models );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that every model has required non-empty fields.
|
||||
*/
|
||||
public function test_every_model_has_required_fields(): void {
|
||||
$models = \PRAutoBlogger_Image_Model_Registry::get_models();
|
||||
foreach ( $models as $model ) {
|
||||
$this->assertNotEmpty( $model['id'] ?? '', 'Model missing id' );
|
||||
$this->assertNotEmpty( $model['name'] ?? '', 'Model missing name' );
|
||||
$this->assertNotEmpty( $model['provider'] ?? '', 'Model missing provider' );
|
||||
$this->assertTrue( isset( $model['cost_per_image'] ), 'Model missing cost_per_image' );
|
||||
$this->assertIsNumeric( $model['cost_per_image'], 'cost_per_image is not numeric' );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user