dzen.nstarikov.ru/docs/superpowers/plans/2026-08-11-polza-image-generation.md
nstarikov f3a557cf17
Some checks failed
Deploy Dzen assistant / deploy (push) Failing after 22s
chore: make dzen assistant repository root
2026-08-15 14:21:59 +03:00

8.6 KiB
Raw Permalink Blame History

Polza Image Generation Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Let an authenticated editor configure Polza and generate, replace, or regenerate a cover plus two contextual illustrations without exposing the API token.

Architecture: Persist batches/jobs in SQLite, generate asynchronously through Celery and the Polza Media API, and permanently store verified provider results in local media storage. The React editor polls job state and applies each ready image to the current Editor.js document without auto-saving the article.

Tech Stack: FastAPI, SQLAlchemy/SQLite, Celery/Redis, httpx, Pillow, React, TypeScript, Editor.js, pytest, Vite.


Task 1: Add persistent generation state

Files:

  • Modify: dzen-assistant/app/models.py

  • Test: dzen-assistant/tests/test_image_generation_models.py

  • Step 1: Write the failing model test.

def test_image_generation_models_exist():
    from app.models import ArticleImageGenerationBatch, ArticleImageGenerationJob
    assert ArticleImageGenerationBatch.__tablename__ == "article_image_generation_batches"
    assert ArticleImageGenerationJob.__tablename__ == "article_image_generation_jobs"
  • Step 2: Run cd dzen-assistant && pytest tests/test_image_generation_models.py -q; expect failure because the models are absent.

  • Step 3: Implement ArticleImageGenerationBatch and ArticleImageGenerationJob. Batch fields: UUID id, article FK, status, snapshot id, timestamps. Job fields: UUID id, batch/article FK, target (cover|middle|final), nullable target locator, snapshot JSON, API URL/model/prompt snapshot, Celery ID, status, progress, stage, local URL, safe error code/message, timestamps. Add (batch_id, target) uniqueness. Do not store a token in either model.

  • Step 4: Run the model test; expect pass.

  • Step 5: Commit the model/test changes with feat: persist image generation jobs.

Task 2: Implement prompt, Polza, and download service

Files:

  • Create: dzen-assistant/app/image_generation.py

  • Test: dzen-assistant/tests/test_image_generation.py

  • Step 1: Write failing tests for URL validation, three prompt roles, provider fallback, and local image validation.

def test_cover_prompt_keeps_exact_title():
    assert "КТО НАВЁЛ УДАР" in build_cover_prompt("КТО НАВЁЛ УДАР", "контекст")

def test_body_prompts_are_distinct_and_text_free():
    assert build_body_prompt("middle", "a") != build_body_prompt("final", "b")
    assert "без текста" in build_body_prompt("middle", "a").lower()
  • Step 2: Run cd dzen-assistant && pytest tests/test_image_generation.py -q; expect import failure.

  • Step 3: Implement validate_image_api_url, snapshot/section extraction, cover/body prompt builders, PolzaMediaClient, error mapper, and verified local downloader. Use POST {base}/v1/media then GET {base}/v1/media/{id}; request one image per role. First payload requests 16:9, 4K, and PNG. Retry once with 1792x1024 only for an explicit unsupported size/quality error. Never retry auth, balance, moderation, model, or timeout errors. Require remote HTTPS, block private/reserved hosts, apply byte/time limits, Pillow-decode the file, write a temp file and atomically rename under media/generated/YYYYMMDD/{article_id}.

  • Step 4: Run service tests; expect pass.

  • Step 5: Commit with feat: add Polza media generation client.

Task 3: Add safe settings and image-generation API

Files:

  • Modify: dzen-assistant/app/routes.py

  • Modify: dzen-assistant/app/worker.py

  • Test: dzen-assistant/tests/test_image_generation_routes.py

  • Step 1: Write failing tests for token masking, retain/replace/delete semantics, three-job creation, active-batch reuse, and status responses.

