odforge 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. odforge/__init__.py +1 -0
  2. odforge/benchmark.py +287 -0
  3. odforge/check.py +416 -0
  4. odforge/cli.py +1027 -0
  5. odforge/components.py +270 -0
  6. odforge/critic.py +1260 -0
  7. odforge/docfonts.py +104 -0
  8. odforge/editor_api.py +33 -0
  9. odforge/editor_launch.py +134 -0
  10. odforge/editor_routes.py +131 -0
  11. odforge/extract.py +478 -0
  12. odforge/feedback.py +86 -0
  13. odforge/fontembed.py +166 -0
  14. odforge/ir.py +1181 -0
  15. odforge/layoutcheck.py +602 -0
  16. odforge/llm.py +1865 -0
  17. odforge/localguard.py +42 -0
  18. odforge/mcp_server.py +552 -0
  19. odforge/media.py +352 -0
  20. odforge/odpedit.py +1219 -0
  21. odforge/package.py +114 -0
  22. odforge/pagefacts.py +388 -0
  23. odforge/preview.py +104 -0
  24. odforge/references.py +153 -0
  25. odforge/render/__init__.py +40 -0
  26. odforge/render/odp.py +5687 -0
  27. odforge/render/ods.py +155 -0
  28. odforge/render/odt.py +223 -0
  29. odforge/scene.py +657 -0
  30. odforge/setup_agents.py +274 -0
  31. odforge/skills/odforge-design/SKILL.md +298 -0
  32. odforge/skills/odforge-design/themes/academic.md +52 -0
  33. odforge/skills/odforge-design/themes/clay.md +53 -0
  34. odforge/skills/odforge-design/themes/color-system.md +59 -0
  35. odforge/skills/odforge-design/themes/crimson.md +53 -0
  36. odforge/skills/odforge-design/themes/dark.md +53 -0
  37. odforge/skills/odforge-design/themes/forest.md +54 -0
  38. odforge/skills/odforge-design/themes/gold.md +53 -0
  39. odforge/skills/odforge-design/themes/minimal.md +53 -0
  40. odforge/skills/odforge-design/themes/navy.md +56 -0
  41. odforge/skills/odforge-design/themes/plum.md +53 -0
  42. odforge/skills/odforge-design/themes/sky.md +53 -0
  43. odforge/skills/odforge-design/themes/slate.md +53 -0
  44. odforge/skills/odforge-design/themes/teal.md +53 -0
  45. odforge/skills/odforge-design/themes/violet.md +56 -0
  46. odforge/templates.py +250 -0
  47. odforge/textmetrics.py +616 -0
  48. odforge/textutil.py +24 -0
  49. odforge/themes.py +886 -0
  50. odforge/validate.py +403 -0
  51. odforge/watch.py +266 -0
  52. odforge/webapi.py +2617 -0
  53. odforge/webui/assets/editor-CjpYXM1a.css +1 -0
  54. odforge/webui/assets/editor-DPToJGio.js +3 -0
  55. odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
  56. odforge/webui/assets/main-BLOs7Hnk.js +7 -0
  57. odforge/webui/assets/main-D21yFVE6.css +1 -0
  58. odforge/webui/editor.html +14 -0
  59. odforge/webui/index.html +25 -0
  60. odforge/xmlsafe.py +46 -0
  61. odforge/zipguard.py +91 -0
  62. odforge-0.3.0.dist-info/METADATA +95 -0
  63. odforge-0.3.0.dist-info/RECORD +66 -0
  64. odforge-0.3.0.dist-info/WHEEL +4 -0
  65. odforge-0.3.0.dist-info/entry_points.txt +3 -0
  66. odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/webapi.py ADDED