def test_settings_never_returns_token(client):
    client.put("/api/settings", json={"imageApiToken": "secret"})
    payload = client.get("/api/settings").json()
    assert payload["imageApiTokenConfigured"] is True
    assert "secret" not in str(payload)
  • Step 2: Run cd dzen-assistant && pytest tests/test_image_generation_routes.py -q; expect failure.

  • Step 3: Extend Settings API. Persist API URL default https://polza.ai/api, model default google/gemini-3.1-flash-image, and write-only token in AppSetting. Return only URL, model, and imageApiTokenConfigured; blank/absent token retains, nonblank replaces, and explicit delete removes it. Reject replacement plus deletion together.

  • Step 4: Implement generation APIs and Celery worker. Add protected routes POST /api/articles/{id}/image-generations, GET /api/articles/{id}/image-generations/active, and GET /api/articles/{id}/image-generations/{batch_id}. Validate current title and Editor.js snapshot. all creates cover/middle/final jobs; an individual target creates one. Reuse active work per requested target. Queue generate_article_image(job_id) after commit. The worker transitions queued → requesting → generating → downloading → ready/failed, obtains the token only server-side, writes only local URLs, maps errors to safe codes, and recomputes batch status.

  • Step 5: Run route and service tests; expect pass.

  • Step 6: Commit with feat: queue article image generations.

Task 4: Add settings UI

Files:

  • Modify: dzen-assistant/admin/src/App.tsx

  • Step 1: Extend the public AppSettings type with URL/model/configured fields, retaining the token only as a local password-input state.

  • Step 2: Add a «Генерация изображений» card. Include API URL, model, masked token state, a password input used only on save, and a separate confirmable delete action. A blank token input must omit the token property, and every successful save must clear it.

  • Step 3: Run cd dzen-assistant/admin && npm run build; expect a successful TypeScript/Vite build.

  • Step 4: Commit with feat: configure image provider in admin.

Task 5: Add editor actions, polling, and placement

Files:

  • Modify: dzen-assistant/admin/src/App.tsx

  • Modify: dzen-assistant/admin/src/index.css

  • Step 1: Add pure Editor.js helpers. They must select first/last existing image blocks for all-generation, insert before headings nearest the second/final third when missing, preserve the signature as last block, and replace image URL/caption without removing the old image until the replacement job is ready.

  • Step 2: Add controls. Put «Сгенерировать изображения» with editor save actions, «Перегенерировать обложку» at the feature-image control, and a second ImageTool tune «Перегенерировать по тексту» on each inline image. Individual actions use surrounding text context and change only their selected block.

  • Step 3: Add batch state and polling. Serialize await editor.save() plus current title before POST; show named cover/middle/final status rows; recover active work when opening the article; clear polling on modal close. Use a durable locator (image URL/HTML position) rather than raw Editor.js block IDs after a saved/reopened document. Apply each ready local URL once, set editorDirty, and never PATCH automatically. If a changed document makes a target ambiguous, retain the result and expose «Применить».

  • Step 4: Add loading styles and build the admin. Run cd dzen-assistant/admin && npm run build; expect exit 0.

  • Step 5: Commit with feat: generate and regenerate article images.

Task 6: Run proportional verification

Files:

  • Modify: dzen-assistant/.env.example

  • Step 1: Document empty optional fallback variables only; the admin UI remains the token source and no key is committed.

  • Step 2: Run backend verification. Run cd dzen-assistant && pytest -q && python -m compileall app; expect all tests and compilation to pass.

  • Step 3: Run frontend verification. Run cd dzen-assistant/admin && npm run build; expect exit 0.

  • Step 4: With a non-production token configured in Settings, manually verify a non-published draft: generate three images, confirm three local /media/generated/... URLs, regenerate cover and one inline image, save, reopen, and confirm the URLs persist.

  • Step 5: Commit any final documentation/test adjustment with test: verify generated article image flow.