@@ -0,0 +1,2617 @@
1
+ """ODForge Web API — FastAPI + SSE over the two-stage generation pipeline.
2
+
3
+ This module wraps the *same* machinery the CLI uses (``generate_outline`` →
4
+ ``generate_slides`` → ``render`` → ``render_pages`` → optional ``run_qa_loop``)
5
+ behind an HTTP + Server-Sent-Events surface a browser front-end drives. It is an
6
+ **optional extra**: nothing in ``odforge``'s core import path imports this module,
7
+ and FastAPI / sse-starlette are only required when serving or testing the web
8
+ layer (``pip install "odforge[web]"``). Construct the app via :func:`create_app`.
9
+
10
+ Security model (path whitelist)
11
+ -------------------------------
12
+ No caller-supplied filesystem path is ever opened. A job id is a server-minted
13
+ ``uuid4().hex`` (never echoed caller input) that maps — only as a dict key — to a
14
+ per-job directory the server created under ``%TEMP%/odforge-jobs/{id}/``. Page
15
+ indices arrive as validated integers and are formatted into a fixed server-owned
16
+ name (``page-NN.png``); an out-of-range page is a 404, never a path lookup. There
17
+ is therefore no way for a request to name a path outside its own job directory.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import base64
24
+ import binascii
25
+ import json
26
+ import logging
27
+ import os
28
+ import re
29
+ import shutil
30
+ import tempfile
31
+ import threading
32
+ import time
33
+ import uuid
34
+ from collections.abc import AsyncIterator
35
+ from contextlib import asynccontextmanager, suppress
36
+ from dataclasses import dataclass, field
37
+ from importlib import resources
38
+ from pathlib import Path
39
+ from typing import Any, Dict, List, Literal, Optional
40
+ from urllib.parse import urlsplit
41
+
42
+ from fastapi import FastAPI, HTTPException, Request
43
+ from fastapi.middleware.cors import CORSMiddleware
44
+ from fastapi.responses import FileResponse, StreamingResponse
45
+ from fastapi.staticfiles import StaticFiles
46
+ from pydantic import (
47
+ BaseModel,
48
+ ConfigDict,
49
+ Field,
50
+ ValidationError,
51
+ field_validator,
52
+ model_validator,
53
+ )
54
+ from sse_starlette import EventSourceResponse
55
+
56
+ from odforge import __version__, critic, llm
57
+ from odforge.critic import QAReport, run_qa_loop
58
+ from odforge.extract import TemplateExtractionError, extract_design
59
+ from odforge.ir import (
60
+ LANGUAGES,
61
+ MAX_OUTLINE_PAGES,
62
+ Branding,
63
+ DesignSpec,
64
+ MediaAssetRef,
65
+ Outline,
66
+ PageRole,
67
+ Presentation,
68
+ )
69
+ from odforge.llm import (
70
+ DiscoveryPlan,
71
+ DroppedContent,
72
+ generate_discovery_questions,
73
+ generate_outline,
74
+ generate_slides,
75
+ )
76
+ from odforge.media import AssetBlob, AssetInput, MediaError, decode_data_uri
77
+ from odforge.preview import PreviewUnavailable, render_pages
78
+ from odforge.references import (
79
+ ReferenceDocument,
80
+ ReferenceError,
81
+ decode_pdf_data_uri,
82
+ format_reference_context,
83
+ is_pdf_data_uri,
84
+ )
85
+ from odforge.render import render
86
+ from odforge.templates import (
87
+ MAX_NAME_CHARS,
88
+ all_templates,
89
+ delete_template,
90
+ save_template,
91
+ templates_path,
92
+ )
93
+ from odforge.themes import STYLES, THEMES
94
+ from odforge.validate import validate_odf
95
+
96
+ # The odp mimetype, verbatim per the project's ODF mimetype constants.
97
+ ODP_MIME = "application/vnd.oasis.opendocument.presentation"
98
+
99
+ # 頁數下限只在 API 這一層有意義(產品不接受 1–2 頁的請求);上限直接沿用 IR 的
100
+ # MAX_OUTLINE_PAGES,前後端與 Outline schema 因此共用同一個數字。
101
+ MIN_REQUESTED_PAGES = 3
102
+
103
+ # CORS: an explicit localhost dev allowlist (never wildcard-with-credentials).
104
+ # This API has no auth and spends the user's real LLM key, so a permissive
105
+ # ``*`` + credentials origin would let ANY site the user visits drive it from
106
+ # their browser. Override with ``ODFORGE_CORS_ORIGINS`` (comma-separated).
107
+ _DEFAULT_CORS_ORIGINS = [
108
+ "http://localhost:5173",
109
+ "http://127.0.0.1:5173",
110
+ "http://localhost:3000",
111
+ "http://127.0.0.1:3000",
112
+ ]
113
+
114
+
115
+ def _cors_origins() -> List[str]:
116
+ """Resolve the CORS allowlist from ``ODFORGE_CORS_ORIGINS`` or the default."""
117
+ raw = os.environ.get("ODFORGE_CORS_ORIGINS")
118
+ if raw:
119
+ origins = [o.strip() for o in raw.split(",") if o.strip()]
120
+ if origins:
121
+ for origin in origins:
122
+ if not _is_explicit_http_origin(origin):
123
+ raise ValueError(
124
+ "ODFORGE_CORS_ORIGINS must contain explicit http(s) origins; "
125
+ f"unsafe value: {origin!r}"
126
+ )
127
+ return origins
128
+ return list(_DEFAULT_CORS_ORIGINS)
129
+
130
+
131
+ def _is_explicit_http_origin(origin: str) -> bool:
132
+ parsed = urlsplit(origin)
133
+ return (
134
+ origin.lower() not in {"*", "null"}
135
+ and parsed.scheme in {"http", "https"}
136
+ and bool(parsed.netloc)
137
+ and not parsed.path
138
+ and not parsed.query
139
+ and not parsed.fragment
140
+ )
141
+
142
+ # How long an idle SSE subscriber sleeps between liveness checks. Small enough
143
+ # that a newly-emitted event is delivered promptly; a fallback only — emits also
144
+ # fire ``job.updated`` to wake the subscriber immediately.
145
+ _SSE_POLL_SECONDS = 0.4
146
+ _MAX_ACTIVE_JOBS = 4
147
+ _MAX_ACTIVE_REGENERATIONS = 2
148
+ _MAX_RETAINED_JOBS = 100
149
+ _JOB_RETENTION_SECONDS = 90 * 24 * 60 * 60
150
+ _APPROVAL_TIMEOUT_SECONDS = 30 * 60
151
+ _TERMINAL_JOB_STATUSES = {"complete", "error", "cancelled"}
152
+ _SESSION_FILENAME = "session.json"
153
+ _DISCOVERY_HEARTBEAT_SECONDS = 3.0
154
+ _DISCOVERY_STAGE_MESSAGES = {
155
+ "accepted": "已收到需求",
156
+ "preparing": "正在整理設定與參考文件",
157
+ "requesting": "正在產生關鍵問題",
158
+ "retrying": "格式不符,正在重試",
159
+ "validating": "正在檢查問題",
160
+ "complete": "問題準備完成",
161
+ "waiting": "模型仍在處理",
162
+ }
163
+
164
+ # Reuse uvicorn's configured error logger so lifecycle timings are visible in
165
+ # the same console (and any redirected server log) without requiring callers
166
+ # to install a separate logging configuration.
167
+ logger = logging.getLogger("uvicorn.error")
168
+
169
+
170
+ # ---------------------------------------------------------------------------
171
+ # Job model + in-memory store
172
+ # ---------------------------------------------------------------------------
173
+
174
+
175
+ @dataclass
176
+ class Job:
177
+ """One generation request and everything the API needs to serve it.
178
+
179
+ Lives only in memory (``app.state.jobs``); its artifacts live under the
180
+ server-owned :attr:`dir`. ``events`` is an append-only log of every SSE
181
+ event emitted, so a late/reconnecting subscriber can be replayed the whole
182
+ history and the snapshot endpoint can reconstruct state.
183
+ """
184
+
185
+ id: str
186
+ dir: Path
187
+ prompt: str
188
+ mode: Optional[str] = None
189
+ theme: Optional[str] = None
190
+ interactive: bool = False
191
+ qa: bool = False
192
+ backend: Optional[str] = None
193
+ # Per-job vision source; ``None`` falls back to ODFORGE_VISION_BACKEND.
194
+ vision_backend: Optional[str] = None
195
+ pages: Optional[int] = None
196
+ # Output language of the deck (ir.LANGUAGES); stamped onto the outline after
197
+ # stage 1 so stage 2 and any later single-page regeneration inherit it.
198
+ language: str = "zh-TW"
199
+ # A user template's design tokens. Beats both the model's own DesignSpec and
200
+ # ``theme``: the user picked this look explicitly.
201
+ design: Optional[DesignSpec] = None
202
+ # 版式 (layout personality). None = the palette's paired default.
203
+ style: Optional[str] = None
204
+ # Cover byline + logo. ``branding.logo`` points at ``assets["logo"]``.
205
+ branding: Optional[Branding] = None
206
+ assets: Dict[str, AssetInput] = field(default_factory=dict)
207
+ asset_refs: List[MediaAssetRef] = field(default_factory=list)
208
+ reference_documents: List[ReferenceDocument] = field(default_factory=list)
209
+ created_at: float = field(default_factory=time.time)
210
+ finished_at: Optional[float] = None
211
+
212
+ status: str = "pending"
213
+ outline: Optional[Outline] = None
214
+ ir: Optional[Presentation] = None
215
+ slides_done: int = 0
216
+ # 每次「重算圖後再發佈預覽」遞增。URL 帶上 ?v={n} 讓字串不同,否則瀏覽器/
217
+ # React 對同字串 URL 不會重抓,修補後的頁面永遠顯示舊圖(F5)。同時也是預覽
218
+ # 目錄名(preview/v{n}):換版本 = 換目錄,舊頁數的殘骸不可能混進新的一輪。
219
+ # ``-1`` = 還沒發佈過任何一批;第一批發佈為 v0(URL 不帶 ?v=,與舊行為一致)。
220
+ preview_version: int = -1
221
+ # ---- artifact lifecycle -------------------------------------------------
222
+ # ``artifact_version`` 每成功發佈一次 deck.odp 就 +1;``validated_version``
223
+ # 記錄「通過必要閘門的是哪一版」。下載端點比對兩者:相等才交付。檔案存在
224
+ # 不等於檔案可信 —— 生成中、驗證失敗、重生失敗的中途檔都存在於磁碟上。
225
+ artifact_version: int = 0
226
+ validated_version: int = -1
227
+ # 最近一次的四道閘結果,重生後要能整批重算(不得沿用上一版的綠燈)。
228
+ gates: Dict[str, str] = field(default_factory=dict)
229
+ qa_report: Optional[QAReport] = None
230
+ # 版面預算被迫刪掉的內容。使用者要求過這些字,消失了就必須說出來。
231
+ dropped_content: List[DroppedContent] = field(default_factory=list)
232
+ # Why the design gate could not run (missing key, exhausted quota, 4xx from
233
+ # the vision provider…). QA never fails the run, but the reason must reach the
234
+ # user: "未啟用" with no cause is indistinguishable from a silent bug.
235
+ qa_error: Optional[str] = None
236
+ error: Optional[Dict[str, str]] = None
237
+ # Strong ref to the background runner so the loop doesn't GC a "fire and
238
+ # forget" task before it finishes.
239
+ task: Optional[asyncio.Task] = None
240
+ # How many worker threads this job still has running. Incremented when work
241
+ # is handed to the executor, decremented *by the thread itself* when it
242
+ # returns — so a cancelled ``await`` cannot make it look idle while a
243
+ # provider call is still burning quota. Touched from two threads: guarded.
244
+ active_workers: int = 0
245
+ worker_lock: threading.Lock = field(default_factory=threading.Lock)
246
+
247
+ events: List[Dict[str, Any]] = field(default_factory=list)
248
+ # Live-preview jobs (``odforge preview``) re-render whenever their source file
249
+ # changes. Their event log is replaced wholesale on each reload — bumping
250
+ # ``event_epoch`` tells every open stream to start over from the new log — and
251
+ # their stream never ends, because "complete" only means "this version is done".
252
+ watching: bool = False
253
+ event_epoch: int = 0
254
+ # Set on approve (interactive gate) and on every emit (wakes SSE subscribers).
255
+ approval: asyncio.Event = field(default_factory=asyncio.Event)
256
+ updated: asyncio.Event = field(default_factory=asyncio.Event)
257
+ mutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
258
+ # When session.json was last rewritten — the debounce clock for high-
259
+ # frequency events (see ``_emit``). Not persisted.
260
+ last_persist: float = 0.0
261
+
262
+ @property
263
+ def odp_path(self) -> Path:
264
+ return self.dir / "deck.odp"
265
+
266
+ @property
267
+ def previews_root(self) -> Path:
268
+ return self.dir / "preview"
269
+
270
+ @property
271
+ def preview_dir(self) -> Path:
272
+ """The *published* preview directory for the current version.
273
+
274
+ Each publish writes a fresh ``preview/v{n}`` and then moves the pointer
275
+ (``preview_version``) — so a 5-page deck re-generated down to 3 pages
276
+ cannot leave ``page-04.png``/``page-05.png`` behind to be served as if
277
+ they were still part of the deck. Version 0 (nothing published yet) is a
278
+ directory that never exists, which is exactly the right answer.
279
+ """
280
+ return self.previews_root / f"v{self.preview_version}"
281
+
282
+ def preview_dir_for(self, version: int) -> Path:
283
+ return self.previews_root / f"v{version}"
284
+
285
+ @property
286
+ def downloadable(self) -> bool:
287
+ """Whether the artifact on disk is the one the gates actually approved.
288
+
289
+ Three things must line up: the job finished, the file exists, and the
290
+ version that passed validation is the version sitting on disk. A job that
291
+ is still generating, is mid-regeneration, failed validation, errored or
292
+ was cancelled fails at least one of them — even though ``deck.odp`` may
293
+ well exist, because a partial or rolled-back render leaves a file behind.
294
+ """
295
+ return (
296
+ self.status == "complete"
297
+ and self.artifact_version > 0
298
+ and self.validated_version == self.artifact_version
299
+ and self.odp_path.is_file()
300
+ )
301
+
302
+
303
+ def _occupies_a_slot(job: Job) -> bool:
304
+ """Whether this job still ties up one of the concurrent-work slots.
305
+
306
+ Two independent facts, deliberately kept apart:
307
+
308
+ * ``job.status`` is what the **UI** shows. Cancel sets it to ``cancelled``
309
+ instantly, because a user who pressed cancel should see it stop.
310
+ * ``job.task`` is what is **actually running**. ``Task.cancel()`` only
311
+ requests cancellation, and a thread already inside ``requests.post`` to a
312
+ provider cannot be interrupted at all — it runs to completion, spending
313
+ the user's quota, long after the UI said "cancelled".
314
+
315
+ The limit has to be enforced on the second one. Otherwise start/cancel in a
316
+ loop is a way to launch unlimited simultaneous provider calls while the
317
+ console shows an idle machine.
318
+
319
+ And ``job.task`` alone is still not the second one. Cancelling a task that
320
+ is parked on ``asyncio.to_thread`` marks the *task* done the moment
321
+ ``CancelledError`` propagates — while the thread it handed the work to keeps
322
+ running inside ``requests.post`` with no idea any of this happened. Between
323
+ those two moments the slot was already free. ``active_workers`` is
324
+ decremented by that thread, when it actually finishes, which is the only
325
+ event that means the provider call is over.
326
+ """
327
+ if job.status not in _TERMINAL_JOB_STATUSES:
328
+ return True
329
+ if job.task is not None and not job.task.done():
330
+ return True
331
+ with job.worker_lock:
332
+ return job.active_workers > 0
333
+
334
+
335
+ async def _offload(job: Job, fn, /, *args, **kwargs):
336
+ """Run ``fn`` in a worker thread, counted against the job for its real life.
337
+
338
+ ``asyncio.to_thread`` with bookkeeping: the count goes up before the work is
339
+ handed over and comes down inside the thread, so cancelling the awaiting
340
+ coroutine cannot release the slot early. Every provider call, render and
341
+ validation in the pipeline goes through here.
342
+ """
343
+ with job.worker_lock:
344
+ job.active_workers += 1
345
+
346
+ def _tracked():
347
+ try:
348
+ return fn(*args, **kwargs)
349
+ finally:
350
+ with job.worker_lock:
351
+ job.active_workers -= 1
352
+
353
+ return await asyncio.to_thread(_tracked)
354
+
355
+
356
+ def _job_metadata(job: Job) -> Dict[str, Any]:
357
+ assets: dict[str, str] = {}
358
+ for asset_id, value in job.assets.items():
359
+ if not isinstance(value, (str, Path)):
360
+ continue
361
+ path = Path(value)
362
+ try:
363
+ assets[asset_id] = path.relative_to(job.dir).as_posix()
364
+ except ValueError:
365
+ continue
366
+ return {
367
+ "schema_version": 1,
368
+ "id": job.id,
369
+ "prompt": job.prompt,
370
+ "mode": job.mode,
371
+ "theme": job.theme,
372
+ "interactive": job.interactive,
373
+ "qa": job.qa,
374
+ "vision_backend": job.vision_backend,
375
+ "backend": job.backend,
376
+ "pages": job.pages,
377
+ "language": job.language,
378
+ "style": job.style,
379
+ "design": (
380
+ job.design.model_dump(mode="json") if job.design is not None else None
381
+ ),
382
+ "branding": (
383
+ job.branding.model_dump(mode="json")
384
+ if job.branding is not None
385
+ else None
386
+ ),
387
+ "assets": assets,
388
+ "asset_refs": [ref.model_dump(mode="json") for ref in job.asset_refs],
389
+ "created_at": job.created_at,
390
+ "finished_at": job.finished_at,
391
+ "status": job.status,
392
+ "preview_version": job.preview_version,
393
+ "artifact_version": job.artifact_version,
394
+ "validated_version": job.validated_version,
395
+ "gates": dict(job.gates),
396
+ "outline": (
397
+ job.outline.model_dump(mode="json") if job.outline is not None else None
398
+ ),
399
+ "ir": job.ir.model_dump(mode="json") if job.ir is not None else None,
400
+ "slides_done": job.slides_done,
401
+ "qa_report": (
402
+ job.qa_report.model_dump(mode="json")
403
+ if job.qa_report is not None
404
+ else None
405
+ ),
406
+ "error": job.error,
407
+ "events": job.events,
408
+ }
409
+
410
+
411
+ def _persist_job(job: Job) -> None:
412
+ """Atomically persist resumable session state without uploaded document bytes."""
413
+
414
+ job.last_persist = time.time()
415
+ target = job.dir / _SESSION_FILENAME
416
+ temporary = job.dir / f"{_SESSION_FILENAME}.tmp"
417
+ try:
418
+ temporary.write_text(
419
+ json.dumps(
420
+ _job_metadata(job),
421
+ ensure_ascii=False,
422
+ separators=(",", ":"),
423
+ ),
424
+ encoding="utf-8",
425
+ )
426
+ temporary.replace(target)
427
+ except (OSError, TypeError, ValueError) as exc:
428
+ logger.warning("session_persist_failed job_id=%s error=%s", job.id, exc)
429
+ with suppress(OSError):
430
+ temporary.unlink()
431
+
432
+
433
+ def _safe_restored_asset(job_dir: Path, relative: str) -> Optional[Path]:
434
+ candidate = (job_dir / relative).resolve()
435
+ try:
436
+ candidate.relative_to(job_dir.resolve())
437
+ except ValueError:
438
+ return None
439
+ return candidate if candidate.is_file() else None
440
+
441
+
442
+ def _load_persisted_job(job_dir: Path) -> Optional[Job]:
443
+ metadata_path = job_dir / _SESSION_FILENAME
444
+ if not metadata_path.is_file() or not re.fullmatch(r"[0-9a-f]{32}", job_dir.name):
445
+ return None
446
+ try:
447
+ data = json.loads(metadata_path.read_text(encoding="utf-8"))
448
+ if data.get("id") != job_dir.name:
449
+ return None
450
+ job = Job(
451
+ id=job_dir.name,
452
+ dir=job_dir,
453
+ prompt=str(data.get("prompt", "")),
454
+ mode=data.get("mode"),
455
+ theme=data.get("theme"),
456
+ interactive=bool(data.get("interactive", False)),
457
+ qa=bool(data.get("qa", False)),
458
+ vision_backend=data.get("vision_backend"),
459
+ backend=data.get("backend"),
460
+ pages=data.get("pages"),
461
+ # Jobs persisted before these fields existed restore as the
462
+ # defaults, which is exactly what they ran as.
463
+ language=str(data.get("language") or "zh-TW"),
464
+ style=data.get("style"),
465
+ design=(
466
+ DesignSpec.model_validate(data["design"])
467
+ if data.get("design") is not None
468
+ else None
469
+ ),
470
+ branding=(
471
+ Branding.model_validate(data["branding"])
472
+ if data.get("branding") is not None
473
+ else None
474
+ ),
475
+ created_at=float(data.get("created_at", time.time())),
476
+ finished_at=(
477
+ float(data["finished_at"])
478
+ if data.get("finished_at") is not None
479
+ else None
480
+ ),
481
+ status=str(data.get("status", "error")),
482
+ outline=(
483
+ Outline.model_validate(data["outline"])
484
+ if data.get("outline") is not None
485
+ else None
486
+ ),
487
+ ir=(
488
+ Presentation.model_validate(data["ir"])
489
+ if data.get("ir") is not None
490
+ else None
491
+ ),
492
+ slides_done=int(data.get("slides_done", 0)),
493
+ preview_version=int(data.get("preview_version", -1)),
494
+ artifact_version=int(data.get("artifact_version", 0)),
495
+ validated_version=int(data.get("validated_version", -1)),
496
+ gates={
497
+ str(k): str(v)
498
+ for k, v in (data.get("gates") or {}).items()
499
+ if isinstance(k, str) and isinstance(v, str)
500
+ },
501
+ qa_report=(
502
+ QAReport.model_validate(data["qa_report"])
503
+ if data.get("qa_report") is not None
504
+ else None
505
+ ),
506
+ error=data.get("error"),
507
+ events=[
508
+ event
509
+ for event in data.get("events", [])
510
+ if isinstance(event, dict)
511
+ and isinstance(event.get("event"), str)
512
+ and "data" in event
513
+ ],
514
+ asset_refs=[
515
+ MediaAssetRef.model_validate(item)
516
+ for item in data.get("asset_refs", [])
517
+ ],
518
+ )
519
+ # Sessions written before artifact versioning existed carry neither
520
+ # field. They reached ``complete`` under the old rule (completion implied
521
+ # the gates had passed), so honour that rather than retroactively making
522
+ # every archived deck undownloadable.
523
+ if job.artifact_version == 0 and job.status == "complete":
524
+ job.artifact_version = 1
525
+ job.validated_version = 1
526
+ for asset_id, relative in data.get("assets", {}).items():
527
+ if not isinstance(asset_id, str) or not isinstance(relative, str):
528
+ continue
529
+ restored = _safe_restored_asset(job_dir, relative)
530
+ if restored is not None:
531
+ job.assets[asset_id] = restored
532
+ if job.status not in _TERMINAL_JOB_STATUSES:
533
+ job.status = "error"
534
+ job.finished_at = time.time()
535
+ job.error = {
536
+ "message": "服務重啟,此工作未完成",
537
+ "stage": "restore",
538
+ }
539
+ job.events.append({"event": "error", "data": job.error})
540
+ _persist_job(job)
541
+ return job
542
+ except (OSError, ValueError, TypeError, ValidationError, json.JSONDecodeError) as exc:
543
+ logger.warning(
544
+ "session_restore_skipped path=%s error=%s",
545
+ metadata_path,
546
+ exc,
547
+ )
548
+ return None
549
+
550
+
551
+ def _load_persisted_jobs(base: Path) -> Dict[str, Job]:
552
+ jobs: dict[str, Job] = {}
553
+ for job_dir in base.iterdir():
554
+ if not job_dir.is_dir():
555
+ continue
556
+ job = _load_persisted_job(job_dir)
557
+ if job is not None:
558
+ jobs[job.id] = job
559
+ return jobs
560
+
561
+
562
+ def create_job(
563
+ app: FastAPI,
564
+ *,
565
+ prompt: str,
566
+ mode: Optional[str] = None,
567
+ theme: Optional[str] = None,
568
+ interactive: bool = False,
569
+ qa: bool = False,
570
+ vision_backend: Optional[str] = None,
571
+ backend: Optional[str] = None,
572
+ pages: Optional[int] = None,
573
+ uploads: Optional[List[AssetUpload]] = None,
574
+ language: str = "zh-TW",
575
+ design: Optional[DesignSpec] = None,
576
+ style: Optional[str] = None,
577
+ byline: str = "",
578
+ logo: Optional[AssetUpload] = None,
579
+ logo_placement: str = "cover-closing",
580
+ ) -> Job:
581
+ """Register a new job with a server-minted id and its own artifact dir.
582
+
583
+ The cover logo is decoded and stored like any other image asset, under the
584
+ reserved id ``logo`` — it is deliberately NOT added to ``asset_refs``, which
585
+ is the list the model may draw from: a school crest is furniture, and a
586
+ model offered it as page media would eventually put it on a slide.
587
+ """
588
+ decoded_images = []
589
+ reference_documents: list[ReferenceDocument] = []
590
+ for upload in uploads or []:
591
+ if is_pdf_data_uri(upload.data_url):
592
+ reference_documents.append(
593
+ decode_pdf_data_uri(
594
+ upload.data_url,
595
+ description=upload.description,
596
+ credit=upload.credit,
597
+ )
598
+ )
599
+ continue
600
+ blob = decode_data_uri(upload.data_url)
601
+ asset_id = f"asset-{len(decoded_images) + 1:02d}"
602
+ decoded_images.append((asset_id, upload, blob))
603
+
604
+ # Decoded before the job dir exists so a bad logo fails the request (422)
605
+ # rather than leaving a half-built job behind.
606
+ logo_blob = decode_data_uri(logo.data_url) if logo is not None else None
607
+ branding = None
608
+ if byline.strip() or logo_blob is not None:
609
+ branding = Branding(
610
+ byline=byline.strip(),
611
+ logo="asset://logo" if logo_blob is not None else "",
612
+ placement=logo_placement,
613
+ )
614
+
615
+ job_id = uuid.uuid4().hex
616
+ job_dir = Path(app.state.jobs_dir) / job_id
617
+ job_dir.mkdir(parents=True, exist_ok=True)
618
+ job = Job(
619
+ id=job_id,
620
+ dir=job_dir,
621
+ prompt=prompt,
622
+ mode=mode,
623
+ theme=theme,
624
+ interactive=interactive,
625
+ qa=qa,
626
+ vision_backend=vision_backend,
627
+ backend=backend,
628
+ pages=pages,
629
+ language=language,
630
+ design=design,
631
+ style=style,
632
+ branding=branding,
633
+ reference_documents=reference_documents,
634
+ )
635
+ assets_dir = job_dir / "assets"
636
+ if logo_blob is not None:
637
+ assets_dir.mkdir(parents=True, exist_ok=True)
638
+ logo_path = assets_dir / f"logo{logo_blob.extension}"
639
+ logo_path.write_bytes(logo_blob.data)
640
+ job.assets["logo"] = logo_path
641
+ for asset_id, upload, blob in decoded_images:
642
+ assets_dir.mkdir(parents=True, exist_ok=True)
643
+ path = assets_dir / f"{asset_id}{blob.extension}"
644
+ path.write_bytes(blob.data)
645
+ job.assets[asset_id] = path
646
+ job.asset_refs.append(
647
+ MediaAssetRef(
648
+ id=asset_id,
649
+ description=upload.description,
650
+ credit=upload.credit,
651
+ )
652
+ )
653
+ app.state.jobs[job_id] = job
654
+ _persist_job(job)
655
+ return job
656
+
657
+
658
+ def _prune_jobs(app: FastAPI, *, now: Optional[float] = None) -> None:
659
+ """Remove expired/overflow terminal jobs and their server-owned artifacts."""
660
+ current = time.time() if now is None else now
661
+ jobs: dict[str, Job] = app.state.jobs
662
+ expired = [
663
+ job
664
+ for job in jobs.values()
665
+ if job.status in _TERMINAL_JOB_STATUSES
666
+ and job.finished_at is not None
667
+ and current - job.finished_at > _JOB_RETENTION_SECONDS
668
+ ]
669
+
670
+ remaining_after_expiry = len(jobs) - len(expired)
671
+ overflow = max(0, remaining_after_expiry - _MAX_RETAINED_JOBS)
672
+ expired_ids = {job.id for job in expired}
673
+ terminal = sorted(
674
+ (
675
+ job
676
+ for job in jobs.values()
677
+ if job.id not in expired_ids and job.status in _TERMINAL_JOB_STATUSES
678
+ ),
679
+ key=lambda job: job.finished_at or job.created_at,
680
+ )
681
+ for job in [*expired, *terminal[:overflow]]:
682
+ jobs.pop(job.id, None)
683
+ shutil.rmtree(job.dir, ignore_errors=True)
684
+
685
+
686
+ @asynccontextmanager
687
+ async def _regeneration_slot(app: FastAPI, job: Job) -> AsyncIterator[None]:
688
+ """Reserve one global regeneration slot and the job's mutation lock."""
689
+ async with app.state.regeneration_counter_lock:
690
+ if app.state.active_regenerations >= _MAX_ACTIVE_REGENERATIONS:
691
+ raise HTTPException(
692
+ status_code=429,
693
+ detail=(
694
+ "too many active regenerations; "
695
+ f"limit is {_MAX_ACTIVE_REGENERATIONS}"
696
+ ),
697
+ )
698
+ app.state.active_regenerations += 1
699
+
700
+ try:
701
+ if job.mutation_lock.locked():
702
+ raise HTTPException(
703
+ status_code=409, detail="regeneration already in progress"
704
+ )
705
+ await job.mutation_lock.acquire()
706
+ try:
707
+ yield
708
+ finally:
709
+ job.mutation_lock.release()
710
+ finally:
711
+ async with app.state.regeneration_counter_lock:
712
+ app.state.active_regenerations -= 1
713
+
714
+
715
+ # ---------------------------------------------------------------------------
716
+ # Event emission
717
+ # ---------------------------------------------------------------------------
718
+
719
+
720
+ # Per-slide events arrive in bursts (two per slide plus a preview each) and
721
+ # each persist rewrites the WHOLE event log — O(N²) blocking file I/O on the
722
+ # event loop for a 30-page deck. They ride a debounce instead: a crash between
723
+ # debounced writes only costs recent per-slide detail, and a restored
724
+ # non-terminal session is marked interrupted anyway. Structural events
725
+ # (outline, gates, complete, error…) stay durable immediately.
726
+ _DEBOUNCED_EVENTS = frozenset({"slide_done", "unit_done", "preview_ready"})
727
+ _PERSIST_DEBOUNCE_SECONDS = 2.0
728
+
729
+
730
+ async def _emit(job: Job, event: str, data: Any) -> None:
731
+ """Append an SSE event to the job's log and wake any subscribers.
732
+
733
+ The write is pushed off the event loop with ``asyncio.to_thread``: a session
734
+ rewrite is a JSON serialisation of the whole job plus a file write, and doing
735
+ that inline blocked every other request (including the SSE stream this event
736
+ is meant to reach) for the duration.
737
+ """
738
+ job.events.append({"event": event, "data": data})
739
+ if (
740
+ event not in _DEBOUNCED_EVENTS
741
+ or time.time() - job.last_persist >= _PERSIST_DEBOUNCE_SECONDS
742
+ ):
743
+ # Stamp the clock synchronously so a burst of events cannot all decide
744
+ # they are due while the first write is still in flight.
745
+ job.last_persist = time.time()
746
+ await asyncio.to_thread(_persist_job, job)
747
+ job.updated.set()
748
+
749
+
750
+ async def _emit_gate(
751
+ job: Job, gate: str, status: str, note: Optional[str] = None
752
+ ) -> None:
753
+ """Record a gate outcome on the job *and* emit it.
754
+
755
+ Keeping the latest verdict on the job is what lets a regeneration reset the
756
+ board honestly: the four ticks belong to a specific artifact version, so a
757
+ new version has to earn them again rather than inherit them.
758
+ """
759
+ job.gates[gate] = status
760
+ data: Dict[str, Any] = {"gate": gate, "status": status}
761
+ if note:
762
+ data["note"] = note
763
+ await _emit(job, "gate_result", data)
764
+
765
+
766
+ def _prune_preview_versions(job: Job, keep: int = 2) -> None:
767
+ """Drop superseded ``preview/v{n}`` directories (best effort).
768
+
769
+ The published version and one predecessor are kept — a browser that already
770
+ has an old ``?v=`` URL in flight still gets an image instead of a 404.
771
+ """
772
+ root = job.previews_root
773
+ if not root.is_dir():
774
+ return
775
+ versions = []
776
+ for child in root.iterdir():
777
+ if child.is_dir() and re.fullmatch(r"v(\d+)", child.name):
778
+ versions.append((int(child.name[1:]), child))
779
+ for _version, path in sorted(versions, reverse=True)[keep:]:
780
+ shutil.rmtree(path, ignore_errors=True)
781
+
782
+
783
+ def _preview_file(job: Job, n: int) -> Optional[Path]:
784
+ """The PNG for page ``n`` of the *published* preview version, if it exists.
785
+
786
+ Falls back to the pre-versioning flat layout (``preview/page-NN.png``) so
787
+ sessions written by an older build still show their thumbnails.
788
+ """
789
+ name = f"page-{n:02d}.png"
790
+ candidate = job.preview_dir / name
791
+ if candidate.is_file():
792
+ return candidate
793
+ legacy = job.previews_root / name
794
+ return legacy if legacy.is_file() else None
795
+
796
+
797
+ def _download_url(job: Job) -> str:
798
+ return f"/api/jobs/{job.id}/download"
799
+
800
+
801
+ # Why an artifact is not servable, in the user's language. "deck not ready" told
802
+ # someone staring at a finished-looking screen precisely nothing.
803
+ _UNDOWNLOADABLE_BY_STATUS: Dict[str, str] = {
804
+ "pending": "這份工作還沒開始生成。",
805
+ "generating_outline": "大綱還在生成中,檔案尚未產生。",
806
+ "awaiting_approval": "還在等待你確認大綱,檔案尚未產生。",
807
+ "generating_slides": "內容還在逐頁生成中,檔案尚未產生。",
808
+ "rendering": "檔案正在算圖中,請稍候。",
809
+ "validating": "檔案正在通過格式驗證,請稍候。",
810
+ "qa": "設計品檢進行中,完成後才會釋出下載。",
811
+ "regenerating": "有一頁正在重生,完成後才會釋出新版本的下載。",
812
+ "cancelled": "這份工作已取消,沒有可下載的成品。",
813
+ }
814
+
815
+
816
+ def _undownloadable_reason(job: Job) -> str:
817
+ if job.status == "error":
818
+ detail = (job.error or {}).get("message", "")
819
+ return "這份工作在生成過程中失敗,沒有通過驗證的成品可以下載。" + (
820
+ f"(原因:{detail})" if detail else ""
821
+ )
822
+ known = _UNDOWNLOADABLE_BY_STATUS.get(job.status)
823
+ if known:
824
+ return known
825
+ if not job.odp_path.is_file():
826
+ return "找不到這份工作的成品檔案。"
827
+ # complete, file present, but the version on disk never passed the gates.
828
+ return (
829
+ "磁碟上的檔案沒有通過品質閘門(或不是最新一版),為避免交付未驗證的成品,"
830
+ "這裡不提供下載。請重新生成。"
831
+ )
832
+
833
+
834
+ def _session_title(job: Job) -> str:
835
+ if job.ir is not None and job.ir.title.strip():
836
+ return job.ir.title.strip()
837
+ if job.outline is not None and job.outline.pages:
838
+ # 與前端 taskName 同步:封面頁(role=="title")的標題優先於第一頁。
839
+ pages = job.outline.pages
840
+ cover = next((p for p in pages if p.role == "title"), pages[0])
841
+ title = cover.title.strip()
842
+ if title:
843
+ return title
844
+ first_line = next(
845
+ (line.strip() for line in job.prompt.splitlines() if line.strip()),
846
+ "未命名簡報",
847
+ )
848
+ return first_line[:80]
849
+
850
+
851
+ def _session_summary(job: Job) -> Dict[str, Any]:
852
+ preview = _preview_file(job, 1)
853
+ page_count = (
854
+ len(job.ir.slides)
855
+ if job.ir is not None
856
+ else len(job.outline.pages)
857
+ if job.outline is not None
858
+ else 0
859
+ )
860
+ data: Dict[str, Any] = {
861
+ "id": job.id,
862
+ "title": _session_title(job),
863
+ "prompt": job.prompt,
864
+ "status": job.status,
865
+ "created_at": job.created_at,
866
+ "updated_at": job.finished_at or job.created_at,
867
+ "page_count": page_count,
868
+ "preview_url": (
869
+ f"/api/jobs/{job.id}/preview/1.png" if preview is not None else None
870
+ ),
871
+ # A card only offers a download when the artifact is actually servable —
872
+ # otherwise the link 409s the moment it is clicked.
873
+ "download_url": _download_url(job) if job.downloadable else None,
874
+ }
875
+ if job.error is not None:
876
+ data["error"] = job.error
877
+ return data
878
+
879
+
880
+ def _persist_generated_assets(job: Job) -> None:
881
+ """Move generated in-memory image blobs into the job's isolated directory."""
882
+
883
+ generated = [
884
+ (asset_id, value)
885
+ for asset_id, value in job.assets.items()
886
+ if isinstance(value, AssetBlob)
887
+ ]
888
+ if not generated:
889
+ return
890
+ assets_dir = job.dir / "assets"
891
+ assets_dir.mkdir(parents=True, exist_ok=True)
892
+ for asset_id, blob in generated:
893
+ path = assets_dir / f"{asset_id}{blob.extension}"
894
+ path.write_bytes(blob.data)
895
+ job.assets[asset_id] = path
896
+
897
+
898
+ # Characters illegal in a filename on common filesystems, plus newlines.
899
+ _FILENAME_ILLEGAL = re.compile(r'[\\/:*?"<>|\r\n]')
900
+
901
+
902
+ def _sanitize_filename(name: str) -> str:
903
+ """Strip filename-illegal characters and surrounding whitespace (CJK kept)."""
904
+ return _FILENAME_ILLEGAL.sub("", name).strip()
905
+
906
+
907
+ def _download_filename(job: Job) -> str:
908
+ """A human, topic-based ``.odp`` filename (never the bare UUID unless empty).
909
+
910
+ Prefers the generated deck's title (``job.ir.title``); falls back to the
911
+ first 20 chars of the prompt; and if sanitising leaves nothing usable,
912
+ falls back to the job id. Chinese is preserved — FileResponse emits an
913
+ RFC 5987 ``filename*`` for non-ASCII names.
914
+ """
915
+ raw = ""
916
+ if job.ir is not None and job.ir.title and job.ir.title.strip():
917
+ raw = job.ir.title
918
+ elif job.prompt:
919
+ raw = job.prompt[:20]
920
+ cleaned = _sanitize_filename(raw)
921
+ if not cleaned:
922
+ cleaned = job.id
923
+ return f"{cleaned}.odp"
924
+
925
+
926
+ def _preview_url(job: Job, n: int) -> str:
927
+ """Preview URL for page ``n``, cache-busted after any re-render.
928
+
929
+ ``?v={k}`` only appears once the deck was re-rendered (QA repair, per-page
930
+ regenerate): the changed string forces the browser to refetch. The GET
931
+ route ignores the query — old un-versioned links keep working.
932
+ """
933
+ base = f"/api/jobs/{job.id}/preview/{n}.png"
934
+ return f"{base}?v={job.preview_version}" if job.preview_version > 0 else base
935
+
936
+
937
+ # ---------------------------------------------------------------------------
938
+ # The pipeline runner (a background asyncio task per job)
939
+ # ---------------------------------------------------------------------------
940
+
941
+
942
+ async def _rasterise_next_version(job: Job, source: Path) -> List[Path]:
943
+ """Rasterise ``source`` into the *next* preview version directory.
944
+
945
+ Nothing is published here — the caller decides whether this version becomes
946
+ the live one. Raises :class:`PreviewUnavailable` (no soffice) or whatever
947
+ ``render_pages`` raises; both are the caller's to interpret.
948
+ """
949
+ target = job.preview_dir_for(job.preview_version + 1)
950
+ shutil.rmtree(target, ignore_errors=True)
951
+ target.mkdir(parents=True, exist_ok=True)
952
+ return await _offload(job, render_pages, source, target)
953
+
954
+
955
+ def _publish_previews(job: Job) -> None:
956
+ """Move the pointer to the version just rasterised, and prune the old ones."""
957
+ job.preview_version += 1
958
+ _prune_preview_versions(job)
959
+
960
+
961
+ async def _emit_previews(job: Job) -> None:
962
+ """Rasterise the deck to PNGs, emit the ``libreoffice`` gate + a ``preview_ready``.
963
+
964
+ Best-effort: the previews degrade, they never crash the pipeline. The
965
+ ``libreoffice`` gate reports the real outcome:
966
+
967
+ * ``render_pages`` succeeds → ``gate_result{libreoffice, pass}`` then one
968
+ ``preview_ready`` per page.
969
+ * :class:`PreviewUnavailable` (no soffice) → ``gate_result{libreoffice,
970
+ skipped}`` (an absent tool is skipped, not a failure).
971
+ * any other exception → ``gate_result{libreoffice, fail}`` but the job
972
+ continues — previews are best-effort.
973
+
974
+ Pages are written to a fresh version directory and only published once the
975
+ whole rasterisation succeeded, so a half-written set never replaces a good
976
+ one and a shorter deck never inherits the previous deck's extra pages.
977
+ """
978
+ if job.ir is None:
979
+ return
980
+ try:
981
+ paths = await _rasterise_next_version(job, job.odp_path)
982
+ except PreviewUnavailable:
983
+ await _emit_gate(job, "libreoffice", "skipped")
984
+ return
985
+ except Exception:
986
+ await _emit_gate(job, "libreoffice", "fail")
987
+ return
988
+ _publish_previews(job)
989
+ await _emit_gate(job, "libreoffice", "pass")
990
+ for n, _path in enumerate(paths, start=1):
991
+ await _emit(job, "preview_ready", {"n": n, "url": _preview_url(job, n)})
992
+
993
+
994
+ def _qa_failure_reason(vision_backend: str, exc: BaseException) -> str:
995
+ """A zh-TW one-liner explaining why the design gate could not run.
996
+
997
+ The provider's own message is kept (whitespace-collapsed, truncated) — a line
998
+ like "the free quota has been exhausted" is exactly what tells the operator
999
+ what to fix — and the selected source is named, because one ``.env`` line
1000
+ decides it.
1001
+ """
1002
+ detail = " ".join(str(exc).split())[:240] or exc.__class__.__name__
1003
+ return f"視覺品檢無法執行(來源:{vision_backend}):{detail}"
1004
+
1005
+
1006
+ async def _run_qa_loop(job: Job, outline: Optional[Outline]) -> None:
1007
+ """Run the design-QA loop and emit one ``qa_round`` per round.
1008
+
1009
+ Uses the same ``run_qa_loop`` the CLI's ``--qa`` calls. The vision backend
1010
+ comes from ``ODFORGE_VISION_BACKEND`` (default ``off``); with it off (or no
1011
+ soffice) the loop degrades to zero rounds. A QA error never fails the
1012
+ generation — but it is *recorded* (logged + ``job.qa_error``) so the design
1013
+ gate can say why it did not run, instead of reporting a bare "未啟用" that
1014
+ looks identical to the gate being turned off. Because ``run_qa_loop`` runs its
1015
+ rounds internally, the per-round events are emitted from its returned report.
1016
+ """
1017
+ vision_backend = job.vision_backend or os.environ.get(
1018
+ "ODFORGE_VISION_BACKEND", "off"
1019
+ )
1020
+ # The repair path re-runs the layout budget, so QA is a place content can be
1021
+ # dropped. It was the only such place with no collector attached.
1022
+ dropped: List[DroppedContent] = []
1023
+ try:
1024
+ qa_kwargs = {
1025
+ "outline": outline,
1026
+ "backend": vision_backend,
1027
+ "llm_backend": job.backend,
1028
+ "dropped": dropped,
1029
+ }
1030
+ if job.assets:
1031
+ qa_kwargs["render_assets"] = job.assets
1032
+ report = await _offload(
1033
+ job,
1034
+ run_qa_loop,
1035
+ job.ir,
1036
+ job.odp_path,
1037
+ **qa_kwargs,
1038
+ )
1039
+ except Exception as exc:
1040
+ job.qa_error = _qa_failure_reason(vision_backend, exc)
1041
+ logger.warning(
1042
+ "qa_failed job_id=%s vision_backend=%s error=%s",
1043
+ job.id,
1044
+ vision_backend,
1045
+ exc,
1046
+ exc_info=True,
1047
+ )
1048
+ return
1049
+ job.qa_report = report
1050
+ if dropped:
1051
+ job.dropped_content = [*job.dropped_content, *dropped]
1052
+ await _emit(
1053
+ job,
1054
+ "content_degraded",
1055
+ {"items": [d.model_dump(mode="json") for d in dropped]},
1056
+ )
1057
+ for round_no, findings in enumerate(report.findings_by_round, start=1):
1058
+ await _emit(
1059
+ job,
1060
+ "qa_round",
1061
+ {
1062
+ "round": round_no,
1063
+ "findings": [f.model_dump(mode="json") for f in findings],
1064
+ },
1065
+ )
1066
+
1067
+
1068
+ class JobCancelled(Exception):
1069
+ """The job was cancelled between stages; stop without emitting completion."""
1070
+
1071
+
1072
+ def _abort_if_cancelled(job: Job) -> None:
1073
+ """Checkpoint before any stage that starts new work or claims success.
1074
+
1075
+ ``Task.cancel()`` alone is not enough. A cancel that lands while the job is
1076
+ inside ``asyncio.to_thread`` does not interrupt the thread — the awaited call
1077
+ finishes first, and only then does the CancelledError surface. Between those
1078
+ two moments the pipeline would happily start a render, kick off a QA loop, or
1079
+ emit ``complete`` with a download link for a job the user stopped. Explicit
1080
+ checkpoints close that window.
1081
+ """
1082
+ if job.status == "cancelled":
1083
+ raise JobCancelled
1084
+
1085
+
1086
+ async def run_job(job: Job) -> None:
1087
+ """Drive one job through the two-stage pipeline, emitting SSE events.
1088
+
1089
+ Stages: outline → (await approval if interactive) → slides → render →
1090
+ previews → optional QA → complete. Any unexpected failure emits a single
1091
+ ``error`` event carrying the stage it failed in and stops the job.
1092
+ """
1093
+ stage = "outline"
1094
+ try:
1095
+ job.status = "generating_outline"
1096
+ model_prompt = job.prompt
1097
+ reference_context = format_reference_context(job.reference_documents)
1098
+ if reference_context:
1099
+ model_prompt = f"{model_prompt}\n\n{reference_context}"
1100
+ outline = await _offload(
1101
+ job,
1102
+ generate_outline,
1103
+ model_prompt,
1104
+ job.backend,
1105
+ pages=job.pages,
1106
+ language=job.language,
1107
+ )
1108
+ if job.mode:
1109
+ outline = outline.model_copy(update={"mode": job.mode})
1110
+ # Language is application-owned: the facade stamps it too, but stage 2
1111
+ # reads it off the outline, so the pipeline enforces it here rather than
1112
+ # trusting every backend implementation to have remembered.
1113
+ outline = outline.model_copy(update={"language": job.language})
1114
+ # A user template beats the model's own art direction, and it has to be
1115
+ # applied HERE rather than only on the finished deck: stage 2 is shown
1116
+ # the outline's design, and telling the writer one palette while the
1117
+ # renderer paints another is how "presenter on a dark theme" ends up
1118
+ # written for a light one.
1119
+ if job.design is not None:
1120
+ outline = outline.model_copy(update={"design": job.design})
1121
+ outline = outline.model_copy(
1122
+ update={
1123
+ "media_assets": job.asset_refs,
1124
+ "image_generation_available": (
1125
+ os.getenv("ODFORGE_IMAGE_BACKEND", "off").lower() == "http"
1126
+ and bool(os.getenv("ODFORGE_IMAGE_ENDPOINT", "").strip())
1127
+ ),
1128
+ }
1129
+ )
1130
+ job.outline = outline
1131
+ await _emit(job, "outline", outline.model_dump(mode="json"))
1132
+
1133
+ if job.interactive:
1134
+ stage = "outline_approval"
1135
+ job.status = "awaiting_approval"
1136
+ await _emit(job, "awaiting_approval", {})
1137
+ try:
1138
+ await asyncio.wait_for(
1139
+ job.approval.wait(), timeout=_APPROVAL_TIMEOUT_SECONDS
1140
+ )
1141
+ except TimeoutError as exc:
1142
+ raise RuntimeError("大綱確認逾時,請重新建立工作") from exc
1143
+ # The /outline endpoint may have replaced job.outline (an edit).
1144
+ outline = job.outline
1145
+
1146
+ _abort_if_cancelled(job)
1147
+ stage = "slides"
1148
+ job.status = "generating_slides"
1149
+ # Collect anything the layout budget had to remove, so it can be shown
1150
+ # rather than buried in a speaker note nobody opens.
1151
+ dropped: List[DroppedContent] = []
1152
+ ir = await _offload(job, generate_slides, outline, job.backend, dropped)
1153
+ if dropped:
1154
+ job.dropped_content = dropped
1155
+ await _emit(
1156
+ job,
1157
+ "content_degraded",
1158
+ {"items": [d.model_dump(mode="json") for d in dropped]},
1159
+ )
1160
+ # --theme parity: lock a preset and drop any LLM-chosen design.
1161
+ if job.theme:
1162
+ ir = ir.model_copy(update={"theme": job.theme, "design": None})
1163
+ # A user template wins over both: it is the one look the user picked by
1164
+ # name. (Re-applied here because stage 2 could have returned its own.)
1165
+ if job.design is not None:
1166
+ ir = ir.model_copy(update={"design": job.design})
1167
+ # 版式 and cover branding are both app-owned: whatever the model may
1168
+ # have emitted in these fields is replaced by what the user chose.
1169
+ if job.style:
1170
+ ir = ir.model_copy(update={"style": job.style})
1171
+ ir = ir.model_copy(update={"branding": job.branding})
1172
+ job.ir = ir
1173
+ for n, slide in enumerate(ir.slides, start=1):
1174
+ job.slides_done = n
1175
+ payload = {"n": n, "slide": slide.model_dump(mode="json")}
1176
+ await _emit(job, "slide_done", payload)
1177
+ # unit_done 為 F4 起的正名;與 slide_done 同 data 並發。舊事件保留以向前相容。
1178
+ await _emit(job, "unit_done", payload)
1179
+
1180
+ _abort_if_cancelled(job)
1181
+ stage = "render"
1182
+ job.status = "rendering"
1183
+ needs_asset_context = bool(job.assets) or any(
1184
+ slide.image is not None and bool(slide.image.prompt)
1185
+ for slide in ir.slides
1186
+ )
1187
+ if needs_asset_context:
1188
+ await _offload(job, render, ir, job.odp_path, assets=job.assets)
1189
+ else:
1190
+ await _offload(job, render, ir, job.odp_path)
1191
+ _persist_generated_assets(job)
1192
+ # A new artifact exists on disk; it is NOT validated until the gates below
1193
+ # say so, and the download endpoint refuses anything unvalidated.
1194
+ job.artifact_version += 1
1195
+
1196
+ # Deterministic validation gates (zip/mimetype + XML well-formed) on the
1197
+ # freshly rendered deck, using validate.py's existing functions. Each
1198
+ # emits a gate_result; a failure of either stops the pipeline (the
1199
+ # existing except emits an ``error`` event carrying stage="validate").
1200
+ stage = "validate"
1201
+ job.status = "validating"
1202
+ report = await _offload(job, validate_odf, job.odp_path)
1203
+ zip_ok, zip_msg = report.gates["structure"]
1204
+ xml_ok, xml_msg = report.gates["xml"]
1205
+ await _emit_gate(job, "zip", "pass" if zip_ok else "fail")
1206
+ await _emit_gate(job, "xml", "pass" if xml_ok else "fail")
1207
+ if not (zip_ok and xml_ok):
1208
+ problems = [m for ok, m in ((zip_ok, zip_msg), (xml_ok, xml_msg)) if not ok]
1209
+ raise RuntimeError("ODF 驗證未通過:" + ";".join(problems))
1210
+ job.validated_version = job.artifact_version
1211
+
1212
+ stage = "preview"
1213
+ await _emit_previews(job)
1214
+
1215
+ if job.qa:
1216
+ _abort_if_cancelled(job)
1217
+ stage = "qa"
1218
+ job.status = "qa"
1219
+ # Snapshot before the loop so the repaired pages can be identified and
1220
+ # re-emitted. Without this the cockpit keeps showing the pre-repair
1221
+ # title/role for a page whose content QA replaced — the thumbnail
1222
+ # updates (new PNG) while the caption underneath it lies.
1223
+ before_qa = [slide.model_dump(mode="json") for slide in ir.slides]
1224
+ await _run_qa_loop(job, outline)
1225
+ _persist_generated_assets(job)
1226
+ # ``repaired`` means QA mutated slides and re-rendered the deck, so
1227
+ # the first-pass PNGs are stale — refresh them (with a bumped cache
1228
+ # version so the browser refetches the same-named pages). Round
1229
+ # count is NOT the signal: a partial report can be rounds=1 yet
1230
+ # repaired. A clean unrepaired run changed nothing — don't re-emit.
1231
+ if job.qa_report is not None and job.qa_report.repaired:
1232
+ # QA wrote a NEW deck to disk. The zip/xml/LibreOffice ticks the
1233
+ # user is looking at were earned by the pre-repair file; carrying
1234
+ # them over would certify bytes nobody checked. Re-run all three
1235
+ # against the artifact actually being shipped.
1236
+ stage = "validate"
1237
+ job.artifact_version += 1
1238
+ report = await _offload(job, validate_odf, job.odp_path)
1239
+ zip_ok, zip_msg = report.gates["structure"]
1240
+ xml_ok, xml_msg = report.gates["xml"]
1241
+ await _emit_gate(job, "zip", "pass" if zip_ok else "fail")
1242
+ await _emit_gate(job, "xml", "pass" if xml_ok else "fail")
1243
+ if not (zip_ok and xml_ok):
1244
+ problems = [
1245
+ m for ok, m in ((zip_ok, zip_msg), (xml_ok, xml_msg)) if not ok
1246
+ ]
1247
+ raise RuntimeError("QA 修補後的 ODF 驗證未通過:" + ";".join(problems))
1248
+ job.validated_version = job.artifact_version
1249
+ # Re-emit every page QA actually rewrote, so the outline rail,
1250
+ # the thumbnail caption and the single-page detail all describe
1251
+ # the deck that is about to be downloaded.
1252
+ for n, slide in enumerate(ir.slides, start=1):
1253
+ payload = slide.model_dump(mode="json")
1254
+ if n <= len(before_qa) and before_qa[n - 1] == payload:
1255
+ continue
1256
+ event = {"n": n, "slide": payload}
1257
+ await _emit(job, "slide_done", event)
1258
+ await _emit(job, "unit_done", event)
1259
+ if job.outline is not None and n <= len(job.outline.pages):
1260
+ job.outline.pages[n - 1] = _page_contract(
1261
+ slide, job.outline.pages[n - 1], None
1262
+ )
1263
+ stage = "preview"
1264
+ await _emit_previews(job)
1265
+
1266
+ # Design gate: reflects the QA outcome, in the same four-way vocabulary
1267
+ # the other gates use — and the distinction the whole gate rests on is
1268
+ # ``skipped`` vs ``unknown``:
1269
+ #
1270
+ # * ``skipped`` — nobody *asked* for a review (QA off, or this job chose
1271
+ # no vision source). Nothing is wrong; the user opted out.
1272
+ # * ``unknown`` — a review *was* asked for and could not be delivered
1273
+ # (no soffice, provider refused, response unreadable). The deck's design
1274
+ # is genuinely unverified, which is not the same as opting out and is
1275
+ # emphatically not a pass.
1276
+ # * ``pass`` / ``fail`` — a review completed and returned a verdict.
1277
+ note: Optional[str] = None
1278
+ resolved_vision = job.vision_backend or os.environ.get(
1279
+ "ODFORGE_VISION_BACKEND", "off"
1280
+ )
1281
+ if not job.qa:
1282
+ design_status = "skipped"
1283
+ note = "這次生成關閉了設計品質檢查。"
1284
+ elif resolved_vision == "off":
1285
+ # No vision source means the critic returns zero findings by
1286
+ # construction — that is an opt-out, not a review.
1287
+ design_status = "skipped"
1288
+ if job.qa_error:
1289
+ # 真實的失敗原因永遠優先於「你沒開」的泛用說明。
1290
+ design_status = "unknown"
1291
+ note = job.qa_error
1292
+ elif job.vision_backend == "off":
1293
+ # 是這次工作自己選了 off,不是環境變數 — 別叫使用者去改 .env。
1294
+ note = "這次生成選擇不使用視覺模型,這一輪只跑了前三道格式驗證。"
1295
+ else:
1296
+ note = (
1297
+ "沒有設定視覺模型(ODFORGE_VISION_BACKEND=off),"
1298
+ "這一輪只跑了前三道格式驗證。"
1299
+ )
1300
+ elif job.qa_report is None:
1301
+ # QA was requested and threw: unverified, not opted out.
1302
+ design_status = "unknown"
1303
+ note = job.qa_error or "視覺品檢未能完成。"
1304
+ else:
1305
+ # The report's own verdict is authoritative — it already encodes
1306
+ # "nobody looked" as ``unknown`` rather than a vacuous pass.
1307
+ design_status = job.qa_report.verdict
1308
+ note = job.qa_report.failure or job.qa_report.note
1309
+ await _emit_gate(job, "design", design_status, note)
1310
+
1311
+ _abort_if_cancelled(job)
1312
+ job.status = "complete"
1313
+ job.finished_at = time.time()
1314
+ data: Dict[str, Any] = {"download_url": _download_url(job)}
1315
+ if job.qa_report is not None:
1316
+ data["qa_report"] = job.qa_report.model_dump(mode="json")
1317
+ await _emit(job, "complete", data)
1318
+ except JobCancelled:
1319
+ # 取消端點已經寫過狀態與事件了;這裡安靜收工,不要再蓋一個 error 上去,
1320
+ # 更不要發出 complete —— 使用者按過取消,就不該再收到「完成」。
1321
+ logger.info("job_cancelled job_id=%s stage=%s", job.id, stage)
1322
+ except Exception as exc:
1323
+ job.status = "error"
1324
+ job.finished_at = time.time()
1325
+ job.error = {"message": str(exc), "stage": stage}
1326
+ await _emit(job, "error", {"message": str(exc), "stage": stage})
1327
+
1328
+
1329
+ def _page_contract(slide, fallback: PageRole, instruction: Optional[str]) -> PageRole:
1330
+ """The outline row a regenerated slide should be described by afterwards.
1331
+
1332
+ Regeneration used to leave ``outline.pages[n-1]`` frozen at whatever stage 1
1333
+ first decided. That is how a QA repair got undone: QA upgrades page 4 from
1334
+ ``title-content`` to ``process``, the user then regenerates page 4, and the
1335
+ stale outline row hands the model back the *original* role — silently
1336
+ reverting the fix. The contract has to follow the artifact.
1337
+ """
1338
+ gist = fallback.gist
1339
+ if instruction:
1340
+ # 使用者的調整指示是新的頁面意圖,不是一次性的補充;下次重生要看得到。
1341
+ gist = f"{gist}(調整指示:{instruction})"
1342
+ return PageRole(
1343
+ role=slide.layout,
1344
+ title=slide.title or fallback.title,
1345
+ gist=gist,
1346
+ visual_intent=fallback.visual_intent,
1347
+ )
1348
+
1349
+
1350
+ async def regenerate_slide(
1351
+ job: Job, n: int, instruction: Optional[str]
1352
+ ) -> Dict[str, Any]:
1353
+ """Regenerate ONLY page ``n``, transactionally.
1354
+
1355
+ Builds a one-page sub-outline from that page's role/title/gist (the same
1356
+ shape the QA repair path uses), folding ``instruction`` into the gist, and
1357
+ re-runs stage 2 against just that page. Untouched pages are never re-sent,
1358
+ so they cannot drift.
1359
+
1360
+ **Nothing user-visible changes until everything succeeds.** The candidate
1361
+ slide is rendered to a side file, validated, and rasterised into an unused
1362
+ preview version; only then are the in-memory IR, the deck on disk, the
1363
+ published previews and the version counters swapped over — in that order, as
1364
+ one step. Any failure before the swap leaves the previous IR, the previous
1365
+ ``deck.odp``, the previous previews and the previous gate results exactly as
1366
+ they were, and raises. The alternative — the old in-place mutation — meant a
1367
+ render that blew up after ``job.ir.slides[n-1]`` was replaced left a job
1368
+ whose IR, artifact and previews disagreed with each other, and whose download
1369
+ still served the failed page's predecessor under the new page's title.
1370
+
1371
+ Because the artifact changes, the deterministic gates are re-run and the
1372
+ design gate is invalidated: the vision critic reviewed the *old* page 4.
1373
+
1374
+ This is a **synchronous** operation (unlike initial generation): the result
1375
+ comes back to the caller in the HTTP response, not via the SSE stream — that
1376
+ stream's lifecycle already ended at ``complete``. Returns ``{"n", "slide",
1377
+ "preview_url", "gates", "version"}``; ``preview_url`` is ``None`` when
1378
+ previews are unavailable (no soffice).
1379
+ """
1380
+ assert job.ir is not None and job.outline is not None # guarded by caller
1381
+ base = job.outline.pages[n - 1]
1382
+ gist = base.gist
1383
+ if instruction:
1384
+ gist = f"{gist}(調整指示:{instruction})"
1385
+ sub = Outline(
1386
+ design=job.outline.design,
1387
+ mode=job.outline.mode,
1388
+ pages=[
1389
+ PageRole(
1390
+ role=base.role,
1391
+ title=base.title,
1392
+ gist=gist,
1393
+ visual_intent=base.visual_intent,
1394
+ )
1395
+ ],
1396
+ source_prompt=job.outline.source_prompt or job.prompt,
1397
+ media_assets=job.asset_refs,
1398
+ image_generation_available=job.outline.image_generation_available,
1399
+ # Without this a regenerated page comes back in zh-TW while the rest of
1400
+ # the deck is English — the one page the user asked to fix.
1401
+ language=job.outline.language,
1402
+ )
1403
+ # The layout budget can silently drop bullets here exactly as it can during
1404
+ # the first generation. Until this collector existed, regeneration was the
1405
+ # one path where content vanished with nobody told (R2-03).
1406
+ dropped: List[DroppedContent] = []
1407
+ generated = await _offload(job, generate_slides, sub, job.backend, dropped)
1408
+ if not generated.slides:
1409
+ raise RuntimeError("模型沒有回傳這一頁的內容,原本的版本維持不變")
1410
+
1411
+ # ---- build the candidate, entirely off to the side ----------------------
1412
+ candidate_ir = job.ir.model_copy(deep=True)
1413
+ candidate_ir.slides[n - 1] = generated.slides[0]
1414
+ candidate_path = job.dir / "deck.candidate.odp"
1415
+ candidate_preview = job.preview_dir_for(job.preview_version + 1)
1416
+
1417
+ def _discard() -> None:
1418
+ candidate_path.unlink(missing_ok=True)
1419
+ shutil.rmtree(candidate_preview, ignore_errors=True)
1420
+
1421
+ try:
1422
+ needs_asset_context = bool(job.assets) or any(
1423
+ slide.image is not None and bool(slide.image.prompt)
1424
+ for slide in candidate_ir.slides
1425
+ )
1426
+ if needs_asset_context:
1427
+ await _offload(
1428
+ job, render, candidate_ir, candidate_path, assets=job.assets
1429
+ )
1430
+ else:
1431
+ await _offload(job, render, candidate_ir, candidate_path)
1432
+
1433
+ report = await _offload(job, validate_odf, candidate_path)
1434
+ zip_ok, zip_msg = report.gates["structure"]
1435
+ xml_ok, xml_msg = report.gates["xml"]
1436
+ if not (zip_ok and xml_ok):
1437
+ problems = [m for ok, m in ((zip_ok, zip_msg), (xml_ok, xml_msg)) if not ok]
1438
+ raise RuntimeError("重生後的 ODF 驗證未通過:" + ";".join(problems))
1439
+
1440
+ # Previews are best-effort *as a feature*, but a preview run that dies
1441
+ # unexpectedly is a signal the deck is broken — so only the documented
1442
+ # degrade (no soffice) is tolerated here. Anything else rolls back.
1443
+ libreoffice_status = "pass"
1444
+ try:
1445
+ paths = await _rasterise_next_version(job, candidate_path)
1446
+ except PreviewUnavailable:
1447
+ paths = []
1448
+ libreoffice_status = "skipped"
1449
+ # Writing generated image blobs to disk is the last thing that can fail,
1450
+ # so it happens here — inside the rollback — rather than as the opening
1451
+ # line of a commit block that is supposed to be infallible.
1452
+ _persist_generated_assets(job)
1453
+ except BaseException:
1454
+ _discard()
1455
+ raise
1456
+
1457
+ # ---- commit --------------------------------------------------------------
1458
+ # ``os.replace`` is the single point of no return and the only step here that
1459
+ # touches the filesystem. It goes first: if it fails (a Windows share lock,
1460
+ # a full disk) the candidate is discarded and the job still has its previous
1461
+ # IR, deck, previews, gates and versions — all of them, consistently. Every
1462
+ # statement after it is an in-memory assignment that cannot raise, which is
1463
+ # what makes "all or nothing" a property of the code rather than a hope.
1464
+ try:
1465
+ os.replace(candidate_path, job.odp_path)
1466
+ except BaseException:
1467
+ _discard()
1468
+ raise
1469
+
1470
+ job.ir = candidate_ir
1471
+ job.outline.pages[n - 1] = _page_contract(
1472
+ candidate_ir.slides[n - 1], base, instruction
1473
+ )
1474
+ job.artifact_version += 1
1475
+ job.validated_version = job.artifact_version
1476
+ # Publish unconditionally, even when the rasterisation produced nothing.
1477
+ # Leaving the pointer on the previous version means every thumbnail request
1478
+ # for the new deck is answered with a picture of the old one — the preview
1479
+ # would be quietly, confidently wrong. An empty version directory 404s, and
1480
+ # "no image" is the truth here.
1481
+ _publish_previews(job)
1482
+ job.gates["zip"] = "pass"
1483
+ job.gates["xml"] = "pass"
1484
+ job.gates["libreoffice"] = libreoffice_status
1485
+ # The critic reviewed the page this one just replaced. Its verdict does not
1486
+ # transfer — a stale green tick on regenerated content is exactly the "舊綠燈"
1487
+ # this whole path exists to prevent.
1488
+ design_note = "這一頁重生後尚未經過視覺品檢,設計閘結果已重設。"
1489
+ job.gates["design"] = "unknown"
1490
+ job.qa_report = None
1491
+ if dropped:
1492
+ job.dropped_content = [*job.dropped_content, *dropped]
1493
+
1494
+ preview_url = _preview_url(job, n) if len(paths) >= n else None
1495
+ gates = [
1496
+ {"gate": "zip", "status": "pass"},
1497
+ {"gate": "xml", "status": "pass"},
1498
+ {"gate": "libreoffice", "status": libreoffice_status},
1499
+ {"gate": "design", "status": "unknown", "note": design_note},
1500
+ ]
1501
+
1502
+ # ---- make the new state survive a refresh (R1-02) ------------------------
1503
+ # The cockpit rebuilds itself by replaying this log. Until these events were
1504
+ # appended, a successful regeneration existed only in the HTTP response: F5
1505
+ # replayed the *previous* slide, the previous gates and the previous preview
1506
+ # while the download served the new deck.
1507
+ await _emit(job, "qa_invalidated", {"n": n, "reason": design_note})
1508
+ payload = {"n": n, "slide": job.ir.slides[n - 1].model_dump(mode="json")}
1509
+ await _emit(job, "slide_done", payload)
1510
+ await _emit(job, "unit_done", payload)
1511
+ # ``url: null`` is meaningful, not an omission: it says "this page has no
1512
+ # current thumbnail". The alternative — staying silent — leaves the previous
1513
+ # deck's image on screen labelled as the new page.
1514
+ await _emit(job, "preview_ready", {"n": n, "url": preview_url})
1515
+ if dropped:
1516
+ await _emit(
1517
+ job,
1518
+ "content_degraded",
1519
+ {"items": [d.model_dump(mode="json") for d in dropped]},
1520
+ )
1521
+ for gate in gates:
1522
+ await _emit_gate(job, gate["gate"], gate["status"], gate.get("note"))
1523
+ # Re-terminating the log: the job really is complete again, and a replay that
1524
+ # stopped before this point would restore a cockpit stuck mid-generation.
1525
+ await _emit(job, "complete", {"download_url": _download_url(job)})
1526
+
1527
+ return {
1528
+ "n": n,
1529
+ "slide": job.ir.slides[n - 1].model_dump(mode="json"),
1530
+ "preview_url": preview_url,
1531
+ "version": job.artifact_version,
1532
+ "dropped_content": [d.model_dump(mode="json") for d in dropped],
1533
+ "gates": gates,
1534
+ }
1535
+
1536
+
1537
+ # ---------------------------------------------------------------------------
1538
+ # Request bodies
1539
+ # ---------------------------------------------------------------------------
1540
+
1541
+
1542
+ class StrictBody(BaseModel):
1543
+ """Request bodies reject unknown fields instead of dropping them.
1544
+
1545
+ ``doc_type`` was silently discarded for a whole release: the frontend sent
1546
+ ``"ods"``, pydantic dropped the key, and the user downloaded a ``.odp``
1547
+ believing they had asked for a spreadsheet. A 422 naming the field is the
1548
+ only version of that story where anyone finds out.
1549
+ """
1550
+
1551
+ model_config = ConfigDict(extra="forbid")
1552
+
1553
+
1554
+ # The whole batch of reference material, not one file of it. Six assets each
1555
+ # just under the per-file cap decoded to ~17 MiB and arrived as ~23 MiB of JSON —
1556
+ # accepted, parsed and held in memory, because nothing had ever added the totals
1557
+ # up. The frontend enforces the same number, which is a courtesy to the user and
1558
+ # no kind of gate: a client is free not to run it.
1559
+ MAX_TOTAL_ASSET_BYTES = 16 * 1024 * 1024
1560
+ # Base64 costs 4 bytes per 3, plus a short ``data:...;base64,`` prefix each. This
1561
+ # is the cheap pre-check that runs *before* any decoding is attempted.
1562
+ MAX_TOTAL_ASSET_ENCODED = (MAX_TOTAL_ASSET_BYTES // 3 + 1) * 4 + 6 * 128
1563
+
1564
+
1565
+ def _decoded_length(data_url: str) -> int:
1566
+ """Decoded byte count of a base64 data URI, computed without decoding it.
1567
+
1568
+ Deriving the size from the string's length is the point: calling
1569
+ ``base64.b64decode`` to find out how big something is means allocating the
1570
+ thing you are trying to refuse.
1571
+ """
1572
+ _, _, payload = data_url.partition(",")
1573
+ padding = len(payload) - len(payload.rstrip("="))
1574
+ return max(0, (len(payload) * 3) // 4 - padding)
1575
+
1576
+
1577
+ def _check_asset_budget(assets: List[Any]) -> None:
1578
+ """Reject a batch of references whose *total* exceeds the budget."""
1579
+ urls = [a.data_url for a in assets if getattr(a, "data_url", None)]
1580
+ encoded = sum(len(u) for u in urls)
1581
+ if encoded > MAX_TOTAL_ASSET_ENCODED:
1582
+ raise ValueError(
1583
+ f"參考檔案總量過大(編碼後約 {encoded / 1024 / 1024:.1f} MiB);"
1584
+ f"全部檔案合計上限為 {MAX_TOTAL_ASSET_BYTES // 1024 // 1024} MiB,"
1585
+ "請減少檔案數量或改用較小的檔案。"
1586
+ )
1587
+ decoded = sum(_decoded_length(u) for u in urls)
1588
+ if decoded > MAX_TOTAL_ASSET_BYTES:
1589
+ raise ValueError(
1590
+ f"參考檔案總量過大({decoded / 1024 / 1024:.1f} MiB);"
1591
+ f"全部檔案合計上限為 {MAX_TOTAL_ASSET_BYTES // 1024 // 1024} MiB,"
1592
+ "請減少檔案數量或改用較小的檔案。"
1593
+ )
1594
+
1595
+
1596
+ class AssetUpload(StrictBody):
1597
+ description: str = Field(min_length=1, max_length=240)
1598
+ credit: str = Field(default="", max_length=160)
1599
+ data_url: str = Field(max_length=12_000_000)
1600
+
1601
+ @field_validator("description")
1602
+ @classmethod
1603
+ def description_must_have_content(cls, value: str) -> str:
1604
+ value = value.strip()
1605
+ if not value:
1606
+ raise ValueError("asset description must not be blank")
1607
+ return value
1608
+
1609
+ @field_validator("data_url")
1610
+ @classmethod
1611
+ def data_url_must_be_supported(cls, value: str) -> str:
1612
+ lowered = value.lower()
1613
+ if not (
1614
+ lowered.startswith("data:image/png;base64,")
1615
+ or lowered.startswith("data:image/jpeg;base64,")
1616
+ or lowered.startswith("data:application/pdf;base64,")
1617
+ ):
1618
+ raise ValueError("reference must be a PDF/PNG/JPEG base64 data URI")
1619
+ return value
1620
+
1621
+
1622
+ class GenerateBody(StrictBody):
1623
+ prompt: str = Field(min_length=1, max_length=8000)
1624
+ mode: Optional[Literal["presenter", "detailed"]] = None
1625
+ # Validated against the theme registry (like ``backend``), so adding a
1626
+ # built-in preset does not mean editing a Literal in three files.
1627
+ theme: Optional[str] = None
1628
+ # A user template's tokens, sent instead of ``theme``. Validated by
1629
+ # DesignSpec itself — an unreadable palette is a 422, not a grey deck.
1630
+ design: Optional[DesignSpec] = None
1631
+ # 版式: independent of colour, so a palette can be worn by any composition.
1632
+ style: Optional[str] = None
1633
+ language: str = "zh-TW"
1634
+ # Cover branding. ``logo`` is one more base64 image upload; it is stored
1635
+ # apart from ``assets`` so the model is never offered the crest as media.
1636
+ byline: str = Field(default="", max_length=160)
1637
+ logo: Optional[AssetUpload] = None
1638
+ logo_placement: Literal["cover", "cover-closing", "all"] = "cover-closing"
1639
+ interactive: bool = False
1640
+ qa: bool = False
1641
+ # Validated against the registries rather than a hand-kept Literal, so a new
1642
+ # source is one edit (the factory) instead of five.
1643
+ backend: Optional[str] = None
1644
+ vision_backend: Optional[str] = None
1645
+ # Only presentations (odp) are supported today; a non-"odp" value is a 422
1646
+ # with a human message (checked in the endpoint so ``detail`` is a plain
1647
+ # zh-TW string, not pydantic's list-of-errors shape).
1648
+ doc_type: str = "odp"
1649
+ # Optional target page count (inclusive 3..30); out of range → pydantic 422.
1650
+ pages: Optional[int] = Field(default=None, ge=MIN_REQUESTED_PAGES, le=MAX_OUTLINE_PAGES)
1651
+ assets: List[AssetUpload] = Field(default_factory=list, max_length=6)
1652
+
1653
+ @model_validator(mode="after")
1654
+ def assets_must_fit_the_batch_budget(self) -> GenerateBody:
1655
+ _check_asset_budget(self.assets)
1656
+ return self
1657
+
1658
+ @field_validator("prompt")
1659
+ @classmethod
1660
+ def prompt_must_have_content(cls, value: str) -> str:
1661
+ value = value.strip()
1662
+ if not value:
1663
+ raise ValueError("prompt must not be blank")
1664
+ return value
1665
+
1666
+ @field_validator("backend")
1667
+ @classmethod
1668
+ def backend_must_be_registered(cls, value: Optional[str]) -> Optional[str]:
1669
+ if value is not None and value not in llm.BACKENDS:
1670
+ raise ValueError(f"unknown text backend; available: {sorted(llm.BACKENDS)}")
1671
+ return value
1672
+
1673
+ @field_validator("theme")
1674
+ @classmethod
1675
+ def theme_must_be_a_preset(cls, value: Optional[str]) -> Optional[str]:
1676
+ if value is not None and value not in THEMES:
1677
+ raise ValueError(f"unknown theme; available: {sorted(THEMES)}")
1678
+ return value
1679
+
1680
+ @field_validator("language")
1681
+ @classmethod
1682
+ def language_must_be_supported(cls, value: str) -> str:
1683
+ if value not in LANGUAGES:
1684
+ raise ValueError(f"unknown language; available: {sorted(LANGUAGES)}")
1685
+ return value
1686
+
1687
+ @field_validator("style")
1688
+ @classmethod
1689
+ def style_must_be_registered(cls, value: Optional[str]) -> Optional[str]:
1690
+ if value is not None and value not in STYLES:
1691
+ raise ValueError(f"unknown style; available: {sorted(STYLES)}")
1692
+ return value
1693
+
1694
+ @field_validator("logo")
1695
+ @classmethod
1696
+ def logo_must_be_a_raster_image(
1697
+ cls, value: Optional[AssetUpload]
1698
+ ) -> Optional[AssetUpload]:
1699
+ # AssetUpload also accepts PDFs (they are reference documents elsewhere);
1700
+ # a crest has to be an image the renderer can actually draw.
1701
+ if value is not None and value.data_url.lower().startswith(
1702
+ "data:application/pdf"
1703
+ ):
1704
+ raise ValueError("校徽必須是 PNG 或 JPEG 圖片")
1705
+ return value
1706
+
1707
+ @field_validator("vision_backend")
1708
+ @classmethod
1709
+ def vision_backend_must_be_registered(cls, value: Optional[str]) -> Optional[str]:
1710
+ available = vision_source_names()
1711
+ if value is not None and value not in available:
1712
+ raise ValueError(f"unknown vision backend; available: {sorted(available)}")
1713
+ return value
1714
+
1715
+
1716
+ def vision_source_names() -> set[str]:
1717
+ """Every selectable vision source, read from the registry *now*.
1718
+
1719
+ A module-level snapshot would freeze at import and silently ignore a source
1720
+ registered afterwards — the exact staleness this whole change is undoing.
1721
+ "off" belongs here too: it is the source that always works, and the default.
1722
+ """
1723
+ return set(critic.VISION_BACKENDS) | {"off"}
1724
+
1725
+
1726
+ def _source_status(kind: str, name: str) -> Dict[str, Any]:
1727
+ """Whether a source can actually run right now, and why not if it cannot.
1728
+
1729
+ Availability is decided by *constructing* the backend and reporting what it
1730
+ complains about. Every factory already raises a specific, human message for
1731
+ a missing key, a missing CLI or a public bind, so there is no second list of
1732
+ preconditions to keep in step with the first.
1733
+ """
1734
+ if kind == "vision" and name == "off":
1735
+ return {"name": name, "available": True, "reason": ""}
1736
+ factory = (
1737
+ (lambda: llm.get_backend(name))
1738
+ if kind == "text"
1739
+ else (lambda: critic.get_vision_backend(name))
1740
+ )
1741
+ try:
1742
+ factory()
1743
+ except Exception as exc:
1744
+ return {"name": name, "available": False, "reason": _first_line(str(exc))}
1745
+ return {"name": name, "available": True, "reason": ""}
1746
+
1747
+
1748
+ def _first_line(message: str) -> str:
1749
+ """The headline of a multi-line factory error (the rest is shell examples).
1750
+
1751
+ The raw error's first line ends mid-sentence(「…請先設定後再執行,例如:」)
1752
+ because the shell examples live on the lines this cut drops — a dangling
1753
+ 「例如:」promising an example that never comes reads as a broken UI, so the
1754
+ suffix goes too.
1755
+ """
1756
+ if not message.strip():
1757
+ return ""
1758
+ line = message.strip().splitlines()[0].rstrip()
1759
+ for suffix in ("例如:", "例如:"):
1760
+ if line.endswith(suffix):
1761
+ line = line[: -len(suffix)].rstrip(",, ").rstrip()
1762
+ return line
1763
+
1764
+
1765
+ # An .otp/.odp is a zip; a few MiB is a generous ceiling for one, and the cap
1766
+ # is what stops a 200 MB "template" from being base64-inflated into memory.
1767
+ MAX_TEMPLATE_BYTES = 12 * 1024 * 1024
1768
+ _TEMPLATE_MIMES = (
1769
+ "application/vnd.oasis.opendocument.presentation",
1770
+ "application/vnd.oasis.opendocument.presentation-template",
1771
+ "application/vnd.oasis.opendocument.text",
1772
+ "application/vnd.oasis.opendocument.text-template",
1773
+ # Windows browsers commonly send .otp as one of these.
1774
+ "application/octet-stream",
1775
+ "application/zip",
1776
+ "application/x-zip-compressed",
1777
+ )
1778
+
1779
+
1780
+ def decode_template_upload(data_url: str) -> bytes:
1781
+ """Decode a base64 ``data:`` URI holding an ODF template file."""
1782
+ header, _, encoded = data_url.partition(",")
1783
+ lowered = header.lower()
1784
+ if not lowered.startswith("data:") or ";base64" not in lowered:
1785
+ raise ValueError("範本必須是 base64 data URI")
1786
+ if not any(f"data:{mime}" == lowered.split(";")[0] for mime in _TEMPLATE_MIMES):
1787
+ raise ValueError("請上傳 .otp / .odp / .ott / .odt 範本檔")
1788
+ try:
1789
+ blob = base64.b64decode(encoded, validate=True)
1790
+ except (binascii.Error, ValueError) as exc:
1791
+ raise ValueError("範本檔內容不是有效的 base64") from exc
1792
+ if not blob:
1793
+ raise ValueError("範本檔是空的")
1794
+ if len(blob) > MAX_TEMPLATE_BYTES:
1795
+ raise ValueError(
1796
+ f"範本檔超過 {MAX_TEMPLATE_BYTES // (1024 * 1024)} MiB 上限"
1797
+ )
1798
+ if not blob.startswith(b"PK"):
1799
+ raise ValueError("範本檔不是有效的 ODF(zip)檔案")
1800
+ return blob
1801
+
1802
+
1803
+ class TemplateBody(StrictBody):
1804
+ """Save (or overwrite) one user template."""
1805
+
1806
+ name: str = Field(min_length=1, max_length=MAX_NAME_CHARS)
1807
+ design: DesignSpec
1808
+ style: str = "classic"
1809
+ source: Literal["custom", "extracted"] = "custom"
1810
+ # Present = overwrite that template; absent = create a new one.
1811
+ id: Optional[str] = Field(default=None, max_length=64)
1812
+
1813
+
1814
+ class TemplateExtractBody(StrictBody):
1815
+ """An uploaded ODF template to sample a DesignSpec from."""
1816
+
1817
+ data_url: str = Field(min_length=1, max_length=17_000_000)
1818
+
1819
+
1820
+ class DiscoveryAsset(StrictBody):
1821
+ description: str = Field(min_length=1, max_length=240)
1822
+ credit: str = Field(default="", max_length=160)
1823
+ data_url: Optional[str] = Field(default=None, max_length=12_000_000)
1824
+
1825
+ @field_validator("data_url")
1826
+ @classmethod
1827
+ def data_url_must_be_pdf(cls, value: Optional[str]) -> Optional[str]:
1828
+ if value is not None and not is_pdf_data_uri(value):
1829
+ raise ValueError("discovery reference bytes must be a PDF data URI")
1830
+ return value
1831
+
1832
+
1833
+ class DiscoveryBody(StrictBody):
1834
+ """Preflight payload; PDF text is read while image bytes stay client-side."""
1835
+
1836
+ prompt: str = Field(min_length=1, max_length=8000)
1837
+ mode: Optional[Literal["presenter", "detailed"]] = None
1838
+ theme: Optional[str] = None
1839
+ language: str = "zh-TW"
1840
+ backend: Optional[Literal["codex", "ollama", "custom"]] = None
1841
+ doc_type: str = "odp"
1842
+ pages: Optional[int] = Field(default=None, ge=MIN_REQUESTED_PAGES, le=MAX_OUTLINE_PAGES)
1843
+ assets: List[DiscoveryAsset] = Field(default_factory=list, max_length=6)
1844
+
1845
+ @field_validator("theme")
1846
+ @classmethod
1847
+ def theme_must_be_a_preset(cls, value: Optional[str]) -> Optional[str]:
1848
+ if value is not None and value not in THEMES:
1849
+ raise ValueError(f"unknown theme; available: {sorted(THEMES)}")
1850
+ return value
1851
+
1852
+ @field_validator("language")
1853
+ @classmethod
1854
+ def language_must_be_supported(cls, value: str) -> str:
1855
+ if value not in LANGUAGES:
1856
+ raise ValueError(f"unknown language; available: {sorted(LANGUAGES)}")
1857
+ return value
1858
+
1859
+ @model_validator(mode="after")
1860
+ def assets_must_fit_the_batch_budget(self) -> DiscoveryBody:
1861
+ # Discovery takes the same payload shape and so had the same hole.
1862
+ _check_asset_budget(self.assets)
1863
+ return self
1864
+
1865
+ @field_validator("prompt")
1866
+ @classmethod
1867
+ def prompt_must_have_content(cls, value: str) -> str:
1868
+ value = value.strip()
1869
+ if not value:
1870
+ raise ValueError("prompt must not be blank")
1871
+ return value
1872
+
1873
+
1874
+ class OutlineActionBody(StrictBody):
1875
+ action: str
1876
+ outline: Optional[dict] = None
1877
+
1878
+
1879
+ class RegenerateBody(StrictBody):
1880
+ instruction: Optional[str] = Field(default=None, max_length=2000)
1881
+
1882
+
1883
+ # ---------------------------------------------------------------------------
1884
+ # App factory
1885
+ # ---------------------------------------------------------------------------
1886
+
1887
+
1888
+ def frontend_dist() -> Optional[Path]:
1889
+ """Where the built web cockpit lives, or ``None`` if this install has none.
1890
+
1891
+ Two locations, in priority order:
1892
+
1893
+ 1. ``odforge/webui`` **inside the installed package** — put there by the
1894
+ wheel's build hook (see ``hatch_build.py``) and found with
1895
+ ``importlib.resources``, so it works from site-packages and from a venv
1896
+ on another machine.
1897
+ 2. ``<repo>/web/dist`` — the developer's live ``npm run build`` output, so a
1898
+ git checkout still serves the cockpit without reinstalling after every
1899
+ frontend change.
1900
+
1901
+ The old implementation had only (2), computed by walking up from
1902
+ ``__file__``: correct in a checkout, wrong in every wheel, and the resulting
1903
+ API-only server looked exactly like a server whose frontend you forgot to
1904
+ build.
1905
+
1906
+ **Import from inside a zip is not supported**, and the previous code only
1907
+ appeared to support it. ``resources.as_file`` materialises a zipped resource
1908
+ into a temp directory and *deletes it when its context closes* — and the
1909
+ path was returned from inside the ``with``, so the zipped case handed
1910
+ ``StaticFiles`` a directory that no longer existed. On Python 3.11 it did
1911
+ not get that far: ``as_file`` could not handle a directory at all. Nothing
1912
+ caught either, because pip always unpacks a wheel, which makes ``as_file``
1913
+ a no-op on every install this project actually ships. A claim that is never
1914
+ exercised and does not work is worse than no claim, so it is gone: a zip
1915
+ import now degrades to API-only with a log line saying so.
1916
+ """
1917
+ try:
1918
+ packaged = resources.files("odforge") / "webui"
1919
+ if (packaged / "index.html").is_file():
1920
+ if isinstance(packaged, Path):
1921
+ return packaged
1922
+ logger.warning(
1923
+ "the web cockpit is packaged inside a non-filesystem loader "
1924
+ "(%r); serving API-only. Install the wheel normally — "
1925
+ "importing odforge from a zip is not supported.",
1926
+ type(packaged).__name__,
1927
+ )
1928
+ except (ModuleNotFoundError, FileNotFoundError, TypeError, OSError):
1929
+ pass
1930
+ source_tree = Path(__file__).resolve().parents[2] / "web" / "dist"
1931
+ return source_tree if (source_tree / "index.html").is_file() else None
1932
+
1933
+
1934
+ def _default_sessions_dir() -> Path:
1935
+ configured = os.environ.get("ODFORGE_SESSIONS_DIR", "").strip()
1936
+ if configured:
1937
+ return Path(configured).expanduser()
1938
+ local_app_data = os.environ.get("LOCALAPPDATA", "").strip()
1939
+ if local_app_data:
1940
+ return Path(local_app_data) / "ODForge" / "sessions"
1941
+ xdg_data = os.environ.get("XDG_DATA_HOME", "").strip()
1942
+ if xdg_data:
1943
+ return Path(xdg_data) / "odforge" / "sessions"
1944
+ return Path.home() / ".local" / "share" / "odforge" / "sessions"
1945
+
1946
+
1947
+ def create_app(jobs_dir: Optional[Path] = None, lifespan: Any = None) -> FastAPI:
1948
+ """Build the ODForge Web API application.
1949
+
1950
+ ``jobs_dir`` overrides where per-job artifacts live. By default sessions are
1951
+ stored under the user's local application-data directory; tests point it at
1952
+ a temporary path for isolation. ``lifespan`` is passed through to FastAPI —
1953
+ ``odforge preview`` uses it to run its file watcher for the server's lifetime.
1954
+ """
1955
+ app = FastAPI(title="ODForge Web API", version=__version__, lifespan=lifespan)
1956
+ # Explicit origin allowlist, credentials OFF. A local browser can still reach
1957
+ # 127.0.0.1, so binding to localhost is NOT a substitute — the origin check
1958
+ # is what stops a random visited site from driving this tool.
1959
+ app.add_middleware(
1960
+ CORSMiddleware,
1961
+ allow_origins=_cors_origins(),
1962
+ allow_credentials=False,
1963
+ allow_methods=["*"],
1964
+ allow_headers=["*"],
1965
+ )
1966
+
1967
+ app.state.active_regenerations = 0
1968
+ app.state.regeneration_counter_lock = asyncio.Lock()
1969
+ base = Path(jobs_dir) if jobs_dir is not None else _default_sessions_dir()
1970
+ base.mkdir(parents=True, exist_ok=True)
1971
+ app.state.jobs_dir = base
1972
+ app.state.jobs = _load_persisted_jobs(base)
1973
+ _prune_jobs(app)
1974
+
1975
+ def _get_job(job_id: str) -> Job:
1976
+ job = app.state.jobs.get(job_id)
1977
+ if job is None:
1978
+ raise HTTPException(status_code=404, detail="job not found")
1979
+ return job
1980
+
1981
+ def _discovery_context(body: DiscoveryBody) -> str:
1982
+ context: list[str] = []
1983
+ images: list[str] = []
1984
+ documents: list[ReferenceDocument] = []
1985
+ if body.mode:
1986
+ context.append(
1987
+ "講述型態:" + ("講者型" if body.mode == "presenter" else "自讀型")
1988
+ )
1989
+ if body.theme:
1990
+ context.append(f"視覺主題:{body.theme}")
1991
+ if body.language != "zh-TW":
1992
+ # The interview stays in zh-TW (that is the user's language); this
1993
+ # only tells the editor what the DECK will be written in, so it can
1994
+ # ask about terminology instead of asking which language to use.
1995
+ context.append(
1996
+ f"簡報輸出語言:{LANGUAGES[body.language]}"
1997
+ "(訪談問題仍以繁體中文提問)"
1998
+ )
1999
+ if body.pages is not None:
2000
+ context.append(f"目標頁數:{body.pages} 頁")
2001
+ for asset in body.assets:
2002
+ if asset.data_url:
2003
+ documents.append(
2004
+ decode_pdf_data_uri(
2005
+ asset.data_url,
2006
+ description=asset.description,
2007
+ credit=asset.credit,
2008
+ )
2009
+ )
2010
+ else:
2011
+ images.append(asset.description)
2012
+ if images:
2013
+ context.append(f"可用圖片素材:{'、'.join(images)}")
2014
+ document_context = format_reference_context(documents, max_chars=30_000)
2015
+ if document_context:
2016
+ context.append(document_context)
2017
+ return "\n".join(context)
2018
+
2019
+ def _validate_discovery_type(body: DiscoveryBody) -> None:
2020
+ if body.doc_type != "odp":
2021
+ raise HTTPException(
2022
+ status_code=422,
2023
+ detail="目前僅支援簡報(odp)的需求訪談。",
2024
+ )
2025
+
2026
+ @app.post("/api/discovery/questions", response_model=DiscoveryPlan)
2027
+ async def discovery_questions(body: DiscoveryBody) -> DiscoveryPlan:
2028
+ _validate_discovery_type(body)
2029
+ request_id = uuid.uuid4().hex[:10]
2030
+ started = time.perf_counter()
2031
+ logger.info(
2032
+ "discovery_start request_id=%s backend=%s prompt_chars=%d",
2033
+ request_id,
2034
+ body.backend or os.environ.get("ODFORGE_BACKEND", llm.DEFAULT_BACKEND),
2035
+ len(body.prompt),
2036
+ )
2037
+ try:
2038
+ context = await asyncio.to_thread(_discovery_context, body)
2039
+ plan = await asyncio.to_thread(
2040
+ generate_discovery_questions,
2041
+ body.prompt,
2042
+ body.backend,
2043
+ context=context,
2044
+ )
2045
+ except ReferenceError as exc:
2046
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
2047
+ except Exception as exc:
2048
+ logger.exception(
2049
+ "discovery_error request_id=%s elapsed_ms=%d",
2050
+ request_id,
2051
+ round((time.perf_counter() - started) * 1000),
2052
+ )
2053
+ raise HTTPException(
2054
+ status_code=502,
2055
+ detail=f"需求訪談生成失敗:{str(exc)[:500]}",
2056
+ ) from exc
2057
+ logger.info(
2058
+ "discovery_complete request_id=%s elapsed_ms=%d questions=%d",
2059
+ request_id,
2060
+ round((time.perf_counter() - started) * 1000),
2061
+ len(plan.questions),
2062
+ )
2063
+ return plan
2064
+
2065
+ @app.post("/api/discovery/questions/stream")
2066
+ async def discovery_questions_stream(
2067
+ body: DiscoveryBody,
2068
+ request: Request,
2069
+ ) -> StreamingResponse:
2070
+ """Stream operational progress while the structured model call runs.
2071
+
2072
+ Events deliberately expose lifecycle state and elapsed time, never the
2073
+ model's private chain-of-thought. Each frame is one UTF-8 NDJSON line.
2074
+ """
2075
+
2076
+ _validate_discovery_type(body)
2077
+ request_id = uuid.uuid4().hex[:10]
2078
+ try:
2079
+ context = await asyncio.to_thread(_discovery_context, body)
2080
+ except ReferenceError as exc:
2081
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
2082
+
2083
+ async def event_stream() -> AsyncIterator[str]:
2084
+ started = time.perf_counter()
2085
+ loop = asyncio.get_running_loop()
2086
+ progress_queue: asyncio.Queue[tuple[str, int]] = asyncio.Queue()
2087
+
2088
+ def elapsed_ms() -> int:
2089
+ return round((time.perf_counter() - started) * 1000)
2090
+
2091
+ def report(stage: str) -> None:
2092
+ loop.call_soon_threadsafe(
2093
+ progress_queue.put_nowait,
2094
+ (stage, elapsed_ms()),
2095
+ )
2096
+
2097
+ def line(event_type: str, data: dict[str, Any]) -> str:
2098
+ return (
2099
+ json.dumps(
2100
+ {"type": event_type, "data": data},
2101
+ ensure_ascii=False,
2102
+ separators=(",", ":"),
2103
+ )
2104
+ + "\n"
2105
+ )
2106
+
2107
+ def progress_data(stage: str, at_ms: int) -> dict[str, Any]:
2108
+ return {
2109
+ "request_id": request_id,
2110
+ "stage": stage,
2111
+ "message": _DISCOVERY_STAGE_MESSAGES.get(
2112
+ stage, "讀題工作持續進行中"
2113
+ ),
2114
+ "elapsed_ms": at_ms,
2115
+ }
2116
+
2117
+ logger.info(
2118
+ "discovery_start request_id=%s backend=%s prompt_chars=%d stream=true",
2119
+ request_id,
2120
+ body.backend or os.environ.get("ODFORGE_BACKEND", llm.DEFAULT_BACKEND),
2121
+ len(body.prompt),
2122
+ )
2123
+ yield line("progress", progress_data("accepted", 0))
2124
+
2125
+ task = asyncio.create_task(
2126
+ asyncio.to_thread(
2127
+ generate_discovery_questions,
2128
+ body.prompt,
2129
+ body.backend,
2130
+ context=context,
2131
+ progress=report,
2132
+ )
2133
+ )
2134
+ try:
2135
+ while not task.done():
2136
+ if await request.is_disconnected():
2137
+ logger.info(
2138
+ "discovery_disconnected request_id=%s elapsed_ms=%d",
2139
+ request_id,
2140
+ elapsed_ms(),
2141
+ )
2142
+ task.cancel()
2143
+ return
2144
+ queued = asyncio.create_task(progress_queue.get())
2145
+ done, _pending = await asyncio.wait(
2146
+ {task, queued},
2147
+ timeout=_DISCOVERY_HEARTBEAT_SECONDS,
2148
+ return_when=asyncio.FIRST_COMPLETED,
2149
+ )
2150
+ if queued in done:
2151
+ stage, at_ms = queued.result()
2152
+ logger.info(
2153
+ "discovery_progress request_id=%s stage=%s elapsed_ms=%d",
2154
+ request_id,
2155
+ stage,
2156
+ at_ms,
2157
+ )
2158
+ yield line("progress", progress_data(stage, at_ms))
2159
+ else:
2160
+ queued.cancel()
2161
+ with suppress(asyncio.CancelledError):
2162
+ await queued
2163
+
2164
+ if task in done:
2165
+ break
2166
+ if not done:
2167
+ at_ms = elapsed_ms()
2168
+ logger.info(
2169
+ "discovery_progress request_id=%s stage=waiting elapsed_ms=%d",
2170
+ request_id,
2171
+ at_ms,
2172
+ )
2173
+ yield line(
2174
+ "progress",
2175
+ progress_data("waiting", at_ms),
2176
+ )
2177
+
2178
+ while not progress_queue.empty():
2179
+ stage, at_ms = progress_queue.get_nowait()
2180
+ yield line("progress", progress_data(stage, at_ms))
2181
+
2182
+ plan = await task
2183
+ except asyncio.CancelledError:
2184
+ task.cancel()
2185
+ raise
2186
+ except Exception as exc:
2187
+ at_ms = elapsed_ms()
2188
+ logger.exception(
2189
+ "discovery_error request_id=%s elapsed_ms=%d stream=true",
2190
+ request_id,
2191
+ at_ms,
2192
+ )
2193
+ yield line(
2194
+ "error",
2195
+ {
2196
+ "request_id": request_id,
2197
+ "message": f"需求訪談生成失敗:{str(exc)[:500]}",
2198
+ "elapsed_ms": at_ms,
2199
+ },
2200
+ )
2201
+ return
2202
+
2203
+ at_ms = elapsed_ms()
2204
+ logger.info(
2205
+ "discovery_complete request_id=%s elapsed_ms=%d questions=%d stream=true",
2206
+ request_id,
2207
+ at_ms,
2208
+ len(plan.questions),
2209
+ )
2210
+ yield line(
2211
+ "result",
2212
+ {
2213
+ "request_id": request_id,
2214
+ "elapsed_ms": at_ms,
2215
+ "plan": plan.model_dump(mode="json"),
2216
+ },
2217
+ )
2218
+
2219
+ return StreamingResponse(
2220
+ event_stream(),
2221
+ media_type="application/x-ndjson",
2222
+ headers={
2223
+ "Cache-Control": "no-cache, no-transform",
2224
+ "X-Accel-Buffering": "no",
2225
+ },
2226
+ )
2227
+
2228
+ @app.post("/api/generate")
2229
+ async def generate(body: GenerateBody) -> Dict[str, str]:
2230
+ if body.doc_type != "odp":
2231
+ raise HTTPException(
2232
+ status_code=422,
2233
+ detail=(
2234
+ "Web 控制台只產生簡報(odp)。文件(odt)與試算表(ods)"
2235
+ "請用 CLI(odforge new -o out.odt)或 MCP 的 forge_* 工具——"
2236
+ "核心引擎三種格式都支援,是控制台的頁面模型只適用簡報"
2237
+ "(見 docs/gates.md 第五節)。"
2238
+ ),
2239
+ )
2240
+ _prune_jobs(app)
2241
+ # Count jobs whose WORKER is still alive, not jobs whose UI status looks
2242
+ # busy. Cancelling flips the status to "cancelled" at once, but the
2243
+ # provider call already in flight keeps running inside its thread: the old
2244
+ # count let a user press start/cancel five times and end up with five
2245
+ # concurrent paid API calls while the console showed nothing running.
2246
+ active_jobs = sum(_occupies_a_slot(job) for job in app.state.jobs.values())
2247
+ if active_jobs >= _MAX_ACTIVE_JOBS:
2248
+ raise HTTPException(
2249
+ status_code=429,
2250
+ detail=(
2251
+ f"同時進行的工作已達上限 {_MAX_ACTIVE_JOBS}"
2252
+ "(含已取消但外部呼叫尚未結束的工作),請稍候再試。"
2253
+ ),
2254
+ )
2255
+ try:
2256
+ job = create_job(
2257
+ app,
2258
+ prompt=body.prompt,
2259
+ mode=body.mode,
2260
+ theme=body.theme,
2261
+ interactive=body.interactive,
2262
+ qa=body.qa,
2263
+ vision_backend=body.vision_backend,
2264
+ backend=body.backend,
2265
+ pages=body.pages,
2266
+ uploads=body.assets,
2267
+ language=body.language,
2268
+ design=body.design,
2269
+ style=body.style,
2270
+ byline=body.byline,
2271
+ logo=body.logo,
2272
+ logo_placement=body.logo_placement,
2273
+ )
2274
+ except MediaError as exc:
2275
+ raise HTTPException(
2276
+ status_code=422, detail=f"invalid image asset: {exc}"
2277
+ ) from exc
2278
+ except ReferenceError as exc:
2279
+ raise HTTPException(
2280
+ status_code=422, detail=f"參考文件無法讀取:{exc}"
2281
+ ) from exc
2282
+ # Background task on the running loop; keep a ref so it isn't GC'd.
2283
+ job.task = asyncio.create_task(run_job(job))
2284
+ return {"job_id": job.id}
2285
+
2286
+ # ---- 範本庫 (deck templates) ------------------------------------------
2287
+ #
2288
+ # Built-ins and user templates are listed together but travel differently:
2289
+ # a built-in is applied as ``theme: <id>`` (a preset the renderer already
2290
+ # knows), a user template as a full ``design`` payload. The frontend does
2291
+ # not need to know that rule — each row says which it is.
2292
+
2293
+ def _templates_file() -> Path:
2294
+ return templates_path(app.state.jobs_dir)
2295
+
2296
+ @app.get("/api/templates")
2297
+ async def list_templates() -> Dict[str, Any]:
2298
+ return {
2299
+ "templates": [
2300
+ t.model_dump(mode="json") for t in all_templates(_templates_file())
2301
+ ],
2302
+ "languages": [
2303
+ {"id": code, "label": label} for code, label in LANGUAGES.items()
2304
+ ],
2305
+ # The style registry travels with the list so the gallery can offer
2306
+ # 版式 without keeping its own copy of the names and descriptions.
2307
+ "styles": [
2308
+ {"id": s.id, "label": s.label, "blurb": s.blurb}
2309
+ for s in STYLES.values()
2310
+ ],
2311
+ }
2312
+
2313
+ @app.post("/api/templates")
2314
+ async def create_template(body: TemplateBody) -> Dict[str, Any]:
2315
+ try:
2316
+ template = save_template(
2317
+ _templates_file(),
2318
+ name=body.name,
2319
+ design=body.design,
2320
+ style=body.style,
2321
+ source=body.source,
2322
+ template_id=body.id,
2323
+ )
2324
+ except ValueError as exc:
2325
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
2326
+ return template.model_dump(mode="json")
2327
+
2328
+ @app.delete("/api/templates/{template_id}")
2329
+ async def remove_template(template_id: str) -> Dict[str, Any]:
2330
+ try:
2331
+ removed = delete_template(_templates_file(), template_id)
2332
+ except ValueError as exc:
2333
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
2334
+ if not removed:
2335
+ raise HTTPException(status_code=404, detail="找不到這個範本")
2336
+ return {"ok": True}
2337
+
2338
+ @app.post("/api/templates/extract")
2339
+ async def extract_template(body: TemplateExtractBody) -> Dict[str, Any]:
2340
+ """Sample an existing ODF template's look into an editable DesignSpec.
2341
+
2342
+ Nothing is saved here — the caller previews the extracted palette and
2343
+ then POSTs it back under a name. That split is deliberate: a template
2344
+ whose colours came out wrong should never silently join the library.
2345
+ """
2346
+ try:
2347
+ blob = decode_template_upload(body.data_url)
2348
+ except ValueError as exc:
2349
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
2350
+ with tempfile.TemporaryDirectory() as tmp:
2351
+ path = Path(tmp) / "template.odp"
2352
+ path.write_bytes(blob)
2353
+ try:
2354
+ design = await asyncio.to_thread(extract_design, path)
2355
+ except TemplateExtractionError as exc:
2356
+ raise HTTPException(
2357
+ status_code=422, detail=f"無法讀取這個範本檔:{exc}"
2358
+ ) from exc
2359
+ return {"design": design.model_dump(mode="json")}
2360
+
2361
+ @app.get("/api/sessions")
2362
+ async def list_sessions() -> Dict[str, Any]:
2363
+ _prune_jobs(app)
2364
+ sessions = sorted(
2365
+ (_session_summary(job) for job in app.state.jobs.values()),
2366
+ key=lambda item: item["updated_at"],
2367
+ reverse=True,
2368
+ )
2369
+ return {"sessions": sessions}
2370
+
2371
+ @app.delete("/api/sessions/{job_id}")
2372
+ async def delete_session(job_id: str) -> Dict[str, Any]:
2373
+ """Delete one session: drop it from memory and remove its artifacts.
2374
+
2375
+ Refused while anything about the job is still moving. ``_occupies_a_slot``
2376
+ is the honest test — not ``status``, which says "cancelled" the instant
2377
+ the user clicks while the provider call keeps running in its thread. The
2378
+ regeneration lock is the second half: that work runs inside the HTTP
2379
+ request, not ``job.task``, so between two offloads the job can look idle
2380
+ while a new deck is halfway written. Pulling the directory out from under
2381
+ either one leaves a worker writing into deleted paths (and re-creating
2382
+ the directory as it goes).
2383
+ """
2384
+ job = _get_job(job_id)
2385
+ if _occupies_a_slot(job) or job.mutation_lock.locked():
2386
+ raise HTTPException(
2387
+ status_code=409,
2388
+ detail=(
2389
+ "這份工作還在進行(或已取消但外部呼叫尚未結束),"
2390
+ "請等它停下來再刪除。"
2391
+ ),
2392
+ )
2393
+ # Out of the registry first, then off the disk: a concurrent request must
2394
+ # not be able to find a job whose files are already going away.
2395
+ app.state.jobs.pop(job_id, None)
2396
+ await asyncio.to_thread(shutil.rmtree, job.dir, ignore_errors=True)
2397
+ logger.info("session_deleted job_id=%s", job_id)
2398
+ return {"ok": True}
2399
+
2400
+ @app.get("/api/sources")
2401
+ async def sources() -> Dict[str, Any]:
2402
+ """Which model sources exist, which can run, and which are in force.
2403
+
2404
+ Derived from the registries, so the frontend never carries its own copy
2405
+ of the list and a newly registered backend is selectable immediately.
2406
+ """
2407
+ return {
2408
+ "text": [_source_status("text", n) for n in sorted(llm.BACKENDS)],
2409
+ "vision": [
2410
+ _source_status("vision", n) for n in sorted(vision_source_names())
2411
+ ],
2412
+ "defaults": {
2413
+ "text": os.environ.get("ODFORGE_BACKEND", llm.DEFAULT_BACKEND),
2414
+ "vision": os.environ.get("ODFORGE_VISION_BACKEND", "off"),
2415
+ },
2416
+ }
2417
+
2418
+ @app.get("/api/jobs/{job_id}/events")
2419
+ async def events(job_id: str, request: Request) -> EventSourceResponse:
2420
+ job = _get_job(job_id)
2421
+
2422
+ async def event_stream():
2423
+ cursor = 0
2424
+ epoch = job.event_epoch
2425
+ while True:
2426
+ # Replay/emit everything appended since our cursor. The stream
2427
+ # closes on a terminal event — but only on the *last* one. A
2428
+ # successful regeneration appends a fresh page, gates and its own
2429
+ # ``complete`` after the original, so a reconnecting client that
2430
+ # stopped at the first terminal event restored the deck as it
2431
+ # looked several versions ago while the download served the
2432
+ # newest. "Terminal" has to mean "nothing came after it".
2433
+ while True:
2434
+ if job.event_epoch != epoch:
2435
+ # A live-preview reload replaced the log: replay the new one.
2436
+ epoch, cursor = job.event_epoch, 0
2437
+ if cursor >= len(job.events):
2438
+ break
2439
+ ev = job.events[cursor]
2440
+ cursor += 1
2441
+ yield {
2442
+ "event": ev["event"],
2443
+ "data": json.dumps(ev["data"], ensure_ascii=False),
2444
+ }
2445
+ if (
2446
+ ev["event"] in ("complete", "error")
2447
+ and cursor >= len(job.events)
2448
+ and job.status in _TERMINAL_JOB_STATUSES
2449
+ and not job.watching
2450
+ ):
2451
+ return
2452
+ if await request.is_disconnected():
2453
+ return
2454
+ # Wait for the next emit; the timeout bounds liveness (and makes
2455
+ # a missed wakeup at worst a sub-second delay, never a lost event
2456
+ # since the loop re-reads len(job.events) each pass).
2457
+ job.updated.clear()
2458
+ try:
2459
+ await asyncio.wait_for(job.updated.wait(), timeout=_SSE_POLL_SECONDS)
2460
+ except TimeoutError:
2461
+ pass
2462
+
2463
+ return EventSourceResponse(event_stream())
2464
+
2465
+ @app.post("/api/jobs/{job_id}/outline")
2466
+ async def outline_action(job_id: str, body: OutlineActionBody) -> Dict[str, Any]:
2467
+ job = _get_job(job_id)
2468
+ if job.status != "awaiting_approval":
2469
+ raise HTTPException(
2470
+ status_code=409, detail="job is not awaiting outline approval"
2471
+ )
2472
+ if body.action == "edit":
2473
+ if body.outline is None:
2474
+ raise HTTPException(
2475
+ status_code=422, detail="action 'edit' requires an outline"
2476
+ )
2477
+ try:
2478
+ edited = Outline.model_validate(body.outline)
2479
+ edited = edited.model_copy(
2480
+ update={
2481
+ "source_prompt": edited.source_prompt or job.prompt,
2482
+ "media_assets": job.asset_refs,
2483
+ "image_generation_available": (
2484
+ job.outline.image_generation_available
2485
+ if job.outline is not None
2486
+ else False
2487
+ ),
2488
+ }
2489
+ )
2490
+ job.outline = edited
2491
+ except ValidationError as exc:
2492
+ raise HTTPException(status_code=422, detail=f"invalid outline: {exc}") from None
2493
+ # Record the edited outline in the event log so a ?job= resume replays
2494
+ # the *edited* outline, not the original. Without this, a reconnecting
2495
+ # subscriber rebuilds from the stale first outline; after `complete`
2496
+ # every cell is painted done, resurrecting the removed pages as phantom
2497
+ # "done" thumbnails absent from the downloaded deck. Live subscribers
2498
+ # receive a second `outline` event, equivalent (and idempotent) to the
2499
+ # front-end's synthetic re-sync dispatch.
2500
+ await _emit(job, "outline", job.outline.model_dump(mode="json"))
2501
+ elif body.action != "approve":
2502
+ raise HTTPException(
2503
+ status_code=422, detail="action must be 'approve' or 'edit'"
2504
+ )
2505
+ job.approval.set()
2506
+ return {"ok": True, "status": job.status}
2507
+
2508
+ # units/{n}/regenerate 為 F4 正名別名;slides/{n}/regenerate 保留向前相容,同一 handler。
2509
+ @app.post("/api/jobs/{job_id}/units/{n}/regenerate")
2510
+ @app.post("/api/jobs/{job_id}/slides/{n}/regenerate")
2511
+ async def regenerate(job_id: str, n: int, body: RegenerateBody) -> Dict[str, Any]:
2512
+ job = _get_job(job_id)
2513
+ if job.status != "complete" or job.ir is None or job.outline is None:
2514
+ raise HTTPException(
2515
+ status_code=409, detail="job is not ready for regeneration"
2516
+ )
2517
+ if not 1 <= n <= len(job.ir.slides):
2518
+ raise HTTPException(status_code=404, detail="slide index out of range")
2519
+ async with _regeneration_slot(app, job):
2520
+ # While a candidate is being built the artifact on disk is mid-swap,
2521
+ # so the download endpoint must refuse it. ``complete`` is restored
2522
+ # either way — the rollback path leaves a perfectly good deck.
2523
+ job.status = "regenerating"
2524
+ try:
2525
+ result = await regenerate_slide(job, n, body.instruction)
2526
+ except Exception as exc:
2527
+ # Clean, structured error (the run_job error shape) instead of a bare
2528
+ # 500 traceback. The rollback already restored everything, so the
2529
+ # job goes back to being complete and downloadable.
2530
+ job.status = "complete"
2531
+ _persist_job(job)
2532
+ raise HTTPException(
2533
+ status_code=500,
2534
+ detail={"message": str(exc), "stage": "regenerate"},
2535
+ ) from exc
2536
+ job.status = "complete"
2537
+ _persist_job(job)
2538
+ return {"ok": True, **result}
2539
+
2540
+ @app.post("/api/jobs/{job_id}/cancel")
2541
+ async def cancel_job(job_id: str) -> Dict[str, Any]:
2542
+ job = _get_job(job_id)
2543
+ if job.status in _TERMINAL_JOB_STATUSES:
2544
+ raise HTTPException(status_code=409, detail="job is already terminal")
2545
+ job.status = "cancelled"
2546
+ job.finished_at = time.time()
2547
+ job.approval.set()
2548
+ if job.task is not None and not job.task.done():
2549
+ job.task.cancel()
2550
+ await _emit(job, "error", {"message": "工作已取消", "stage": "cancel"})
2551
+ return {"ok": True, "status": job.status}
2552
+
2553
+ @app.get("/api/jobs/{job_id}/preview/{n}.png")
2554
+ async def preview(job_id: str, n: int) -> FileResponse:
2555
+ job = _get_job(job_id)
2556
+ total = len(job.ir.slides) if job.ir is not None else 0
2557
+ if not 1 <= n <= total:
2558
+ raise HTTPException(status_code=404, detail="preview page out of range")
2559
+ # Server-owned path only: fixed name inside the job's own published
2560
+ # preview version — a page beyond the current deck cannot resolve.
2561
+ path = _preview_file(job, n)
2562
+ if path is None:
2563
+ raise HTTPException(status_code=404, detail="preview not available")
2564
+ return FileResponse(path, media_type="image/png")
2565
+
2566
+ @app.get("/api/jobs/{job_id}/download")
2567
+ async def download(job_id: str) -> FileResponse:
2568
+ """Serve the deck only when the gates approved *this* version of it.
2569
+
2570
+ The presence of ``deck.odp`` proves nothing: a job that is still
2571
+ generating, that failed validation, that was cancelled, or whose
2572
+ regeneration rolled back all leave a file at that path. Handing it over
2573
+ would ship an artifact under quality claims it never earned, so anything
2574
+ short of "finished and validated at the current version" is a 409 with a
2575
+ message saying which of those it is.
2576
+ """
2577
+ job = _get_job(job_id)
2578
+ if job.downloadable:
2579
+ return FileResponse(
2580
+ job.odp_path, media_type=ODP_MIME, filename=_download_filename(job)
2581
+ )
2582
+ raise HTTPException(status_code=409, detail=_undownloadable_reason(job))
2583
+
2584
+ @app.get("/api/jobs/{job_id}")
2585
+ async def snapshot(job_id: str) -> Dict[str, Any]:
2586
+ job = _get_job(job_id)
2587
+ data: Dict[str, Any] = {
2588
+ "status": job.status,
2589
+ "slides_done": job.slides_done,
2590
+ "outline": job.outline.model_dump(mode="json") if job.outline else None,
2591
+ "gates": dict(job.gates),
2592
+ "artifact_version": job.artifact_version,
2593
+ "downloadable": job.downloadable,
2594
+ }
2595
+ if job.dropped_content:
2596
+ data["dropped_content"] = [
2597
+ d.model_dump(mode="json") for d in job.dropped_content
2598
+ ]
2599
+ if job.qa_report is not None and job.qa_report.findings_by_round:
2600
+ last = job.qa_report.findings_by_round[-1]
2601
+ data["findings"] = [f.model_dump(mode="json") for f in last]
2602
+ # Only advertise the link when it will actually serve; a snapshot that
2603
+ # promises a download the endpoint then 409s is the same lie one layer up.
2604
+ if job.downloadable:
2605
+ data["download_url"] = _download_url(job)
2606
+ if job.error is not None:
2607
+ data["error"] = job.error
2608
+ return data
2609
+
2610
+ # Host the built frontend at "/" so one `odforge serve` runs the whole cockpit.
2611
+ # Mounted last, after the /api routes, so those still take precedence; skipped
2612
+ # entirely when the frontend hasn't been built (API-only mode).
2613
+ dist = frontend_dist()
2614
+ if dist is not None:
2615
+ app.mount("/", StaticFiles(directory=dist, html=True), name="frontend")
2616
+
2617
+ return app