比较提交
17 提交
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
| ad6e21de88 | |||
| 70821748bc | |||
| 0abc656000 | |||
| 26960a98f5 | |||
| 8f9c543918 | |||
| b57ce466fe | |||
| 0feb76f214 | |||
| a5ff567272 | |||
| 7ad6f3e36a | |||
| 75286e1c54 | |||
| f2366c4361 | |||
| 91220b9059 | |||
| 3415232b4e | |||
| a828f0246b | |||
| 9ce3d3eefe | |||
| 044f2b7822 | |||
| 937ee730ce |
共有 129 个文件被更改,包括 22940 次插入 和 465 次删除
1
.gitignore
Vendored
1
.gitignore
Vendored
|
|
@ -3,6 +3,7 @@ __pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.pytest_tmp*/
|
.pytest_tmp*/
|
||||||
|
.tmp_pytest*/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
.mypy_cache/
|
.mypy_cache/
|
||||||
.venv/
|
.venv/
|
||||||
|
|
|
||||||
386
CHANGELOG.md
386
CHANGELOG.md
|
|
@ -1,103 +1,371 @@
|
||||||
|
## 1.0.66
|
||||||
|
|
||||||
|
- Complete P0-P2 style-profile hardening: decouple age and anatomy evidence, enforce review consistency caps, gate core traits by cross-context evidence, re-audit semantic rewrites, deduplicate scale capsules, use neutral validation scenes, add layered rendering review, improve score trust display, and block automatic adoption of regressed candidates.
|
||||||
|
|
||||||
|
## 1.0.65
|
||||||
|
|
||||||
|
- Improve style transfer with adaptive face and eye proportions, opaque pearlescent hair-highlight constraints, high-frequency representative-image guidance, and representative reference validation enabled by default with safe pure-text fallback.
|
||||||
|
|
||||||
|
## 1.0.64
|
||||||
|
|
||||||
|
- Preserve high-specificity artist signatures with an evidence-gated style kernel, scale-specific prompt adapters, and background-effect isolation for portrait, full-body, and novel-scene validation.
|
||||||
|
|
||||||
|
## 1.0.63
|
||||||
|
|
||||||
|
- Compact the final style prompt into an evidence-backed style kernel, preserve palette/highlights/shading traits after paraphrase, remove literal background effects without evidence, and neutralize age/body template locks.
|
||||||
|
|
||||||
|
## 1.0.62
|
||||||
|
|
||||||
|
- Soften facial-age and head-to-body style cues so user-requested age, gender presentation, body maturity and proportions remain authoritative; reduce childlike or adult template locking during style transfer.
|
||||||
|
|
||||||
|
## 1.0.61
|
||||||
|
|
||||||
|
- Add a selectable advanced-style consensus strategy: pure-text structured consensus by default, with opt-in vision-assisted consensus for cases that benefit from direct image review.
|
||||||
|
|
||||||
|
## 1.0.60
|
||||||
|
|
||||||
|
- Use pure-text structured cross-image consensus from per-image recognition reports, avoiding multi-image Vision relay timeouts while preserving the existing normalization and validation workflow.
|
||||||
|
|
||||||
|
## 1.0.59
|
||||||
|
|
||||||
|
- Reduce grouped consensus vision calls to one representative image plus structured reports to avoid relay multi-image stalls.
|
||||||
|
|
||||||
|
## 1.0.58
|
||||||
|
|
||||||
|
- Split large style consensus requests into grouped multi-image analysis plus a compact final merge to reduce provider timeouts.
|
||||||
|
|
||||||
|
## 1.0.57
|
||||||
|
|
||||||
|
- Make the persisted plugin-data selection authoritative for the dedicated cross-analysis route.
|
||||||
|
|
||||||
|
## 1.0.56
|
||||||
|
|
||||||
|
- Ensure the dedicated consensus route overrides stale task snapshots and survives blank AstrBot runtime defaults.
|
||||||
|
|
||||||
|
## 1.0.55
|
||||||
|
|
||||||
|
- Fix AstrBot runtime-config bridging for the independent `advanced_style_consensus` route so the selected model is actually used.
|
||||||
|
|
||||||
|
## 1.0.54
|
||||||
|
|
||||||
|
- Add an independent `advanced_style_consensus` vision route for multi-image style cross-analysis; blank keeps the recognition-route fallback.
|
||||||
|
- Isolate large cross-image vision requests from the single-image recognition route.
|
||||||
|
|
||||||
|
## 1.0.53
|
||||||
|
|
||||||
|
- Limit concurrent advanced-material vision requests per route to avoid GPT-5.6 relay timeouts when eight images fan out at once.
|
||||||
|
- Add `advanced_materials.recognition_concurrency`, defaulting to `2`.
|
||||||
|
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
本项目从 1.0.8 起使用该文件记录可验收的小版本。开发中的版本仅代表代码里程碑;完成全部二次审计队列后再统一部署。
|
鏈」鐩粠 1.0.8 璧蜂娇鐢ㄨ鏂囦欢璁板綍鍙獙鏀剁殑灏忕増鏈€傚紑鍙戜腑鐨勭増鏈粎浠h〃浠g爜閲岀▼纰戯紱瀹屾垚鍏ㄩ儴浜屾瀹¤闃熷垪鍚庡啀缁熶竴閮ㄧ讲銆?
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
- 已完成全仓角色工作流二次审计;确认在现有 `character_gradual` 主线上增量修复,不创建平行工作流。
|
## [1.0.52] - 2026-07-20
|
||||||
- 修复队列已按 1.0.9–1.0.20 小版本写入 `docs/workflow-secondary-audit-development-queue.md`。
|
|
||||||
|
- Remove source prompt, artist-name and tag anchoring from multi-image style consensus input.
|
||||||
|
- Keep only cross-source-supported signature traits, reject low-support multi-dimension summaries, and reduce final style prompt duplication.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.51] - 2026-07-20
|
||||||
|
|
||||||
|
- Improve artist-style extraction with dimension-balanced signature traits across face structure, eyes, hair, linework, shading, palette, highlights, texture and anatomy.
|
||||||
|
- Weight signatures by cross-source support and specificity, reuse structured source attributes, and mark signatures explicitly in the final generation prompt to reduce generic-anime style collapse.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.50] - 2026-07-20
|
||||||
|
|
||||||
|
- 增加画师风格签名特征聚合,优先保留跨源可验证的高辨识度线稿、眼睛、发丝高光、配色和阴影结构,减少多图共识被压平为通用动漫风格。
|
||||||
|
- 过滤通用标签并保留签名特征进入最终 portrait/fullbody/novel_scene 生成提示词。
|
||||||
|
|
||||||
|
## [1.0.49] - 2026-07-20
|
||||||
|
|
||||||
|
- 修复已封存的 accepted 流仍显示在最近导入和验证工作台的问题。
|
||||||
|
- 验证工作台默认折叠,支持点击展开和收起。
|
||||||
|
|
||||||
|
## [1.0.48] - 2026-07-20
|
||||||
|
|
||||||
|
- 封存验证流后,工作台自动隐藏已封存记录并切换到下一条未封存流,避免封存项目继续显示在最近导入区域。
|
||||||
|
|
||||||
|
## [1.0.47] - 2026-07-20
|
||||||
|
|
||||||
|
- 加强 portrait 验证的脸宽高比、颧部、下颌和下巴轮廓约束,减少头像生成时脸型偏移,同时不改变 fullbody/novel_scene 规则。
|
||||||
|
|
||||||
|
## [1.0.46] - 2026-07-20
|
||||||
|
|
||||||
|
- 参考图改为默认关闭,先进阶画风验证默认使用纯文本生成;仍可由用户显式开启参考图。
|
||||||
|
|
||||||
|
## [1.0.45] - 2026-07-20
|
||||||
|
|
||||||
|
- 参考图生成遇到中转站 400/422/5xx 兼容性错误时,自动回退为纯文本生成;429、鉴权失败和网络超时不盲目重试。
|
||||||
|
- 保留参考图首选路径,兼容不支持 image 字段的 OpenAI-compatible 网关。
|
||||||
|
|
||||||
|
## [1.0.44] - 2026-07-20
|
||||||
|
|
||||||
|
- 加固 advanced-style 验证提示词,移除 juvenile、toddler 及明确二至四头身措辞,保留 neotenic 画风结构与全身比例约束,降低中转站风控误判概率。
|
||||||
|
- 保存图像供应商失败的 HTTP 状态码、路由和安全响应摘要,便于区分 502、429、内容审核和超时。
|
||||||
|
|
||||||
|
## [1.0.43] - 2026-07-20
|
||||||
|
|
||||||
|
- 修复 advanced-style 重试后旧失败记录未标记为已替代的问题,补齐 superseded 时间戳写回。
|
||||||
|
- 批量重试按 source/case lineage 去重,只重试每条逻辑任务的最新失败记录,并归并历史失败记录。
|
||||||
|
|
||||||
|
## [1.0.42] - 2026-07-20
|
||||||
|
|
||||||
|
- 直接重试失败的 advanced-material 子任务后,旧失败记录标记为“已被重试替代”,不再继续占用“需处理”列表。
|
||||||
|
- 新增“jobs/failed/retry”批量接口与队列页“一键重试全部失败任务”,逐条失败也会继续处理并返回错误明细。
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.41] - 2026-07-20
|
||||||
|
|
||||||
|
- Normalize advanced-material queue retry responses to return the replacement task shape expected by the queue page.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.40] - 2026-07-20
|
||||||
|
|
||||||
|
- Queue-page retry now dispatches advanced style source and validation tasks to their direct retry handlers instead of retrying the whole import.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.39] - 2026-07-20
|
||||||
|
|
||||||
|
- Fix style validation when the configured image gateway rejects the optional reference-image field with a generic 4xx HTTP error.
|
||||||
|
- Retry the same validation request without `input_images`, preserving the new reference-image feature for compatible providers while keeping current NAS routes usable.
|
||||||
|
|
||||||
|
## [1.0.38] - 2026-07-20
|
||||||
|
|
||||||
|
- First-round style validation can attach one optional source image as a style-only reference (shared by portrait/fullbody/novel_scene).
|
||||||
|
- Default uses representative/primary source; UI can pick any recognized sample or disable reference for pure-text transfer.
|
||||||
|
- Prompt + negatives forbid identity/costume/pose/scene copy from the reference; providers that reject input images fall back to pure text with metadata flags.
|
||||||
|
- Soft anatomy band from 1.0.37 and age-band ownership by content prompt remain unchanged.
|
||||||
|
|
||||||
|
## [1.0.37] - 2026-07-20
|
||||||
|
|
||||||
|
- Full-body style transfer adds a soft anatomy band (about 5-7 heads tall, prefer observed source ratio) to prevent chibi/super-deformed collapse after removing mature-adult locks.
|
||||||
|
- Keep facial neoteny transferable; do not restore mature adult-woman identity locks. Negative prompt blocks 2-4 heads tall bodies on fullbody validation.
|
||||||
|
|
||||||
|
## [1.0.36] - 2026-07-20
|
||||||
|
|
||||||
|
- 鐢婚杩佺Щ鍙栨秷鈥滄垚鐔熸垚骞?/ 6.5鈥?.5 澶磋韩鈥濈‖閿侊細榛樿楠岃瘉涓讳綋涓嶅啀寮哄埗 mature adult body锛涘叏韬繚鐣欐簮鍥?head-to-body 涓庤偄浣撴娊璞°€?
|
||||||
|
- facial_age_stylization銆佹簮鍥句綋鍨嬫瘮渚嬩綔涓哄彲杩佺Щ缁撴瀯椋庢牸淇濈暀锛涘疄闄?鏃跺簭骞撮緞浠呬綔鍙傝€冿紝涓嶅啓鍏ョ敓鍥?prompt銆?
|
||||||
|
- 楠岃瘉 content prompt 鐨勫勾榫勫甫锛堝皯濂?鎴愬コ绛夛級鐢辩敤鎴锋寚浠ゆ垨鍐呭鎻愮ず鎺у埗锛涙湭鎸囧畾鏃朵繚鎸佷腑鎬у苟璁╂簮鍥鹃鏍煎崰涓汇€?
|
||||||
|
|
||||||
|
## [1.0.35] - 2026-07-20
|
||||||
|
|
||||||
|
- 鍔犲浐闃熷垪 QueueWorker 澶辫触璺緞锛氫笟鍔″け璐ユ垨浜屾鍐欏簱寮傚父涓嶅啀鏉€姝?worker 绾跨▼锛岄伩鍏?advanced-material 浠诲姟姘镐箙鍗″湪 queued銆?
|
||||||
|
- worker 寰幆瀵?run_once 澧炲姞澶栧眰鍏滃簳锛泂tart 鍙湪绾跨▼鎰忓閫€鍑哄悗閲嶆柊鎷夎捣锛汚piError 閿欒娑堟伅浼樺厛灞曠ず message 涓?error_code銆?
|
||||||
|
- 瑙嗚璇嗗埆 prohibited_content 绛変笟鍔″け璐ヤ粛璁颁负 failed锛屼絾闃熷垪涓庡悗缁换鍔″彲缁х画 claim 涓庢墽琛屻€?
|
||||||
|
|
||||||
|
## [1.0.34] - 2026-07-19
|
||||||
|
|
||||||
|
- 杩涢樁鐢婚 portrait銆乫ullbody銆乶ovel_scene 涓夎矾杩佺Щ楠岃瘉浣跨敤鐙珛 900 绉掔敓鍥捐秴鏃讹紝骞跺皢鍚屼竴鏁板€兼寔涔呭寲鍒伴槦鍒楄姹傘€佷换鍔″厓鏁版嵁鍜屽疄闄?Provider 璇锋眰锛涙櫘閫氬揩閫熺敓鍥剧户缁娇鐢ㄩ€傞厤鍣ㄨ嚜韬殑榛樿瓒呮椂銆?
|
||||||
|
- 鐢熷浘 Provider 鏀寔鍗曟璇锋眰瑕嗙洊瓒呮椂锛岃寖鍥撮檺鍒朵负 10锝?600 绉掞紱閬垮厤涓轰簡鎱㈤€熼獙璇佹ā鍨嬭€岃杩彁楂樻墍鏈夌敓鍥句换鍔$殑鍏ㄥ眬绛夊緟鏃堕棿銆?
|
||||||
|
- AstrBot 鎻掍欢妗ュ拰鍐呭祵椤甸潰鐨勯暱浠诲姟绛夊緟缁熶竴涓?900 绉掞紝浠诲姟鍗$洿鎺ユ樉绀哄悗绔褰曠殑鑰楁椂涓婇檺锛屼笉鍐嶅嚭鐜板墠绔厛鎶ヨ秴鏃躲€佸悗绔粛鍦ㄨ繍琛岀殑鍐茬獊鎻愮ず銆?
|
||||||
|
- 淇 SQLite 鏃犳椂鍖?UTC 鏃堕棿琚祻瑙堝櫒褰撴垚鏈湴鏃堕棿瑙f瀽鐨勯棶棰橈紱澶辫触銆佸畬鎴愬拰鍙栨秷浠诲姟鐨勮€楁椂鍥哄畾浣跨敤 `updated_at - created_at`锛屼笉鍐嶆樉绀洪敊璇殑 8 灏忔椂鎴栭殢椤甸潰鍋滅暀鎸佺画澧為暱銆?
|
||||||
|
|
||||||
|
## [1.0.33] - 2026-07-19
|
||||||
|
|
||||||
|
- 灏嗚劯閮ㄥ勾榫勯鏍笺€佸疄闄呭勾榫勪笌韬綋鎴愮啛搴︽媶鍒嗗鐞嗭紱鐢婚姝e悜鎻愮ず璇嶄笉鍐嶇户鎵挎湭鎴愬勾銆侀潚灏戝勾鎴栧辜鎬佽韩浣撴帾杈烇紝涓夌粍楠岃瘉涓讳綋缁熶竴涓烘槑纭垚骞翠汉锛屽叏韬獙璇佸浐瀹氭垚鐔熻偄浣撻暱搴︿笌绾?6.5锝?.5 澶磋韩姣斾緥銆?
|
||||||
|
- 鐢婚鏍稿績椤广€佸繀椤讳繚鐣欓」鍙婅儗鏅€佸叿浣撳厜鏁堛€佸叿浣撹壊鐩樼瓑鏄撴薄鏌撳唴瀹瑰鍔犺瘉鎹棬鎺э紱浠呭綋澶氬浘鏀寔鐜囦笉浣庝簬 60%銆佺疆淇″害涓嶄綆浜?70% 鏃惰繘鍏ユ渶缁堟彁绀鸿瘝銆?
|
||||||
|
- 鑷姩杩樺師搴﹁瘎鍒嗗鍔犱竴鑷存€ф牎鍑嗭細鏈€缁堝垎涓嶉珮浜庢ā鍨嬭嚜璇勫垎锛屽亸宸€佷慨姝hˉ涓併€佽涔夐闄╁拰鏂囧瓧涓ラ噸搴︿細鎵e垎锛涒€滅淮搴﹀叏婊″垎浣嗗悓鏃惰姹備慨姝b€濅細鏍囪涓哄鏍哥粨鏋滀笉涓€鑷淬€?
|
||||||
|
- 瀵规ā鍨嬬粰鍑虹殑瀹夊叏鏀瑰啓鍐嶅仛涓€娆¤涔夊舰鐘跺璁★紱鍙戜笣楂樺厜涓殑鍏夌幆銆佹í甯︺€佹潯鍧楃瓑鐗╀綋鍖栨帾杈炴敼鍐欎负璐村悎鍙戜笣鏇查潰鐨勫崐閫忔槑鏂画缂庨潰鍏夋辰锛屽苟鍔犲叆鐧借壊瀹炵嚎銆佽繛缁厜甯︺€佸嚑浣曟姌绾垮潡绛夎礋鍚戠害鏉熴€?
|
||||||
|
- 鍏叡 detailed 鐢婚鑳跺泭涓?portrait/fullbody/novel_scene 灏哄害鑳跺泭鍦ㄦ湇鍔$鍘婚噸锛屽昂搴﹁兌鍥婂彧淇濈暀璇ユ瀯鍥惧昂搴︾嫭鏈夌殑绾︽潫锛屽噺灏戦暱鎻愮ず璇嶇殑閲嶅娉ㄦ剰鍔涘崰鐢ㄣ€?
|
||||||
|
- 榛樿涓庢ā鍨嬭繑鍥炵殑楠岃瘉鍐呭缁熶竴缁忚繃涓€у寲锛氬ご鍍忎娇鐢ㄥ搼鍏夋鎷嶏紝鍏ㄨ韩浣跨敤涓€ф棩鍏夛紝璺ㄥ満鏅娇鐢ㄦ櫘閫氶槾澶╋紝绉婚櫎榛庢槑銆佹棩钀姐€侀湏铏广€佹暎鏅€侀暅澶村厜鏅曘€佷綋绉厜涓庢垙鍓ф€ч€嗗厜鍋忕疆銆?
|
||||||
|
|
||||||
|
## [1.0.32] - 2026-07-18
|
||||||
|
|
||||||
|
- 鐢婚楠岃瘉瀹℃牳鍗囩骇涓哄浐瀹氱淮搴﹀崗璁紱鏈嶅姟绔寜澶村儚銆佸叏韬€佽法鍦烘櫙鍒嗗埆鍔犳潈鑴搁儴銆佺溂鐫涖€佺嚎绋裤€佽壊褰┿€侀槾褰便€佹瘮渚嬩笌鑳屾櫙锛屼笉鍐嶇洿鎺ラ噰鐢ㄨ瑙夋ā鍨嬬殑鑷敱鎬诲垎锛屽苟璁板綍缁村害瑕嗙洊鐜囦笌缂哄け椤广€?
|
||||||
|
- 澶嶉獙鍏辫瘑鑷姩鑱氬悎涓婁竴杞笁寮犻獙璇佸浘锛屽皢鑷冲皯涓や釜鍦烘櫙閲嶅鍑虹幇鐨勯棶棰樺綊绫讳负鍏叡鐢婚缂洪櫡锛屽皢鍗曞満鏅棶棰樹繚鐣欎负灏哄害鑳跺泭淇锛岄伩鍏嶅ご鍍忛棶棰樻薄鏌撳叏韬垨鍦烘櫙鎻愮ず璇嶃€?
|
||||||
|
- 鍏辫瘑鍗忚鏂板鍏ㄥ眬鑹插僵涓庡眬閮ㄨ壊宸垎绂汇€佺粨鏋勫寲宸紓銆佹彁绀鸿瘝琛ヤ竵銆佽涔夐闄╁璁″拰灏哄害鑳跺泭锛涘彲鑳借瀛楅潰鍖栦负鐗╀綋銆佸厜鏁堟垨鏋勫浘鐨勬瘮鍠诲繀椤绘敼鍐欎负琛ㄩ潰銆佸嚑浣曚笌浣嶇疆鍏崇郴銆?
|
||||||
|
- detailed 鐢婚鑳跺泭鏀圭敱鏈嶅姟绔紪璇戯細鎸夋牳蹇冦€佺粨鏋勩€佹覆鏌撲紭鍏堢骇鍚堝苟 `must_preserve`锛岃繎涔夊幓閲嶅苟闄愬埗涓?14 鏉″叕鍏辨牳蹇冪壒寰侊紝鍐嶅彔鍔犳渶澶?5 鏉″満鏅昂搴︾壒寰侊紝鍑忓皯闀挎彁绀鸿瘝鐨勬敞鎰忓姏绋€閲娿€?
|
||||||
|
- 姣忚疆涓夊浘瀹屾垚鍚庤嚜鍔ㄤ笌涓婁竴杞绠楁€诲垎鍜屽垎鍦烘櫙宸€硷紝鏍囪閲囩敤鍊欓€夈€佷繚鐣欎笂涓€鐗堟垨闇€瑕佷汉宸ュ垽鏂紱瑙嗚瀹℃牳澶辫触浠嶄笉褰卞搷鐢熸垚鍥剧墖淇濈暀銆?
|
||||||
|
|
||||||
|
## [1.0.31] - 2026-07-18
|
||||||
|
|
||||||
|
- 鐢婚閫愬浘璇嗗埆涓庝氦鍙夊叡璇嗘柊澧炶劯鍨嬨€佺溂鐫?铏硅啘銆侀蓟鍙g畝鍖栥€佸ご韬瘮銆佸彂鏉熺粍缁囥€佺嚎鏉℃嫇鎵戙€侀槾褰辫壊鐩搞€侀珮鍏夊舰鐘跺拰鑹插僵鍏崇郴绛夌粨鏋勭敾椋庣淮搴︼紝涓嶅啀鍙緭鍑洪€氱敤鍔ㄦ极娓叉煋鏍囩銆?
|
||||||
|
- 褰掍竴鍖栧眰淇濈暀瑙嗚妯″瀷杩斿洖鐨?`normalized_asset_profile.attributes`锛屽苟涓虹敾椋庤嚜鍔ㄧ敓鎴?`must_preserve`锛涗慨澶嶇粨鏋勫寲灞炴€ч€€鍖栨垚鍗曚竴 `legacy_description` 鐨勯棶棰樸€?
|
||||||
|
- 鍐呭姹℃煋娓呭崟浠呯敤浜庡璁★紝涓嶅啀鍘熸牱娉ㄥ叆鐢熷浘璐熷悜鎻愮ず璇嶏紱鏀逛负鍙帓闄ゅ叿浣撴簮瑙掕壊韬唤銆佸叿浣撴湇瑁呰璁°€佸Э鍔夸笌鍦烘櫙锛岄伩鍏嶈浼?Moe 姣斾緥銆佸姩鐗╄€崇瓑椋庢牸鑰﹀悎鐗瑰緛銆?
|
||||||
|
- 淇 detailed 鑳跺泭鍚€楀彿璇箟鐭琚媶纰庛€佺煭鍏辫瘑涓庤缁嗚兌鍥婇噸澶嶆嫾鎺ャ€佹璐熸彁绀鸿瘝澶氭閲嶅鐨勯棶棰橈紝骞跺缂哄皯缁撴瀯缁村害鐨勬ā鍨嬭嚜鎶ョ疆淇″害杩涜鏈嶅姟绔檷鏉冦€?
|
||||||
|
- 姣忓紶楠岃瘉鍥剧敓鎴愬悗鑷姩浣跨敤浠h〃婧愬浘杩涜瑙嗚杩樺師搴﹀鏍革紝鎸佷箙鍖栫淮搴﹁瘎鍒嗐€佷富瑕佸尮閰?鍋忓樊鍙婁笅涓€杞慨姝f彁绀猴紱瀹℃牳澶辫触涓嶄細涓㈠純宸茬粡鐢熸垚鐨勫浘鐗囥€?
|
||||||
|
- 杩涢樁鐢婚楠岃瘉鍗$墖鏄剧ず鑷姩杩樺師搴﹀拰涓昏鍋忓樊锛涜瑙夋ā鍨嬫牸寮忛敊璇柊澧炶劚鏁忓悗鐨勫叿浣撳搷搴旈棶棰樺拰瑙f瀽鍘熷洜銆?
|
||||||
|
|
||||||
|
## [1.0.30] - 2026-07-18
|
||||||
|
|
||||||
|
- 杩涢樁鐢婚澶嶉獙浼氬悓鏃舵彁浜や唬琛ㄦ簮鍥俱€佷笂涓€杞笁寮犲け璐ラ獙璇佸浘銆佸叏閮ㄦ簮鍥捐瘑鍒姤鍛娿€佷笂涓€鐗堟彁绀鸿瘝涓庣敤鎴蜂慨姝o紝瑙嗚妯″瀷鍙洿鎺ヨ繘琛屽墠鍚庡鐓с€?
|
||||||
|
- 灏嗏€滃お寮恒€侀檷浣庛€佸お寮便€佸姞寮恒€佺Щ闄ゃ€佷繚鎸佲€濈瓑鍙嶉瑙f瀽涓?increase/decrease/remove/preserve 缁撴瀯鍖栨柟鍚戯紝骞舵寔涔呭寲瀵圭収娓呭崟涓庡疄闄呰皟鏁磋鍒掋€?
|
||||||
|
- 澧炲姞鏈嶅姟绔涔夐槻鍙嶈浆锛涗緥濡傗€滈鑹插姣斿お杩囧己鐑堚€濅笉浼氬啀琚浆鎹负 intense/extreme/high contrast锛岃€屼細钀藉疄涓洪€備腑鍏嬪埗鐨勫姣斿苟鎺掗櫎杩囧己鑹插樊銆?
|
||||||
|
- 涓夊紶楠岃瘉鐢熷浘缁熶竴浣跨敤 detailed 鐢婚鑳跺泭鍙婂叾璐熷悜绾︽潫锛屼笉鍐嶅彧浣跨敤鐭叡璇嗘彁绀鸿瘝锛涗粛淇濇寔绾枃鏈縼绉婚獙璇侊紝涓嶅悜鐢熷浘妯″瀷浼犻€掓簮鍥俱€?
|
||||||
|
|
||||||
|
- 宸插畬鎴愬叏浠撹鑹插伐浣滄祦浜屾瀹¤锛涚‘璁ゅ湪鐜版湁 `character_gradual` 涓荤嚎涓婂閲忎慨澶嶏紝涓嶅垱寤哄钩琛屽伐浣滄祦銆?
|
||||||
|
- 淇闃熷垪宸叉寜 1.0.9鈥?.0.20 灏忕増鏈啓鍏?`docs/workflow-secondary-audit-development-queue.md`銆?
|
||||||
|
|
||||||
|
## [1.0.29] - 2026-07-17
|
||||||
|
|
||||||
|
- 杩涢樁绱犳潗鐨勭敾椋庢牱鏈€佷笁寮犲綋鍓嶉獙璇佸浘銆佸崟鍥炬簮鍥?楠岃瘉鍥句互鍙婂巻鍙茶疆娆$缉鐣ュ浘鍏ㄩ儴鎺ュ叆缁熶竴澶у浘棰勮鍗$墖銆?
|
||||||
|
- 鐐瑰嚮鎴栦娇鐢ㄩ敭鐩?Enter/绌烘牸鍙墦寮€鍘熷浘浼樺厛鐨勫ぇ鍥鹃瑙堬紝鏀寔婊氳疆缂╂斁銆佹寜閽缉鏀俱€佸弻鍑荤缉鏀俱€佹嫋鍔ㄧ敾甯冦€侀噸缃拰 Esc 鍏抽棴銆?
|
||||||
|
- 澶у浘閬僵缁х画浣跨敤瀹夊叏鍗曞嚮鍏抽棴閫昏緫锛屾枃鏈嫋閫夈€佸浘鐗囨嫋鍔ㄦ垨鎸囬拡绉诲嚭鍗$墖涓嶄細璇Е鍏抽棴銆?
|
||||||
|
- 缂╃暐鍥惧鍔犳斁澶у厜鏍囥€侀敭鐩樼劍鐐瑰拰鏄庣‘鐨勨€滅偣鍑绘煡鐪嬪ぇ鍥锯€濇彁绀恒€?
|
||||||
|
|
||||||
|
## [1.0.28] - 2026-07-17
|
||||||
|
|
||||||
|
- 淇杩涢樁鐢婚瀵煎叆鍚庣浣跨敤 `advanced_style_set`銆佸墠绔彧璇嗗埆 `style_set`锛屽鑷翠笁鍥鹃獙璇佽璇垽涓哄崟鍥炬祦绋嬩笖涓荤晫闈㈠彧鏄剧ず涓€寮犻獙璇佸浘鐨勯棶棰樸€?
|
||||||
|
- 澶氬浘鐢婚褰撳墠杞鎭㈠涓哄ご鍍忋€佸叏韬€佽法鍦烘櫙涓夊紶楠岃瘉鍗$墖锛涗笁寮犲浘鍒嗗埆鏄剧ず鐘舵€併€佹彁绀鸿瘝銆佹枃瀛楄皟鏁村拰闅忔満绉嶅瓙銆?
|
||||||
|
- 楠岃瘉杞鍒楄〃涓庤鎯呮帴鍙d负姣忎竴杞檮甯﹀畬鏁?`validation_cases`锛屽巻鍙茶疆娆′篃鍙悓鏃舵煡鐪嬩笁寮犵缉鐣ュ浘锛屼笉鍐嶅彧灞曠ず鑱氬悎杞鐨勭涓€寮犳姇褰卞浘銆?
|
||||||
|
- 鍏煎鏃?`style_set`銆佹寮?`advanced_style_set` 浠ュ強鏈嶅姟绔?`metadata.style_set` 鏍囪锛岄伩鍏嶅崌绾у墠鍚庣殑璁板綍鍐嶆璧伴敊鍓嶇鍒嗘敮銆?
|
||||||
|
|
||||||
|
## [1.0.27] - 2026-07-17
|
||||||
|
|
||||||
|
- 杩涢樁鐢婚澶嶉獙鎷嗗垎涓衡€滅敾椋庝慨姝b€濆拰鈥滀笅涓€杞獙璇佸唴瀹光€濅袱鏉$嫭绔嬭緭鍏ワ細鍓嶈€呭彧閲嶅缓鐢婚鍏辫瘑涓庤兌鍥婏紝鍚庤€呯洿鎺ュ啓鍏ヤ笁涓獙璇佺敓鍥炬彁绀鸿瘝銆?
|
||||||
|
- 淇绗簩杞己鍒跺鐢ㄧ涓€杞€佸勾鐢锋€с€佹満鍣ㄤ汉鍜屽畤鑸憳鍦烘櫙鐨勯棶棰橈紱鐢ㄦ埛鎸囧畾瑙掕壊銆佹湇瑁呫€佹瀯鍥炬垨鍦烘櫙鍚庝細閲嶅缓楠岃瘉妗堜緥锛屼笖鏈€缁?`expanded_prompt` 蹇呭畾鍖呭惈鐢ㄦ埛鍘熸枃銆?
|
||||||
|
- 鍙慨鏀圭敾椋庢椂缁х画娌跨敤鐩稿悓楠岃瘉鍦烘櫙涓庣瀛愶紝渚夸簬 A/B 姣旇緝锛涗慨鏀归獙璇佸唴瀹规椂浣跨敤鏂扮瀛愶紝閬垮厤鏃ф瀯鍥捐闅忔満绉嶅瓙鎸佺画閿佸畾銆?
|
||||||
|
- 榛樿楠岃瘉鏀逛负鍚屼竴鏂拌鑹茬殑杩戝煙澶村儚銆佸叏韬拰璺ㄥ満鏅笁绾у鐓э紝鍑忓皯瑙掕壊骞撮緞銆佺墿绉嶄笌鍐欏疄鍏堥獙瀵圭敾椋庡垽鏂殑骞叉壈銆?
|
||||||
|
- 楠岃瘉鍗$墖鏄剧ず宸插簲鐢ㄧ殑鏂囧瓧璋冩暣鍜屽疄闄呯瀛愶紱鍘嗗彶杞鎸佷箙鍖栫敾椋庝慨姝c€侀獙璇佸唴瀹瑰強鍏朵綔鐢ㄨ寖鍥淬€?
|
||||||
|
- 鏃у鎴风缁х画鏀寔鍗曚竴 `adjustment_text`锛屾湇鍔$浼氬悓鏃跺簲鐢ㄥ埌鐢婚涓庨獙璇佸唴瀹归摼璺紝閬垮厤鍙嶉闈欓粯涓㈠け銆?
|
||||||
|
|
||||||
|
## [1.0.26] - 2026-07-17
|
||||||
|
|
||||||
|
- 淇浠诲姟杈冨鏃堕槦鍒楀崱鐗囪婊氬姩鍖哄煙鍘嬬缉鐨勯棶棰橈紱浠诲姟鍗℃敼涓虹旱鍚戣嚜鐒堕珮搴︽帓鍒楋紝鐘舵€併€佹爣棰樸€佽繘搴︽潯涓庤€楁椂涓嶅啀鐩镐簰瑕嗙洊銆?
|
||||||
|
- 杩涢樁绱犳潗楠岃瘉杞鏀逛负鍙洿鏂板綋鍓嶆椿鍔ㄥ鍏ユ垨瀵煎叆鎽樿锛屼笉鍐嶆瘡 4.5 绉掑叏閲忓埛鏂板鍏ュ簱涓庣礌鏉愬簱銆?
|
||||||
|
- 澧炲姞杞浜掓枼锛岄槻姝㈡參璇锋眰鍙戠敓閲嶅彔锛涜疆璇㈠け璐ヤ繚鎸佸綋鍓嶉〉闈紝涓嶅啀瑙﹀彂閿欒鎬佹垨瑙嗚閲嶇疆銆?
|
||||||
|
- 鍥剧墖灞曠ず浼樺厛浣跨敤绋冲畾鐨?`storage://` URI 缂撳瓨锛屽拷鐣ュ悓涓€濯掍綋姣忚疆鍙樺寲鐨勪复鏃剁鍚?URL锛岄伩鍏嶉獙璇佺敓鎴愭湡闂村浘鐗囧弽澶嶉噸杞藉拰椤甸潰闂儊銆?
|
||||||
|
|
||||||
|
## [1.0.25] - 2026-07-17
|
||||||
|
|
||||||
|
- 淇杩涢樁绱犳潗闃熷垪璁板綍琚墜鍔ㄥ垹闄ゅ悗锛屽鍏ユ垨鏍锋湰浠嶄繚鎸?queued/running 骞舵案涔呭崱浣忕殑闂锛涜鎯呰鍙栥€佸垪琛ㄥ埛鏂板拰閲嶈瘯鍓嶄細灏嗙己澶变换鍔″璐︿负鍙噸璇曞け璐ャ€?
|
||||||
|
- 鏂板鏈皝瀛樿繘闃跺鍏ュ垹闄ゆ帴鍙d笌鍓嶇鍙屽嚮纭鎸夐挳锛涘垹闄や細鍏堝彇娑堟畫鐣欎换鍔★紝鍐嶇骇鑱旀竻鐞嗘牱鏈€佷氦鍙夊叡璇嗐€侀獙璇佽疆娆″拰杩涢樁绱犳潗鐙珛鏂囦欢銆?
|
||||||
|
- 宸插皝瀛樹负楂樹紭鍏堢骇绱犳潗鐨勫鍏ョ姝㈠垹闄わ紝浠嶉渶閫氳繃绱犳潗褰掓。娴佺▼澶勭悊锛岄伩鍏嶇牬鍧忕礌鏉愬簱銆佽。姗卞拰宸ヤ綔娴佸紩鐢ㄣ€?
|
||||||
|
- 缂哄け闃熷垪浠诲姟浼氭樉绀烘槑纭彁绀猴紝鍙€夋嫨鍗曠嫭閲嶈瘯銆佹帓闄ゆ牱鏈垨鍒犻櫎鏁翠釜瀵煎叆锛屼笉鍐嶅彧鏄剧ず妯$硦鐨勨€滃緟澶勭悊鏍锋湰鈥濄€?
|
||||||
|
|
||||||
|
## [1.0.24] - 2026-07-17
|
||||||
|
|
||||||
|
- 妯″瀷鍒嗗伐缁熶竴涓哄弻婧愯矾鐢憋細姣忎釜鏂囨湰/瑙嗚鑺傜偣鍒嗗埆閫夋嫨 ImageStudio 鎻掍欢閫傞厤鍣ㄤ笌 AstrBot 妯″瀷鎻愪緵鍟嗭紝鎵ц椤哄簭鍥哄畾涓烘彃浠朵紭鍏堛€丄strBot 澶囩敤銆?
|
||||||
|
- 绱犳潗璇嗗埆銆佽繘闃剁礌鏉愯瘑鍒€佸鍥剧敾椋庡叡璇嗐€佺粨鏋勫寲鏂囨湰璋冪敤鍜岀敓鎴愬悗瑙嗚瀹℃牳鍔犲叆鏁呴殰杞Щ锛涘墠缃彁渚涘晢澶辫触鏃惰嚜鍔ㄥ皾璇曞鐢紝骞朵繚鐣欏け璐ユ憳瑕併€?
|
||||||
|
- 鐢熷浘鑺傜偣鏄庣‘鍙€夋嫨 ImageStudio 鐢熷浘閫傞厤鍣紱AstrBot 4.25 娌℃湁鍏紑鐢熷浘妗ユ帴鎺ュ彛锛屽洜姝ょ晫闈㈢鐢ㄤ笉鍙墽琛岀殑瀹夸富鐢熷浘閫夋嫨锛岄伩鍏嶄繚瀛樺悗杩愯澶辫触銆?
|
||||||
|
- 杩涢樁鐢婚澶辫触鏍锋湰閲嶈瘯鏃堕噸鏂拌鍙栧綋鍓嶅弻婧愰厤缃紝骞跺悓姝ュ埛鏂扮埗瀵煎叆璺敱锛屼慨澶嶆棫 `material_vlm` 琚换鍔℃案涔呭喕缁撶殑闂銆?
|
||||||
|
- 鎻愮ず璇嶈浆璇戙€佺敓鎴愬墠鍐呭瀹℃牳涓庣敓鎴愬悗鍥剧墖瀹℃牳鍚屾浣跨敤鍙岄€夋嫨鏍忥紱鏃у崟璺敱閰嶇疆淇濇寔鍏煎锛屽弻璺敱缁х画瀛樹负鍗曚釜 AstrBot 閰嶇疆瀛楃涓层€?
|
||||||
|
- 淇杩愯鏃剁増鏈父閲忎笌鍙戝竷鍏冩暟鎹笉鍚屾鐨勯棶棰橈紝鐘舵€侀〉鍜屾彃浠跺厓鏁版嵁缁熶竴鏄剧ず 1.0.24銆?
|
||||||
|
|
||||||
|
## [1.0.23] - 2026-07-17
|
||||||
|
|
||||||
|
- 灏嗗唴缃礌鏉愬垎绫荤殑鑻辨枃鍚嶇О缁熶竴鏄剧ず涓轰腑鏂囷紝骞惰鐩栬繘闃剁礌鏉愬鍏ャ€佺礌鏉愭搷浣滃拰璇嗗埆鎻愮ず璇嶈缃笅鎷夋銆?
|
||||||
|
- 淇濈暀鍚庣鍒嗙被 ID 涓庡師濮嬪悕绉帮紝鍏煎鐜版湁绱犳潗銆佽。姗卞拰宸ヤ綔娴佹暟鎹€?
|
||||||
|
|
||||||
|
## [1.0.22] - 2026-07-17
|
||||||
|
|
||||||
|
- 杩涢樁绱犳潗鐨勨€滈鏍尖€濆垎绫绘柊澧?2锝? 寮犳牱鏈粍瀵煎叆锛堟帹鑽?3锝? 寮狅級锛涙瘡寮犲浘鎷ユ湁鐙珛浠诲姟銆佽鏃躲€侀敊璇笌閲嶈瘯锛屽苟鐢?8 Worker 鍚屾椂澶勭悊锛屼笉鍐嶄覆琛屽叡浜秴鏃躲€?
|
||||||
|
- 鏂板閫愬浘璇嗗埆灞忛殰鍜屽鍥句氦鍙夊綊绾筹細妯″瀷鍚屾椂璇诲彇鍏ㄩ儴鏈夋晥鍘熷浘涓庨€愬浘鎶ュ憡锛屽尯鍒嗘牳蹇冨叡鍚岀敾椋庛€佸彲鍙橀」銆佹簮鍐呭姹℃煋銆佺枒浼肩缇ゆ牱鏈拰 1锝? 寮犱唬琛ㄦ牱鏈紝骞剁敓鎴?compact / standard / detailed 涓夋。鐢婚鑳跺泭銆?
|
||||||
|
- 鏂板涓夎矾绾彁绀鸿瘝杩佺Щ楠岃瘉锛屼娇鐢ㄥ畬鍏ㄤ笉鍚岀殑瑙掕壊銆佸満鏅拰鏋勫浘涓斾笉浼犳簮鍥撅紱涓夐」浠诲姟鐙珛骞跺彂锛屽崟椤瑰け璐ュ彲鍗曠嫭閲嶈瘯锛岃皟鏁村悗鍒涘缓鏂板叡璇嗙増鏈苟澶嶇敤鐩稿悓楠岃瘉鍦烘櫙銆?
|
||||||
|
- 鏂板 `advanced_style_sources`銆乣advanced_style_consensus_runs`銆乣advanced_style_validation_cases` 涓夎〃锛涚埗瀵煎叆涓?2锝? 寮犳簮璁板綍鍘熷瓙鍐欏叆锛岄獙璇佸浘鐗囩户缁殧绂诲湪 `storage://advanced_materials/style-validations`銆?
|
||||||
|
- 鍓嶇浠呭湪鈥滈鏍尖€濆垎绫诲惎鐢ㄥ鍥句笂浼狅紝鏀寔绮樿创銆佹嫋鍏ャ€佽拷鍔犮€佺Щ闄ゃ€佹帓搴?涓诲弬鑰冦€佸け璐ラ噸璇曘€佹牱鏈帓闄や笌鎭㈠锛屽苟灞曠ず浜ゅ弶褰掔撼銆佷唬琛?绂荤兢鏍锋湰鍜屼笁鍦烘櫙鐘舵€併€?
|
||||||
|
- 灏佸瓨鍚庝粛鍙骇鐢熶竴涓珮浼樺厛绾?`advmat_`锛涘揩閫熻鑹蹭娇鐢ㄧ粺涓€鏂囧瓧鑳跺泭锛岃缁嗗伐浣滄祦鍐荤粨涓诲弬鑰冧笌鏈€澶氫袱寮犲彲淇′唬琛ㄥ浘锛屾櫘閫氱礌鏉愪吉閫?metadata 鏃犳硶娉ㄥ叆棰濆寮曠敤銆?
|
||||||
|
- 澶囦唤鑴辨晱銆佹仮澶嶃€佸鍎垮獟浣撱€侀€愬満鏅垚鏈€佺礌鏉愮粺璁°€乄orker 閲嶅惎鎭㈠銆佽矾鐢卞绾﹀拰娣辫壊涓婚鍚屾瑕嗙洊鏂伴摼璺紱浠樿垂楠岃瘉浠诲姟閲嶅惎鍚庝笉浼氳嚜鍔ㄩ噸澶嶆彁浜ゃ€?
|
||||||
|
|
||||||
|
## [1.0.21] - 2026-07-16
|
||||||
|
|
||||||
|
- 鏂板鐙珛鈥滆繘闃剁礌鏉愨€濆叆搴撶嚎锛氭簮鍥剧粡 Vision 璇嗗埆鍚庯紝鍙敤鎻愬彇鍑虹殑鏂囧瓧鎻愮ず璇嶇敓鎴愰獙璇佸浘锛涚敤鎴峰彲骞舵帓鍒ゆ柇杩樺師搴︼紝涓嶆弧鎰忔椂杩藉姞鎻忚堪杩涘叆涓嬩竴杞紝婊℃剰鍚庢墠灏佸瓨銆?
|
||||||
|
- 鏂板 `advanced_material_imports`銆乣advanced_material_validation_attempts`銆乣advanced_materials` 涓夎〃涓?`storage://advanced_materials` 鐙珛鏂囦欢鏍癸紱楠岃瘉鍥句笉杩涘叆鏅€氬浘搴撱€佸崟鍥炬睜鎴栧伐浣滄祦鍊欓€夋睜銆?
|
||||||
|
- 杩涢樁绱犳潗浠ユ湇鍔$鍙俊鏍囪杩涘叆缁熶竴绱犳潗鐩綍锛屽揩閫熻鑹插拰璇︾粏宸ヤ綔娴佷紭鍏堜娇鐢紱鏅€氱礌鏉愪吉閫?metadata 涓嶄細鑾峰緱杩涢樁浼樺厛绾с€?
|
||||||
|
- 楠岃瘉鐢熷浘鎺ュ叆鎭愭毚/鏋佺鏆村姏鍓嶇疆绂佹銆佹垚浜哄唴瀹圭櫧鍚嶅崟涓?NSFW 璺敱銆佹櫘閫氭ā鍨嬫槑纭?NSFW 鎷掔粷鍚庣殑涓€娆℃€у洖閫€锛屼互鍙婂彲淇濆瓨鐨勭嫭绔嬮绠楀畧鍗€?
|
||||||
|
- 淇杩愯涓彇娑堝悗鐨勮繜鍒扮粨鏋滃娲汇€佸揩閫熼噸鍚换鍔℃案涔呭崱浣忋€佸け璐?鍙栨秷浣嗗凡璁¤垂杞婕忕畻銆佽劚鏁忓浠藉啓鍏?NOT NULL 澶辫触鍜岀┖ MIME 鍥剧墖璇姤 PNG銆?
|
||||||
|
- 鏂板杩涢樁瀵煎叆銆佷笁搴撳垏鎹€佷换鍔¤疆璇€佸師鍥?楠岃瘉鍥惧苟鎺掑鏍搞€佽皟鏁撮噸璇曘€佹樉寮忓皝瀛樸€佹繁鑹蹭富棰樺拰楂樹紭鍏堢骇鏍囪锛涙ā鍨嬪垎宸ユ柊澧炶繘闃惰瘑鍒笌楠岃瘉鐢熷浘涓ゅ紶鍗°€?
|
||||||
|
- 涓撻」瑕嗙洊杩佺Щ骞傜瓑銆佷粨鍌ㄤ簨鍔°€佹櫘閫?杩涢樁闅旂銆佹棤鍥剧敓鍥捐緭鍏ャ€佸彇娑?CAS銆佸畨鍏ㄨ矾鐢便€侀绠椼€侀噸鍚仮澶嶃€佸浠姐€佹垚鏈笌鍓嶇涓婁紶濂戠害銆?
|
||||||
|
|
||||||
## [1.0.20] - 2026-07-15
|
## [1.0.20] - 2026-07-15
|
||||||
|
|
||||||
- 发布总验收补齐两处跨版本接线:工作台唯一挂载生成式交叉审查对话框并真实调用 decide/regenerate/approve;档案卡入库移除客户端三段式写入,统一调用后端 `finalize-card` 幂等事务。
|
- 鍙戝竷鎬婚獙鏀惰ˉ榻愪袱澶勮法鐗堟湰鎺ョ嚎锛氬伐浣滃彴鍞竴鎸傝浇鐢熸垚寮忎氦鍙夊鏌ュ璇濇骞剁湡瀹炶皟鐢?decide/regenerate/approve锛涙。妗堝崱鍏ュ簱绉婚櫎瀹㈡埛绔笁娈靛紡鍐欏叆锛岀粺涓€璋冪敤鍚庣 `finalize-card` 骞傜瓑浜嬪姟銆?
|
||||||
- AstrBot 托管配置桥补齐视觉质检、兼容审核与生成式交叉审查的主/副/列表字段;保存、清空和重载均保留真实值,不再被旧运行时覆盖恢复。
|
- AstrBot 鎵樼閰嶇疆妗ヨˉ榻愯瑙夎川妫€銆佸吋瀹瑰鏍镐笌鐢熸垚寮忎氦鍙夊鏌ョ殑涓?鍓?鍒楄〃瀛楁锛涗繚瀛樸€佹竻绌哄拰閲嶈浇鍧囦繚鐣欑湡瀹炲€硷紝涓嶅啀琚棫杩愯鏃惰鐩栨仮澶嶃€?
|
||||||
- 新增全新安装、1.0.8 原位升级、重复迁移、缺表/半迁移恢复、stale Worker、终态通知补发、宿主已加载顶层 `core` 包和插件初始化顺序回归。
|
- 鏂板鍏ㄦ柊瀹夎銆?.0.8 鍘熶綅鍗囩骇銆侀噸澶嶈縼绉汇€佺己琛?鍗婅縼绉绘仮澶嶃€乻tale Worker銆佺粓鎬侀€氱煡琛ュ彂銆佸涓诲凡鍔犺浇椤跺眰 `core` 鍖呭拰鎻掍欢鍒濆鍖栭『搴忓洖褰掋€?
|
||||||
- 前端新增路由继承、锁状态、交叉审查接线与原子档案卡接线契约测试;生产构建继续输出 AstrBot 插件页与独立 Web 兼容产物。
|
- 鍓嶇鏂板璺敱缁ф壙銆侀攣鐘舵€併€佷氦鍙夊鏌ユ帴绾夸笌鍘熷瓙妗f鍗℃帴绾垮绾︽祴璇曪紱鐢熶骇鏋勫缓缁х画杈撳嚭 AstrBot 鎻掍欢椤典笌鐙珛 Web 鍏煎浜х墿銆?
|
||||||
- 清除生产包中断连时可达的假生图、假角色、示例素材和预览模型;断连与空后端统一显示明确空状态,缺少图片的真实记录仅显示“未生成/无缩略图”。
|
- 娓呴櫎鐢熶骇鍖呬腑鏂繛鏃跺彲杈剧殑鍋囩敓鍥俱€佸亣瑙掕壊銆佺ず渚嬬礌鏉愬拰棰勮妯″瀷锛涙柇杩炰笌绌哄悗绔粺涓€鏄剧ず鏄庣‘绌虹姸鎬侊紝缂哄皯鍥剧墖鐨勭湡瀹炶褰曚粎鏄剧ず鈥滄湭鐢熸垚/鏃犵缉鐣ュ浘鈥濄€?
|
||||||
- README 与 INSTALL 更新 11 节点工作流、聊天命令、模型分工、无模型行为、Docker/NAS 覆盖和显式运行时 ZIP 白名单;发布包禁止包含 `.env*`、真实数据、测试、前端工程和缓存。
|
- README 涓?INSTALL 鏇存柊 11 鑺傜偣宸ヤ綔娴併€佽亰澶╁懡浠ゃ€佹ā鍨嬪垎宸ャ€佹棤妯″瀷琛屼负銆丏ocker/NAS 瑕嗙洊鍜屾樉寮忚繍琛屾椂 ZIP 鐧藉悕鍗曪紱鍙戝竷鍖呯姝㈠寘鍚?`.env*`銆佺湡瀹炴暟鎹€佹祴璇曘€佸墠绔伐绋嬪拰缂撳瓨銆?
|
||||||
- NAS 实机从 1.0.8 原位升级并重启 `astrbot-ops-pro`:AstrBot 成功加载 ImageStudio 1.0.20,SQLite 15 条迁移与关键轮次/档案卡/素材表通过检查,插件页面自动连接且未触发真实付费生图。
|
- NAS 瀹炴満浠?1.0.8 鍘熶綅鍗囩骇骞堕噸鍚?`astrbot-ops-pro`锛欰strBot 鎴愬姛鍔犺浇 ImageStudio 1.0.20锛孲QLite 15 鏉¤縼绉讳笌鍏抽敭杞/妗f鍗?绱犳潗琛ㄩ€氳繃妫€鏌ワ紝鎻掍欢椤甸潰鑷姩杩炴帴涓旀湭瑙﹀彂鐪熷疄浠樿垂鐢熷浘銆?
|
||||||
|
|
||||||
## [1.0.9] - 2026-07-15
|
## [1.0.9] - 2026-07-15
|
||||||
|
|
||||||
- 在现有节点、任务、图片和历史链路之上增加稳定的生成轮次、候选与候选池聚合层。
|
- 鍦ㄧ幇鏈夎妭鐐广€佷换鍔°€佸浘鐗囧拰鍘嗗彶閾捐矾涔嬩笂澧炲姞绋冲畾鐨勭敓鎴愯疆娆°€佸€欓€変笌鍊欓€夋睜鑱氬悎灞傘€?
|
||||||
- 旧工作流图片通过只读 legacy round 展示,不搬文件、不改原有 `image_id`。
|
- 鏃у伐浣滄祦鍥剧墖閫氳繃鍙 legacy round 灞曠ず锛屼笉鎼枃浠躲€佷笉鏀瑰師鏈?`image_id`銆?
|
||||||
- 新增 `TX-01`、`TX-01-03` 等持久化显示码,并记录模型来源、失败摘要与轮次快照。
|
- 鏂板 `TX-01`銆乣TX-01-03` 绛夋寔涔呭寲鏄剧ず鐮侊紝骞惰褰曟ā鍨嬫潵婧愩€佸け璐ユ憳瑕佷笌杞蹇収銆?
|
||||||
- `SingleFlowEngine` 支持按 workflow/branch/node/round/candidate 隔离输出目录;无 round 上下文时保持旧路径兼容。
|
- `SingleFlowEngine` 鏀寔鎸?workflow/branch/node/round/candidate 闅旂杈撳嚭鐩綍锛涙棤 round 涓婁笅鏂囨椂淇濇寔鏃ц矾寰勫吋瀹广€?
|
||||||
- 补齐数据库表元数据与 AstrBot/前端共享 round 接口;创建轮次仅规划候选,不会触发真实生图。
|
- 琛ラ綈鏁版嵁搴撹〃鍏冩暟鎹笌 AstrBot/鍓嶇鍏变韩 round 鎺ュ彛锛涘垱寤鸿疆娆′粎瑙勫垝鍊欓€夛紝涓嶄細瑙﹀彂鐪熷疄鐢熷浘銆?
|
||||||
|
|
||||||
## [1.0.10] - 2026-07-15
|
## [1.0.10] - 2026-07-15
|
||||||
|
|
||||||
- 详细工作流每轮只执行一次提示词扩写、治理、路由、素材快照与成本检查,再拆分为 4–5 条独立 `count=1` 候选任务。
|
- 璇︾粏宸ヤ綔娴佹瘡杞彧鎵ц涓€娆℃彁绀鸿瘝鎵╁啓銆佹不鐞嗐€佽矾鐢便€佺礌鏉愬揩鐓т笌鎴愭湰妫€鏌ワ紝鍐嶆媶鍒嗕负 4鈥? 鏉$嫭绔?`count=1` 鍊欓€変换鍔°€?
|
||||||
- 启用 5 Worker 持久并发池;单候选失败或超时不影响同轮其他候选,轮次聚合支持完成、部分成功、全部失败和取消。
|
- 鍚敤 5 Worker 鎸佷箙骞跺彂姹狅紱鍗曞€欓€夊け璐ユ垨瓒呮椂涓嶅奖鍝嶅悓杞叾浠栧€欓€夛紝杞鑱氬悎鏀寔瀹屾垚銆侀儴鍒嗘垚鍔熴€佸叏閮ㄥけ璐ュ拰鍙栨秷銆?
|
||||||
- AstrBot 初始化自动启动 Worker、终止时停止;启动可恢复 stale `running/retrying` 任务,旧同步 `generate_node()` 保持兼容。
|
- AstrBot 鍒濆鍖栬嚜鍔ㄥ惎鍔?Worker銆佺粓姝㈡椂鍋滄锛涘惎鍔ㄥ彲鎭㈠ stale `running/retrying` 浠诲姟锛屾棫鍚屾 `generate_node()` 淇濇寔鍏煎銆?
|
||||||
- 异步任务拒绝持久化 data URL;模型路由只保存无敏感字段的快照,执行时重新解析并校验 provider/model 未漂移。
|
- 寮傛浠诲姟鎷掔粷鎸佷箙鍖?data URL锛涙ā鍨嬭矾鐢卞彧淇濆瓨鏃犳晱鎰熷瓧娈电殑蹇収锛屾墽琛屾椂閲嶆柊瑙f瀽骞舵牎楠?provider/model 鏈紓绉汇€?
|
||||||
|
|
||||||
## [1.0.11] - 2026-07-15
|
## [1.0.11] - 2026-07-15
|
||||||
|
|
||||||
- 详细角色候选的聚焦、平铺比较、喜欢/拒绝反馈与最终定稿改为四套独立状态;每轮最多保留 3 个喜欢候选,最终确认严格只能选择 1 个成功候选。
|
- 璇︾粏瑙掕壊鍊欓€夌殑鑱氱劍銆佸钩閾烘瘮杈冦€佸枩娆?鎷掔粷鍙嶉涓庢渶缁堝畾绋挎敼涓哄洓濂楃嫭绔嬬姸鎬侊紱姣忚疆鏈€澶氫繚鐣?3 涓枩娆㈠€欓€夛紝鏈€缁堢‘璁や弗鏍煎彧鑳介€夋嫨 1 涓垚鍔熷€欓€夈€?
|
||||||
- 新增 round feedback/confirm 接口;反馈持久化到候选池与轮次快照,刷新后可恢复,且不会误调用图片采用接口。
|
- 鏂板 round feedback/confirm 鎺ュ彛锛涘弽棣堟寔涔呭寲鍒板€欓€夋睜涓庤疆娆″揩鐓э紝鍒锋柊鍚庡彲鎭㈠锛屼笖涓嶄細璇皟鐢ㄥ浘鐗囬噰鐢ㄦ帴鍙c€?
|
||||||
- 最终确认在单事务内完成候选定稿、图片独占选择、节点状态、历史记录、分支阶段输入和后继节点推进;失败完整回滚,服务端拒绝客户端指定下一节点。
|
- 鏈€缁堢‘璁ゅ湪鍗曚簨鍔″唴瀹屾垚鍊欓€夊畾绋裤€佸浘鐗囩嫭鍗犻€夋嫨銆佽妭鐐圭姸鎬併€佸巻鍙茶褰曘€佸垎鏀樁娈佃緭鍏ュ拰鍚庣户鑺傜偣鎺ㄨ繘锛涘け璐ュ畬鏁村洖婊氾紝鏈嶅姟绔嫆缁濆鎴风鎸囧畾涓嬩竴鑺傜偣銆?
|
||||||
- 工作台接入 4/5 张候选数量、当前轮/历史轮、节制轮询、部分成功/全失败、模型来源、单候选失败和入队提示;旧图片继续使用只读兼容轮次。
|
- 宸ヤ綔鍙版帴鍏?4/5 寮犲€欓€夋暟閲忋€佸綋鍓嶈疆/鍘嗗彶杞€佽妭鍒惰疆璇€侀儴鍒嗘垚鍔?鍏ㄥけ璐ャ€佹ā鍨嬫潵婧愩€佸崟鍊欓€夊け璐ュ拰鍏ラ槦鎻愮ず锛涙棫鍥剧墖缁х画浣跨敤鍙鍏煎杞銆?
|
||||||
|
|
||||||
## [1.0.12] - 2026-07-15
|
## [1.0.12] - 2026-07-15
|
||||||
|
|
||||||
- 工作流对话框支持“1、2 喜欢,3 严格拒绝”等自然语言反馈;LLM 只接收持久展示码和受限候选提示词快照,服务端重新白名单映射,模型失败时安全回退到本地确定性解析。
|
- 宸ヤ綔娴佸璇濇鏀寔鈥?銆? 鍠滄锛? 涓ユ牸鎷掔粷鈥濈瓑鑷劧璇█鍙嶉锛汱LM 鍙帴鏀舵寔涔呭睍绀虹爜鍜屽彈闄愬€欓€夋彁绀鸿瘝蹇収锛屾湇鍔$閲嶆柊鐧藉悕鍗曟槧灏勶紝妯″瀷澶辫触鏃跺畨鍏ㄥ洖閫€鍒版湰鍦扮‘瀹氭€цВ鏋愩€?
|
||||||
- 反馈持久化用户原文、摘要、喜欢/拒绝/严格拒绝、草稿定稿、素材意图与正负提示词补丁;下一轮记录父轮次并严格要求 1–3 个生成成功且喜欢的候选。
|
- 鍙嶉鎸佷箙鍖栫敤鎴峰師鏂囥€佹憳瑕併€佸枩娆?鎷掔粷/涓ユ牸鎷掔粷銆佽崏绋垮畾绋裤€佺礌鏉愭剰鍥句笌姝h礋鎻愮ず璇嶈ˉ涓侊紱涓嬩竴杞褰曠埗杞骞朵弗鏍艰姹?1鈥? 涓敓鎴愭垚鍔熶笖鍠滄鐨勫€欓€夈€?
|
||||||
- 下一轮读取父轮次、候选池和反馈的单一一致性快照,并在创建事务中校验反馈版本;并发反馈变化时拒绝写入,不产生混合或残留子轮次。
|
- 涓嬩竴杞鍙栫埗杞銆佸€欓€夋睜鍜屽弽棣堢殑鍗曚竴涓€鑷存€у揩鐓э紝骞跺湪鍒涘缓浜嬪姟涓牎楠屽弽棣堢増鏈紱骞跺彂鍙嶉鍙樺寲鏃舵嫆缁濆啓鍏ワ紝涓嶄骇鐢熸贩鍚堟垨娈嬬暀瀛愯疆娆°€?
|
||||||
- round 的创建、读取、反馈、下一轮和确认统一接入 profile → workflow → node 所有权链;越权使用资源不存在语义,同时保留 system 与全局管理员兼容。
|
- round 鐨勫垱寤恒€佽鍙栥€佸弽棣堛€佷笅涓€杞拰纭缁熶竴鎺ュ叆 profile 鈫?workflow 鈫?node 鎵€鏈夋潈閾撅紱瓒婃潈浣跨敤璧勬簮涓嶅瓨鍦ㄨ涔夛紝鍚屾椂淇濈暀 system 涓庡叏灞€绠$悊鍛樺吋瀹广€?
|
||||||
- 前端反馈发送不再依赖生图模型;点击“开始下一轮”会先保存未提交文本,保存失败不清空、不建轮次,并同步展示候选门槛与可操作原因。
|
- 鍓嶇鍙嶉鍙戦€佷笉鍐嶄緷璧栫敓鍥炬ā鍨嬶紱鐐瑰嚮鈥滃紑濮嬩笅涓€杞€濅細鍏堜繚瀛樻湭鎻愪氦鏂囨湰锛屼繚瀛樺け璐ヤ笉娓呯┖銆佷笉寤鸿疆娆★紝骞跺悓姝ュ睍绀哄€欓€夐棬妲涗笌鍙搷浣滃師鍥犮€?
|
||||||
|
|
||||||
## [1.0.13] - 2026-07-15
|
## [1.0.13] - 2026-07-15
|
||||||
|
|
||||||
- 详细工作流的任意未封存图像节点可打开独立素材抽屉,复用现有上传、粘贴、视觉识别、确认与素材库筛选能力;抽屉保留 workflow、branch、node、round 返回上下文。
|
- 璇︾粏宸ヤ綔娴佺殑浠绘剰鏈皝瀛樺浘鍍忚妭鐐瑰彲鎵撳紑鐙珛绱犳潗鎶藉眽锛屽鐢ㄧ幇鏈変笂浼犮€佺矘璐淬€佽瑙夎瘑鍒€佺‘璁や笌绱犳潗搴撶瓫閫夎兘鍔涳紱鎶藉眽淇濈暀 workflow銆乥ranch銆乶ode銆乺ound 杩斿洖涓婁笅鏂囥€?
|
||||||
- 节点绑定接口只持久化已确认的 `material_id` 和安全导航上下文;data URL 仅在上传请求内存阶段使用,不进入节点元数据、异步任务或历史记录。
|
- 鑺傜偣缁戝畾鎺ュ彛鍙寔涔呭寲宸茬‘璁ょ殑 `material_id` 鍜屽畨鍏ㄥ鑸笂涓嬫枃锛沝ata URL 浠呭湪涓婁紶璇锋眰鍐呭瓨闃舵浣跨敤锛屼笉杩涘叆鑺傜偣鍏冩暟鎹€佸紓姝ヤ换鍔℃垨鍘嗗彶璁板綍銆?
|
||||||
- 每轮生成冻结不可变 material/reference snapshot;后续修改素材、分类或当前节点绑定不会改变历史轮次,重新打开角色会从后端恢复完整绑定集合。
|
- 姣忚疆鐢熸垚鍐荤粨涓嶅彲鍙?material/reference snapshot锛涘悗缁慨鏀圭礌鏉愩€佸垎绫绘垨褰撳墠鑺傜偣缁戝畾涓嶄細鏀瑰彉鍘嗗彶杞锛岄噸鏂版墦寮€瑙掕壊浼氫粠鍚庣鎭㈠瀹屾暣缁戝畾闆嗗悎銆?
|
||||||
- 写入统一校验资源 owner、当前分支、节点阶段与只读状态;锁定/封存节点明确提示创建分支。抽屉使用主题 token、安全背景单击关闭和移动端布局。
|
- 鍐欏叆缁熶竴鏍¢獙璧勬簮 owner銆佸綋鍓嶅垎鏀€佽妭鐐归樁娈典笌鍙鐘舵€侊紱閿佸畾/灏佸瓨鑺傜偣鏄庣‘鎻愮ず鍒涘缓鍒嗘敮銆傛娊灞変娇鐢ㄤ富棰?token銆佸畨鍏ㄨ儗鏅崟鍑诲叧闂拰绉诲姩绔竷灞€銆?
|
||||||
|
|
||||||
## [1.0.14] - 2026-07-15
|
## [1.0.14] - 2026-07-15
|
||||||
|
|
||||||
- 保留原有 VLM 视觉质检,并新增独立生成式交叉审核;审核候选强制来自不同的 image-generation provider/model,缺少配置时返回可操作的 `required_action`。
|
- 淇濈暀鍘熸湁 VLM 瑙嗚璐ㄦ锛屽苟鏂板鐙珛鐢熸垚寮忎氦鍙夊鏍革紱瀹℃牳鍊欓€夊己鍒舵潵鑷笉鍚岀殑 image-generation provider/model锛岀己灏戦厤缃椂杩斿洖鍙搷浣滅殑 `required_action`銆?
|
||||||
- 审核池始终保留 01 主候选并标注适配器/模型;后续轮只重生用户勾选项,未勾选候选与槽位保持不变,所有 review/skip/approve 操作均写入历史。
|
- 瀹℃牳姹犲缁堜繚鐣?01 涓诲€欓€夊苟鏍囨敞閫傞厤鍣?妯″瀷锛涘悗缁疆鍙噸鐢熺敤鎴峰嬀閫夐」锛屾湭鍕鹃€夊€欓€変笌妲戒綅淇濇寔涓嶅彉锛屾墍鏈?review/skip/approve 鎿嶄綔鍧囧啓鍏ュ巻鍙层€?
|
||||||
- 审核通过或跳过后,以幂等原子事务建立只读 XF 高清修复交接轮次、候选和素材快照,再推进工作流;注入失败会完整回滚,不留下半轮次或重复记录。
|
- 瀹℃牳閫氳繃鎴栬烦杩囧悗锛屼互骞傜瓑鍘熷瓙浜嬪姟寤虹珛鍙 XF 楂樻竻淇浜ゆ帴杞銆佸€欓€夊拰绱犳潗蹇収锛屽啀鎺ㄨ繘宸ヤ綔娴侊紱娉ㄥ叆澶辫触浼氬畬鏁村洖婊氾紝涓嶇暀涓嬪崐杞鎴栭噸澶嶈褰曘€?
|
||||||
- 审核决策、重生和通过接口统一接入 profile → workflow → node → round 的所有权链;前端审核弹窗使用暗色 token、安全背景单击关闭和窄屏布局。
|
- 瀹℃牳鍐崇瓥銆侀噸鐢熷拰閫氳繃鎺ュ彛缁熶竴鎺ュ叆 profile 鈫?workflow 鈫?node 鈫?round 鐨勬墍鏈夋潈閾撅紱鍓嶇瀹℃牳寮圭獥浣跨敤鏆楄壊 token銆佸畨鍏ㄨ儗鏅崟鍑诲叧闂拰绐勫睆甯冨眬銆?
|
||||||
|
|
||||||
## [1.0.15] - 2026-07-15
|
## [1.0.15] - 2026-07-15
|
||||||
|
|
||||||
- 在现有 `character_gradual` 工作流中补齐确认人设、拆解设定、预选素材、头像、上半身、下半身、全身、三视图、设定图、高清修复和档案卡共 11 个规范节点。
|
- 鍦ㄧ幇鏈?`character_gradual` 宸ヤ綔娴佷腑琛ラ綈纭浜鸿銆佹媶瑙h瀹氥€侀閫夌礌鏉愩€佸ご鍍忋€佷笂鍗婅韩銆佷笅鍗婅韩銆佸叏韬€佷笁瑙嗗浘銆佽瀹氬浘銆侀珮娓呬慨澶嶅拰妗f鍗″叡 11 涓鑼冭妭鐐广€?
|
||||||
- 保留旧节点 ID、图片与历史;`half_body / expression_sheet / pose_sheet / final_pack` 通过集中映射继续可读,旧工作流只惰性补充缺失的下半身节点。
|
- 淇濈暀鏃ц妭鐐?ID銆佸浘鐗囦笌鍘嗗彶锛沗half_body / expression_sheet / pose_sheet / final_pack` 閫氳繃闆嗕腑鏄犲皠缁х画鍙锛屾棫宸ヤ綔娴佸彧鎯版€цˉ鍏呯己澶辩殑涓嬪崐韬妭鐐广€?
|
||||||
- 前后端提示词规划、素材绑定、依赖注入、模型分工和节点展示统一使用 canonical stage catalog。
|
- 鍓嶅悗绔彁绀鸿瘝瑙勫垝銆佺礌鏉愮粦瀹氥€佷緷璧栨敞鍏ャ€佹ā鍨嬪垎宸ュ拰鑺傜偣灞曠ず缁熶竴浣跨敤 canonical stage catalog銆?
|
||||||
|
|
||||||
## [1.0.16] - 2026-07-15
|
## [1.0.16] - 2026-07-15
|
||||||
|
|
||||||
- 分支与物理节点副本改为单事务创建,校验父分支、自父、环、状态、切点和“仅已完成节点可分支”。
|
- 鍒嗘敮涓庣墿鐞嗚妭鐐瑰壇鏈敼涓哄崟浜嬪姟鍒涘缓锛屾牎楠岀埗鍒嗘敮銆佽嚜鐖躲€佺幆銆佺姸鎬併€佸垏鐐瑰拰鈥滀粎宸插畬鎴愯妭鐐瑰彲鍒嗘敮鈥濄€?
|
||||||
- 增加多层祖先解析和 branch_state 隔离;依赖上下文明确标注继承来源分支与来源节点。
|
- 澧炲姞澶氬眰绁栧厛瑙f瀽鍜?branch_state 闅旂锛涗緷璧栦笂涓嬫枃鏄庣‘鏍囨敞缁ф壙鏉ユ簮鍒嗘敮涓庢潵婧愯妭鐐广€?
|
||||||
- 工作台增加紧凑分支面板、父链/切点/状态展示和按需依赖上下文,保持三栏与移动端横向布局。
|
- 宸ヤ綔鍙板鍔犵揣鍑戝垎鏀潰鏉裤€佺埗閾?鍒囩偣/鐘舵€佸睍绀哄拰鎸夐渶渚濊禆涓婁笅鏂囷紝淇濇寔涓夋爮涓庣Щ鍔ㄧ妯悜甯冨眬銆?
|
||||||
|
|
||||||
## [1.0.17] - 2026-07-15
|
## [1.0.17] - 2026-07-15
|
||||||
|
|
||||||
- 档案卡封存改为单事务:校验活动分支与四类必填资产,同时写入卡、资产、头像、历史、档案卡节点并封存工作流。
|
- 妗f鍗″皝瀛樻敼涓哄崟浜嬪姟锛氭牎楠屾椿鍔ㄥ垎鏀笌鍥涚被蹇呭~璧勪骇锛屽悓鏃跺啓鍏ュ崱銆佽祫浜с€佸ご鍍忋€佸巻鍙层€佹。妗堝崱鑺傜偣骞跺皝瀛樺伐浣滄祦銆?
|
||||||
- 支持幂等、防跨分支串图、失败回滚,以及旧 `final_archive_*` 的只读档案卡视图。
|
- 鏀寔骞傜瓑銆侀槻璺ㄥ垎鏀覆鍥俱€佸け璐ュ洖婊氾紝浠ュ強鏃?`final_archive_*` 鐨勫彧璇绘。妗堝崱瑙嗗浘銆?
|
||||||
- 角色分类固定为未生成、快速角色、档案卡;详细工作流进度独立展示,三类列表边框、筛选和封存只读状态已接入。
|
- 瑙掕壊鍒嗙被鍥哄畾涓烘湭鐢熸垚銆佸揩閫熻鑹层€佹。妗堝崱锛涜缁嗗伐浣滄祦杩涘害鐙珛灞曠ず锛屼笁绫诲垪琛ㄨ竟妗嗐€佺瓫閫夊拰灏佸瓨鍙鐘舵€佸凡鎺ュ叆銆?
|
||||||
|
|
||||||
## [1.0.18] - 2026-07-15
|
## [1.0.18] - 2026-07-15
|
||||||
|
|
||||||
- `/影棚` 与 `/yp` 的帮助、状态、快速角色、轮次、候选、自然语言反馈、下一轮、严格单候选定稿、生成式交叉审查、素材、分支和档案卡命令逐项委托相同 canonical handler,与 Web 共用 progression/round/feedback/confirm 服务。
|
- `/褰辨` 涓?`/yp` 鐨勫府鍔┿€佺姸鎬併€佸揩閫熻鑹层€佽疆娆°€佸€欓€夈€佽嚜鐒惰瑷€鍙嶉銆佷笅涓€杞€佷弗鏍煎崟鍊欓€夊畾绋裤€佺敓鎴愬紡浜ゅ弶瀹℃煡銆佺礌鏉愩€佸垎鏀拰妗f鍗″懡浠ら€愰」濮旀墭鐩稿悓 canonical handler锛屼笌 Web 鍏辩敤 progression/round/feedback/confirm 鏈嶅姟銆?
|
||||||
- 快速角色聊天入口改为现有 `character_fast` 四图并行流;详细角色不再调用旧 select/adopt 捷径,活动分支和节点所有权由服务端校验,generation 节点无图不能空完成。
|
- 蹇€熻鑹茶亰澶╁叆鍙f敼涓虹幇鏈?`character_fast` 鍥涘浘骞惰娴侊紱璇︾粏瑙掕壊涓嶅啀璋冪敤鏃?select/adopt 鎹峰緞锛屾椿鍔ㄥ垎鏀拰鑺傜偣鎵€鏈夋潈鐢辨湇鍔$鏍¢獙锛実eneration 鑺傜偣鏃犲浘涓嶈兘绌哄畬鎴愩€?
|
||||||
- 长任务先返回入队回执;聊天 reply target 持久化到轮次,Worker 终态主动回传。重载后可恢复尚未确认的 scheduled 通知,已 delivered 的通知持久去重。
|
- 闀夸换鍔″厛杩斿洖鍏ラ槦鍥炴墽锛涜亰澶?reply target 鎸佷箙鍖栧埌杞锛學orker 缁堟€佷富鍔ㄥ洖浼犮€傞噸杞藉悗鍙仮澶嶅皻鏈‘璁ょ殑 scheduled 閫氱煡锛屽凡 delivered 鐨勯€氱煡鎸佷箙鍘婚噸銆?
|
||||||
- 单图任意白名单、快速/详细角色群聊与用户双白名单规则保持不变;知道资源 ID 也不能绕过 profile → workflow → node → round 所有权链。
|
- 鍗曞浘浠绘剰鐧藉悕鍗曘€佸揩閫?璇︾粏瑙掕壊缇よ亰涓庣敤鎴峰弻鐧藉悕鍗曡鍒欎繚鎸佷笉鍙橈紱鐭ラ亾璧勬簮 ID 涔熶笉鑳界粫杩?profile 鈫?workflow 鈫?node 鈫?round 鎵€鏈夋潈閾俱€?
|
||||||
- 帮助与状态优先返回运行时生成的图片卡,渲染或平台能力不足时自动回退为文本,不会阻塞命令处理。
|
- 甯姪涓庣姸鎬佷紭鍏堣繑鍥炶繍琛屾椂鐢熸垚鐨勫浘鐗囧崱锛屾覆鏌撴垨骞冲彴鑳藉姏涓嶈冻鏃惰嚜鍔ㄥ洖閫€涓烘枃鏈紝涓嶄細闃诲鍛戒护澶勭悊銆?
|
||||||
|
|
||||||
## [1.0.19] - 2026-07-15
|
## [1.0.19] - 2026-07-15
|
||||||
|
|
||||||
- 保留现有三栏工作台并抽出 `WorkflowComposer`;catalog、轮次、候选池、比较、确认、素材、分支与依赖面板继续使用单一组件实现,删除详细工作流对全局单图模型选择的耦合。
|
- 淇濈暀鐜版湁涓夋爮宸ヤ綔鍙板苟鎶藉嚭 `WorkflowComposer`锛沜atalog銆佽疆娆°€佸€欓€夋睜銆佹瘮杈冦€佺‘璁ゃ€佺礌鏉愩€佸垎鏀笌渚濊禆闈㈡澘缁х画浣跨敤鍗曚竴缁勪欢瀹炵幇锛屽垹闄よ缁嗗伐浣滄祦瀵瑰叏灞€鍗曞浘妯″瀷閫夋嫨鐨勮€﹀悎銆?
|
||||||
- 工作流生图路由按“显式覆盖 → 父轮次 → 节点 → 模型分工 → 角色默认 → 系统默认”展示;首轮和下一轮仅在用户明确覆盖时发送 `model_route`,继承时请求体不包含该字段。
|
- 宸ヤ綔娴佺敓鍥捐矾鐢辨寜鈥滄樉寮忚鐩?鈫?鐖惰疆娆?鈫?鑺傜偣 鈫?妯″瀷鍒嗗伐 鈫?瑙掕壊榛樿 鈫?绯荤粺榛樿鈥濆睍绀猴紱棣栬疆鍜屼笅涓€杞粎鍦ㄧ敤鎴锋槑纭鐩栨椂鍙戦€?`model_route`锛岀户鎵挎椂璇锋眰浣撲笉鍖呭惈璇ュ瓧娈点€?
|
||||||
- Composer 同时显示实际生图模型、继承来源与提示词规划 LLM;文本 LLM 优先使用 translation 治理路由,再回退到 prompt_planning 分工,并显示适配器/模型友好名。
|
- Composer 鍚屾椂鏄剧ず瀹為檯鐢熷浘妯″瀷銆佺户鎵挎潵婧愪笌鎻愮ず璇嶈鍒?LLM锛涙枃鏈?LLM 浼樺厛浣跨敤 translation 娌荤悊璺敱锛屽啀鍥為€€鍒?prompt_planning 鍒嗗伐锛屽苟鏄剧ず閫傞厤鍣?妯″瀷鍙嬪ソ鍚嶃€?
|
||||||
- 修正节点锁语义:生成完成但未最终采用的 `completed` 节点仍可反馈、创建下一轮和修改节点素材;仅 `selected`、未来节点及封存/归档工作流写锁。
|
- 淇鑺傜偣閿佽涔夛細鐢熸垚瀹屾垚浣嗘湭鏈€缁堥噰鐢ㄧ殑 `completed` 鑺傜偣浠嶅彲鍙嶉銆佸垱寤轰笅涓€杞拰淇敼鑺傜偣绱犳潗锛涗粎 `selected`銆佹湭鏉ヨ妭鐐瑰強灏佸瓨/褰掓。宸ヤ綔娴佸啓閿併€?
|
||||||
- 历史轮次默认显示最近三轮并可展开;终态历史不重复请求,事件只刷新当前页面和可见活动轮次。头像使用 cover,全身/三视图/设定图使用 contain。
|
- 鍘嗗彶杞榛樿鏄剧ず鏈€杩戜笁杞苟鍙睍寮€锛涚粓鎬佸巻鍙蹭笉閲嶅璇锋眰锛屼簨浠跺彧鍒锋柊褰撳墠椤甸潰鍜屽彲瑙佹椿鍔ㄨ疆娆°€傚ご鍍忎娇鐢?cover锛屽叏韬?涓夎鍥?璁惧畾鍥句娇鐢?contain銆?
|
||||||
- 所有新增浮层使用主题 token 和安全背景单击关闭;窄屏 Composer、按钮布局、空状态、部分成功、错误与重试提示完成回归。
|
- 鎵€鏈夋柊澧炴诞灞備娇鐢ㄤ富棰?token 鍜屽畨鍏ㄨ儗鏅崟鍑诲叧闂紱绐勫睆 Composer銆佹寜閽竷灞€銆佺┖鐘舵€併€侀儴鍒嗘垚鍔熴€侀敊璇笌閲嶈瘯鎻愮ず瀹屾垚鍥炲綊銆?
|
||||||
|
|
||||||
## [1.0.8] - 2026-07-15
|
## [1.0.8] - 2026-07-15
|
||||||
|
|
||||||
- 详细角色工作流支持逐节点解锁:锁定节点可查看,只有当前节点可操作。
|
- 璇︾粏瑙掕壊宸ヤ綔娴佹敮鎸侀€愯妭鐐硅В閿侊細閿佸畾鑺傜偣鍙煡鐪嬶紝鍙湁褰撳墠鑺傜偣鍙搷浣溿€?
|
||||||
- 前后端增加防越级校验;生图节点必须采用图片后才能推进。
|
- 鍓嶅悗绔鍔犻槻瓒婄骇鏍¢獙锛涚敓鍥捐妭鐐瑰繀椤婚噰鐢ㄥ浘鐗囧悗鎵嶈兘鎺ㄨ繘銆?
|
||||||
- 提示词规划、素材绑定保存与确认分离,并兼容旧工作流数据。
|
- 鎻愮ず璇嶈鍒掋€佺礌鏉愮粦瀹氫繚瀛樹笌纭鍒嗙锛屽苟鍏煎鏃у伐浣滄祦鏁版嵁銆?
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,18 @@
|
||||||
"default": true
|
"default": true
|
||||||
},
|
},
|
||||||
"model_material_recognition": {"description":"素材导入解析使用的 Vision 路由。","type":"string","default":"material_vlm"},
|
"model_material_recognition": {"description":"素材导入解析使用的 Vision 路由。","type":"string","default":"material_vlm"},
|
||||||
|
"model_advanced_style_consensus": {"description":"\u8fdb\u9636\u753b\u98ce\u591a\u56fe\u4ea4\u53c9\u5f52\u7eb3\u4f7f\u7528\u7684 Vision \u8def\u7531\uff1b\u7559\u7a7a\u65f6\u6cbf\u7528\u8fdb\u9636\u7d20\u6750\u8bc6\u522b\u8def\u7531\u3002","type":"string","default":""},
|
||||||
|
"model_advanced_material_recognition": {"description":"进阶素材导入与高保真特征提取使用的 Vision 路由。","type":"string","default":"material_vlm"},
|
||||||
|
"model_advanced_material_validation_generation": {"description":"进阶素材还原度验证图使用的生图路由。留空时回退到默认生图路由。","type":"string","default":""},
|
||||||
|
"advanced_material_budget_enabled": {"description":"启用进阶素材验证图预算守卫。","type":"bool","default":false},
|
||||||
|
"advanced_material_budget_days": {"description":"进阶素材预算统计窗口天数。","type":"int","default":30},
|
||||||
|
"advanced_material_budget_max_task_count": {"description":"窗口内最大验证任务数;留空表示不限。","type":"string","default":""},
|
||||||
|
"advanced_material_budget_max_image_count": {"description":"窗口内最大验证图片数;留空表示不限。","type":"string","default":""},
|
||||||
|
"advanced_material_budget_max_estimated_cost": {"description":"窗口内最大估算费用;留空表示不限。","type":"string","default":""},
|
||||||
|
"advanced_material_budget_price_key": {"description":"成本计价键,可填写 Provider ID 或模型 ID。","type":"string","default":""},
|
||||||
|
"advanced_material_budget_per_request": {"description":"每次验证请求的估算单价。","type":"string","default":"0"},
|
||||||
|
"advanced_material_budget_per_image": {"description":"每张验证图片的估算单价。","type":"string","default":"0"},
|
||||||
|
"advanced_material_budget_per_1k_tokens": {"description":"每千 Token 的估算单价。","type":"string","default":"0"},
|
||||||
"model_profile_parse": {"description":"外部角色导入解析使用的文本模型路由。","type":"string","default":""},
|
"model_profile_parse": {"description":"外部角色导入解析使用的文本模型路由。","type":"string","default":""},
|
||||||
"model_persona_split": {"description":"角色设定拆解使用的文本模型路由。","type":"string","default":""},
|
"model_persona_split": {"description":"角色设定拆解使用的文本模型路由。","type":"string","default":""},
|
||||||
"model_prompt_planning": {"description":"提示词规划与扩写使用的文本模型路由。","type":"string","default":""},
|
"model_prompt_planning": {"description":"提示词规划与扩写使用的文本模型路由。","type":"string","default":""},
|
||||||
|
|
@ -119,6 +131,11 @@
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "data/db/imagestudio.db"
|
"default": "data/db/imagestudio.db"
|
||||||
},
|
},
|
||||||
|
"advanced_materials_path": {
|
||||||
|
"description": "进阶素材原图、验证图与封存文件的独立逻辑目录。",
|
||||||
|
"type": "string",
|
||||||
|
"default": "data/advanced_materials"
|
||||||
|
},
|
||||||
"postgresql_enabled": {
|
"postgresql_enabled": {
|
||||||
"description": "启用 PostgreSQL。填写 DSN 或主机/库名/用户后也会自动按 PG 配置运行。",
|
"description": "启用 PostgreSQL。填写 DSN 或主机/库名/用户后也会自动按 PG 配置运行。",
|
||||||
"type": "bool",
|
"type": "bool",
|
||||||
|
|
|
||||||
326
backend/dto/advanced_material_dto.py
普通文件
326
backend/dto/advanced_material_dto.py
普通文件
|
|
@ -0,0 +1,326 @@
|
||||||
|
"""DTOs for the isolated advanced-material verification library."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AdvancedMaterialImport:
|
||||||
|
import_id: str
|
||||||
|
category_id: str | None
|
||||||
|
display_name: str
|
||||||
|
source_image_uri: str
|
||||||
|
source_thumbnail_uri: str | None
|
||||||
|
status: str
|
||||||
|
recognition_prompt: str | None
|
||||||
|
recognition_negative_prompt: str | None
|
||||||
|
recognition_tags: list[str]
|
||||||
|
recognition_result: dict[str, Any]
|
||||||
|
recognition_model_route: str | None
|
||||||
|
prompt_revision: int
|
||||||
|
current_attempt_id: str | None
|
||||||
|
accepted_material_id: str | None
|
||||||
|
idempotency_key: str | None
|
||||||
|
created_by: str | None
|
||||||
|
error: dict[str, Any]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
created_at: str
|
||||||
|
updated_at: str
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"import_id": self.import_id,
|
||||||
|
"category_id": self.category_id,
|
||||||
|
"display_name": self.display_name,
|
||||||
|
"source_image_uri": self.source_image_uri,
|
||||||
|
"source_thumbnail_uri": self.source_thumbnail_uri,
|
||||||
|
"status": self.status,
|
||||||
|
"recognition_prompt": self.recognition_prompt,
|
||||||
|
"recognition_negative_prompt": self.recognition_negative_prompt,
|
||||||
|
"recognition_tags": list(self.recognition_tags),
|
||||||
|
"recognition_result": dict(self.recognition_result),
|
||||||
|
"recognition_model_route": self.recognition_model_route,
|
||||||
|
"prompt_revision": self.prompt_revision,
|
||||||
|
"current_attempt_id": self.current_attempt_id,
|
||||||
|
"accepted_material_id": self.accepted_material_id,
|
||||||
|
"idempotency_key": self.idempotency_key,
|
||||||
|
"created_by": self.created_by,
|
||||||
|
"error": dict(self.error),
|
||||||
|
"metadata": dict(self.metadata),
|
||||||
|
"created_at": self.created_at,
|
||||||
|
"updated_at": self.updated_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AdvancedMaterialValidationAttempt:
|
||||||
|
attempt_id: str
|
||||||
|
import_id: str
|
||||||
|
attempt_number: int
|
||||||
|
status: str
|
||||||
|
adjustment_text: str | None
|
||||||
|
prompt: str
|
||||||
|
negative_prompt: str | None
|
||||||
|
model_route: str | None
|
||||||
|
provider_id: str | None
|
||||||
|
provider_model: str | None
|
||||||
|
task_id: str | None
|
||||||
|
validation_image_uri: str | None
|
||||||
|
validation_thumbnail_uri: str | None
|
||||||
|
seed: int | None
|
||||||
|
width: int | None
|
||||||
|
height: int | None
|
||||||
|
usage: dict[str, Any]
|
||||||
|
fidelity_score: float | None
|
||||||
|
decision: str | None
|
||||||
|
decision_notes: str | None
|
||||||
|
error: dict[str, Any]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
created_at: str
|
||||||
|
updated_at: str
|
||||||
|
completed_at: str | None
|
||||||
|
decided_at: str | None
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"attempt_id": self.attempt_id,
|
||||||
|
"import_id": self.import_id,
|
||||||
|
"attempt_number": self.attempt_number,
|
||||||
|
"status": self.status,
|
||||||
|
"adjustment_text": self.adjustment_text,
|
||||||
|
"prompt": self.prompt,
|
||||||
|
"negative_prompt": self.negative_prompt,
|
||||||
|
"model_route": self.model_route,
|
||||||
|
"provider_id": self.provider_id,
|
||||||
|
"provider_model": self.provider_model,
|
||||||
|
"task_id": self.task_id,
|
||||||
|
"validation_image_uri": self.validation_image_uri,
|
||||||
|
"validation_thumbnail_uri": self.validation_thumbnail_uri,
|
||||||
|
"seed": self.seed,
|
||||||
|
"width": self.width,
|
||||||
|
"height": self.height,
|
||||||
|
"usage": dict(self.usage),
|
||||||
|
"fidelity_score": self.fidelity_score,
|
||||||
|
"decision": self.decision,
|
||||||
|
"decision_notes": self.decision_notes,
|
||||||
|
"error": dict(self.error),
|
||||||
|
"metadata": dict(self.metadata),
|
||||||
|
"created_at": self.created_at,
|
||||||
|
"updated_at": self.updated_at,
|
||||||
|
"completed_at": self.completed_at,
|
||||||
|
"decided_at": self.decided_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AdvancedStyleSource:
|
||||||
|
source_id: str
|
||||||
|
import_id: str
|
||||||
|
sort_order: int
|
||||||
|
is_primary: bool
|
||||||
|
source_image_uri: str
|
||||||
|
source_thumbnail_uri: str | None
|
||||||
|
status: str
|
||||||
|
recognition_model_route: str | None
|
||||||
|
provider_id: str | None
|
||||||
|
provider_model: str | None
|
||||||
|
task_id: str | None
|
||||||
|
recognition_prompt: str | None
|
||||||
|
recognition_negative_prompt: str | None
|
||||||
|
recognition_tags: list[str]
|
||||||
|
recognition_result: dict[str, Any]
|
||||||
|
error: dict[str, Any]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
created_at: str
|
||||||
|
updated_at: str
|
||||||
|
completed_at: str | None
|
||||||
|
excluded_at: str | None
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"source_id": self.source_id,
|
||||||
|
"import_id": self.import_id,
|
||||||
|
"sort_order": self.sort_order,
|
||||||
|
"is_primary": self.is_primary,
|
||||||
|
"source_image_uri": self.source_image_uri,
|
||||||
|
"source_thumbnail_uri": self.source_thumbnail_uri,
|
||||||
|
"status": self.status,
|
||||||
|
"recognition_model_route": self.recognition_model_route,
|
||||||
|
"provider_id": self.provider_id,
|
||||||
|
"provider_model": self.provider_model,
|
||||||
|
"task_id": self.task_id,
|
||||||
|
"recognition_prompt": self.recognition_prompt,
|
||||||
|
"recognition_negative_prompt": self.recognition_negative_prompt,
|
||||||
|
"recognition_tags": list(self.recognition_tags),
|
||||||
|
"recognition_result": dict(self.recognition_result),
|
||||||
|
"error": dict(self.error),
|
||||||
|
"metadata": dict(self.metadata),
|
||||||
|
"created_at": self.created_at,
|
||||||
|
"updated_at": self.updated_at,
|
||||||
|
"completed_at": self.completed_at,
|
||||||
|
"excluded_at": self.excluded_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AdvancedStyleConsensusRun:
|
||||||
|
consensus_id: str
|
||||||
|
import_id: str
|
||||||
|
revision: int
|
||||||
|
status: str
|
||||||
|
task_id: str | None
|
||||||
|
model_route: str | None
|
||||||
|
provider_id: str | None
|
||||||
|
provider_model: str | None
|
||||||
|
source_ids: list[str]
|
||||||
|
prompt: str | None
|
||||||
|
negative_prompt: str | None
|
||||||
|
tags: list[str]
|
||||||
|
result: dict[str, Any]
|
||||||
|
error: dict[str, Any]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
created_at: str
|
||||||
|
updated_at: str
|
||||||
|
completed_at: str | None
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"consensus_id": self.consensus_id,
|
||||||
|
"import_id": self.import_id,
|
||||||
|
"revision": self.revision,
|
||||||
|
"status": self.status,
|
||||||
|
"task_id": self.task_id,
|
||||||
|
"model_route": self.model_route,
|
||||||
|
"provider_id": self.provider_id,
|
||||||
|
"provider_model": self.provider_model,
|
||||||
|
"source_ids": list(self.source_ids),
|
||||||
|
"prompt": self.prompt,
|
||||||
|
"negative_prompt": self.negative_prompt,
|
||||||
|
"tags": list(self.tags),
|
||||||
|
"result": dict(self.result),
|
||||||
|
"error": dict(self.error),
|
||||||
|
"metadata": dict(self.metadata),
|
||||||
|
"created_at": self.created_at,
|
||||||
|
"updated_at": self.updated_at,
|
||||||
|
"completed_at": self.completed_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AdvancedStyleValidationCase:
|
||||||
|
case_id: str
|
||||||
|
attempt_id: str
|
||||||
|
import_id: str
|
||||||
|
case_key: str
|
||||||
|
sort_order: int
|
||||||
|
status: str
|
||||||
|
task_id: str | None
|
||||||
|
content_prompt: str
|
||||||
|
final_prompt: str
|
||||||
|
negative_prompt: str | None
|
||||||
|
model_route: str | None
|
||||||
|
provider_id: str | None
|
||||||
|
provider_model: str | None
|
||||||
|
seed: int | None
|
||||||
|
width: int | None
|
||||||
|
height: int | None
|
||||||
|
validation_image_uri: str | None
|
||||||
|
validation_thumbnail_uri: str | None
|
||||||
|
usage: dict[str, Any]
|
||||||
|
style_review: dict[str, Any]
|
||||||
|
fidelity_score: float | None
|
||||||
|
error: dict[str, Any]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
created_at: str
|
||||||
|
updated_at: str
|
||||||
|
completed_at: str | None
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
metadata = dict(self.metadata)
|
||||||
|
applied = bool(metadata.get("reference_image_applied"))
|
||||||
|
if "input_image_count" in metadata:
|
||||||
|
try:
|
||||||
|
input_image_count = int(metadata.get("input_image_count") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
input_image_count = 1 if applied else 0
|
||||||
|
else:
|
||||||
|
input_image_count = 1 if applied else (1 if metadata.get("validation_reference_enabled") and metadata.get("validation_reference_source_uri") else 0)
|
||||||
|
return {
|
||||||
|
"case_id": self.case_id,
|
||||||
|
"attempt_id": self.attempt_id,
|
||||||
|
"import_id": self.import_id,
|
||||||
|
"case_key": self.case_key,
|
||||||
|
"sort_order": self.sort_order,
|
||||||
|
"status": self.status,
|
||||||
|
"task_id": self.task_id,
|
||||||
|
"content_prompt": self.content_prompt,
|
||||||
|
"final_prompt": self.final_prompt,
|
||||||
|
"negative_prompt": self.negative_prompt,
|
||||||
|
"model_route": self.model_route,
|
||||||
|
"provider_id": self.provider_id,
|
||||||
|
"provider_model": self.provider_model,
|
||||||
|
"seed": self.seed,
|
||||||
|
"width": self.width,
|
||||||
|
"height": self.height,
|
||||||
|
"validation_image_uri": self.validation_image_uri,
|
||||||
|
"validation_thumbnail_uri": self.validation_thumbnail_uri,
|
||||||
|
"usage": dict(self.usage),
|
||||||
|
"style_review": dict(self.style_review),
|
||||||
|
"fidelity_score": self.fidelity_score,
|
||||||
|
"error": dict(self.error),
|
||||||
|
"metadata": metadata,
|
||||||
|
"input_image_count": input_image_count,
|
||||||
|
"created_at": self.created_at,
|
||||||
|
"updated_at": self.updated_at,
|
||||||
|
"completed_at": self.completed_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AdvancedMaterial:
|
||||||
|
material_id: str
|
||||||
|
import_id: str
|
||||||
|
accepted_attempt_id: str
|
||||||
|
category_id: str | None
|
||||||
|
display_name: str
|
||||||
|
source_image_uri: str
|
||||||
|
source_thumbnail_uri: str | None
|
||||||
|
validation_image_uri: str
|
||||||
|
validation_thumbnail_uri: str | None
|
||||||
|
prompt: str
|
||||||
|
negative_prompt: str | None
|
||||||
|
tags: list[str]
|
||||||
|
priority: int
|
||||||
|
status: str
|
||||||
|
capsule: dict[str, Any]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
accepted_at: str
|
||||||
|
archived_at: str | None
|
||||||
|
created_at: str
|
||||||
|
updated_at: str
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"material_id": self.material_id,
|
||||||
|
"import_id": self.import_id,
|
||||||
|
"accepted_attempt_id": self.accepted_attempt_id,
|
||||||
|
"category_id": self.category_id,
|
||||||
|
"display_name": self.display_name,
|
||||||
|
"source_image_uri": self.source_image_uri,
|
||||||
|
"source_thumbnail_uri": self.source_thumbnail_uri,
|
||||||
|
"validation_image_uri": self.validation_image_uri,
|
||||||
|
"validation_thumbnail_uri": self.validation_thumbnail_uri,
|
||||||
|
"prompt": self.prompt,
|
||||||
|
"negative_prompt": self.negative_prompt,
|
||||||
|
"tags": list(self.tags),
|
||||||
|
"priority": self.priority,
|
||||||
|
"status": self.status,
|
||||||
|
"capsule": dict(self.capsule),
|
||||||
|
"metadata": dict(self.metadata),
|
||||||
|
"accepted_at": self.accepted_at,
|
||||||
|
"archived_at": self.archived_at,
|
||||||
|
"created_at": self.created_at,
|
||||||
|
"updated_at": self.updated_at,
|
||||||
|
}
|
||||||
|
|
@ -20,6 +20,7 @@ class WardrobeItem:
|
||||||
last_used_at: str | None
|
last_used_at: str | None
|
||||||
created_at: str
|
created_at: str
|
||||||
updated_at: str
|
updated_at: str
|
||||||
|
library_kind: str = "standard"
|
||||||
|
|
||||||
def to_dict(self) -> dict[str, Any]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
return {
|
return {
|
||||||
|
|
@ -35,4 +36,5 @@ class WardrobeItem:
|
||||||
"last_used_at": self.last_used_at,
|
"last_used_at": self.last_used_at,
|
||||||
"created_at": self.created_at,
|
"created_at": self.created_at,
|
||||||
"updated_at": self.updated_at,
|
"updated_at": self.updated_at,
|
||||||
|
"library_kind": self.library_kind,
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -139,6 +139,7 @@ ROUTES: tuple[RouteSpec, ...] = (
|
||||||
RouteSpec("DELETE", "jobs/{task_id}", "backend.routes.job_routes.delete_job", "retry"),
|
RouteSpec("DELETE", "jobs/{task_id}", "backend.routes.job_routes.delete_job", "retry"),
|
||||||
RouteSpec("POST", "jobs/{task_id}/cancel", "backend.routes.job_routes.cancel_job", "write"),
|
RouteSpec("POST", "jobs/{task_id}/cancel", "backend.routes.job_routes.cancel_job", "write"),
|
||||||
RouteSpec("POST", "jobs/{task_id}/retry", "backend.routes.job_routes.retry_job", "retry"),
|
RouteSpec("POST", "jobs/{task_id}/retry", "backend.routes.job_routes.retry_job", "retry"),
|
||||||
|
RouteSpec("POST", "jobs/failed/retry", "backend.routes.job_routes.retry_failed_jobs", "retry"),
|
||||||
RouteSpec("POST", "jobs/failed/clear", "backend.routes.job_routes.clear_failed_jobs", "retry"),
|
RouteSpec("POST", "jobs/failed/clear", "backend.routes.job_routes.clear_failed_jobs", "retry"),
|
||||||
RouteSpec("POST", "jobs/terminal/clear", "backend.routes.job_routes.clear_terminal_jobs", "retry"),
|
RouteSpec("POST", "jobs/terminal/clear", "backend.routes.job_routes.clear_terminal_jobs", "retry"),
|
||||||
RouteSpec("POST", "jobs/dead-letter/retry", "backend.routes.job_routes.retry_dead_letter_jobs", "retry"),
|
RouteSpec("POST", "jobs/dead-letter/retry", "backend.routes.job_routes.retry_dead_letter_jobs", "retry"),
|
||||||
|
|
@ -168,6 +169,110 @@ ROUTES: tuple[RouteSpec, ...] = (
|
||||||
RouteSpec("GET", "media/orphans", "backend.routes.media_routes.scan_orphan_media", "read"),
|
RouteSpec("GET", "media/orphans", "backend.routes.media_routes.scan_orphan_media", "read"),
|
||||||
RouteSpec("GET", "media/payload", "backend.routes.media_routes.fetch_media_payload", "read"),
|
RouteSpec("GET", "media/payload", "backend.routes.media_routes.fetch_media_payload", "read"),
|
||||||
RouteSpec("GET", "media/fetch", "backend.routes.media_routes.fetch_media", "public_token"),
|
RouteSpec("GET", "media/fetch", "backend.routes.media_routes.fetch_media", "public_token"),
|
||||||
|
RouteSpec(
|
||||||
|
"GET",
|
||||||
|
"advanced-material-imports",
|
||||||
|
"backend.routes.advanced_material_routes.list_advanced_material_imports",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/upload",
|
||||||
|
"backend.routes.advanced_material_routes.upload_advanced_material",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/style-set/upload",
|
||||||
|
"backend.routes.advanced_material_routes.upload_advanced_style_set",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"GET",
|
||||||
|
"advanced-material-imports/{import_id}",
|
||||||
|
"backend.routes.advanced_material_routes.get_advanced_material_import",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"DELETE",
|
||||||
|
"advanced-material-imports/{import_id}",
|
||||||
|
"backend.routes.advanced_material_routes.delete_advanced_material_import",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/retry",
|
||||||
|
"backend.routes.advanced_material_routes.retry_advanced_material_import",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/style-sources/{source_id}/retry",
|
||||||
|
"backend.routes.advanced_material_routes.retry_advanced_style_source",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/style-sources/{source_id}/exclude",
|
||||||
|
"backend.routes.advanced_material_routes.exclude_advanced_style_source",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/style-consensus",
|
||||||
|
"backend.routes.advanced_material_routes.create_advanced_style_consensus",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/style-validation-cases/{case_id}/retry",
|
||||||
|
"backend.routes.advanced_material_routes.retry_advanced_style_validation_case",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/cancel",
|
||||||
|
"backend.routes.advanced_material_routes.cancel_advanced_material_import",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"GET",
|
||||||
|
"advanced-material-imports/{import_id}/validation-attempts",
|
||||||
|
"backend.routes.advanced_material_routes.list_advanced_material_attempts",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/validation-attempts",
|
||||||
|
"backend.routes.advanced_material_routes.create_advanced_material_attempt",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/attempts/{attempt_id}/reject",
|
||||||
|
"backend.routes.advanced_material_routes.reject_advanced_material_attempt",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"POST",
|
||||||
|
"advanced-material-imports/{import_id}/attempts/{attempt_id}/accept",
|
||||||
|
"backend.routes.advanced_material_routes.accept_advanced_material_attempt",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec("GET", "advanced-materials", "backend.routes.advanced_material_routes.list_advanced_materials", "read"),
|
||||||
|
RouteSpec(
|
||||||
|
"GET",
|
||||||
|
"advanced-materials/{material_id}",
|
||||||
|
"backend.routes.advanced_material_routes.get_advanced_material",
|
||||||
|
"read",
|
||||||
|
),
|
||||||
|
RouteSpec(
|
||||||
|
"DELETE",
|
||||||
|
"advanced-materials/{material_id}",
|
||||||
|
"backend.routes.advanced_material_routes.archive_advanced_material",
|
||||||
|
"materials",
|
||||||
|
),
|
||||||
|
RouteSpec("GET", "material-catalog", "backend.routes.advanced_material_routes.list_material_catalog", "read"),
|
||||||
RouteSpec("GET", "material-categories", "backend.routes.material_routes.list_material_categories", "read"),
|
RouteSpec("GET", "material-categories", "backend.routes.material_routes.list_material_categories", "read"),
|
||||||
RouteSpec("POST", "material-categories", "backend.routes.material_routes.create_material_category", "materials"),
|
RouteSpec("POST", "material-categories", "backend.routes.material_routes.create_material_category", "materials"),
|
||||||
RouteSpec(
|
RouteSpec(
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,435 @@
|
||||||
|
"""HTTP handlers for the isolated advanced-material workflow."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from backend.routes.common import handle_request
|
||||||
|
from backend.routes.params import int_or_default, optional_str
|
||||||
|
from backend.services.advanced_material_service import (
|
||||||
|
AdvancedMaterialService,
|
||||||
|
create_advanced_material_service,
|
||||||
|
)
|
||||||
|
from backend.services.media_service import MediaService
|
||||||
|
from core.identity import RequestContext
|
||||||
|
from core.security import require_authenticated, require_permission
|
||||||
|
|
||||||
|
|
||||||
|
def list_advanced_material_imports(
|
||||||
|
ctx: RequestContext,
|
||||||
|
query: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
params = query or {}
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
payload = resolved.list_imports(
|
||||||
|
status=optional_str(params.get("status")),
|
||||||
|
page=int_or_default(params.get("page"), 1),
|
||||||
|
page_size=int_or_default(params.get("page_size"), 30),
|
||||||
|
)
|
||||||
|
return _serialize_import_list(payload)
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def upload_advanced_material(
|
||||||
|
ctx: RequestContext,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.upload(payload or {}, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def upload_advanced_style_set(
|
||||||
|
ctx: RequestContext,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""Create one style-only multi-image import and enqueue every source."""
|
||||||
|
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.upload_style_set(payload or {}, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def get_advanced_material_import(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.get_import(import_id))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_advanced_material_import(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return resolved.delete_import(import_id, ctx)
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def retry_advanced_material_import(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
del payload
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.retry_import(import_id, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def retry_advanced_style_source(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
source_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
del payload
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.retry_style_source(import_id, source_id, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def exclude_advanced_style_source(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
source_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
excluded = bool((payload or {}).get("excluded", True))
|
||||||
|
return _serialize_payload(resolved.exclude_style_source(import_id, source_id, excluded, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def create_advanced_style_consensus(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.create_style_consensus(import_id, payload or {}, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def retry_advanced_style_validation_case(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
case_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
del payload
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.retry_style_validation_case(import_id, case_id, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_advanced_material_import(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
del payload
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.cancel_import(import_id, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def list_advanced_material_attempts(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
query: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
del query
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> list[dict[str, Any]]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return [_serialize_attempt(item) for item in resolved.list_attempts(import_id)]
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def create_advanced_material_attempt(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.create_validation_attempt(import_id, payload or {}, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def reject_advanced_material_attempt(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
attempt_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.reject_attempt(import_id, attempt_id, payload or {}, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def accept_advanced_material_attempt(
|
||||||
|
ctx: RequestContext,
|
||||||
|
import_id: str,
|
||||||
|
attempt_id: str,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_payload(resolved.accept_attempt(import_id, attempt_id, payload or {}, ctx))
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def list_advanced_materials(
|
||||||
|
ctx: RequestContext,
|
||||||
|
query: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
params = query or {}
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_authenticated(ctx)
|
||||||
|
payload = resolved.list_materials(
|
||||||
|
page=int_or_default(params.get("page"), 1),
|
||||||
|
page_size=int_or_default(params.get("page_size"), 30),
|
||||||
|
)
|
||||||
|
return _serialize_material_list(payload)
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def get_advanced_material(
|
||||||
|
ctx: RequestContext,
|
||||||
|
material_id: str,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_authenticated(ctx)
|
||||||
|
return _serialize_material(resolved.get_material(material_id).to_dict())
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def archive_advanced_material(
|
||||||
|
ctx: RequestContext,
|
||||||
|
material_id: str,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return _serialize_material(resolved.archive_material(material_id, ctx).to_dict())
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def list_material_catalog(
|
||||||
|
ctx: RequestContext,
|
||||||
|
query: dict[str, Any] | None = None,
|
||||||
|
service: AdvancedMaterialService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
resolved = service or create_advanced_material_service()
|
||||||
|
params = query or {}
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_authenticated(ctx)
|
||||||
|
payload = resolved.list_catalog(
|
||||||
|
page=int_or_default(params.get("page"), 1),
|
||||||
|
page_size=int_or_default(params.get("page_size"), 100),
|
||||||
|
)
|
||||||
|
payload["items"] = [
|
||||||
|
_serialize_material(item) if item.get("library_kind") == "advanced" else _serialize_standard_material(item)
|
||||||
|
for item in payload.get("items", [])
|
||||||
|
]
|
||||||
|
return payload
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_import_list(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"items": [_serialize_import(item) for item in payload.get("items", [])],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_material_list(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"items": [_serialize_material(item) for item in payload.get("items", [])],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_payload(payload: Any) -> Any:
|
||||||
|
if isinstance(payload, list):
|
||||||
|
return [_serialize_payload(item) for item in payload]
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return payload
|
||||||
|
result = {key: _serialize_payload(value) for key, value in payload.items()}
|
||||||
|
if "source_id" in result and "source_image_uri" in result:
|
||||||
|
return _serialize_style_source(result)
|
||||||
|
if "case_id" in result and "validation_image_uri" in result:
|
||||||
|
return _serialize_style_validation_case(result)
|
||||||
|
if "import_id" in result and "source_image_uri" in result:
|
||||||
|
return _serialize_import(result)
|
||||||
|
if "attempt_id" in result and "validation_image_uri" in result:
|
||||||
|
return _serialize_attempt(result)
|
||||||
|
if str(result.get("material_id") or "").startswith("advmat_"):
|
||||||
|
return _serialize_material(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_import(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"source_image_url": _signed_url(payload.get("source_image_uri")),
|
||||||
|
"source_thumbnail_url": _signed_url(payload.get("source_thumbnail_uri")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_attempt(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
**(
|
||||||
|
{
|
||||||
|
"validation_cases": [
|
||||||
|
_serialize_style_validation_case(item)
|
||||||
|
for item in payload.get("validation_cases", [])
|
||||||
|
if isinstance(item, dict)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
if isinstance(payload.get("validation_cases"), list)
|
||||||
|
else {}
|
||||||
|
),
|
||||||
|
"validation_image_url": _signed_url(payload.get("validation_image_uri")),
|
||||||
|
"validation_thumbnail_url": _signed_url(payload.get("validation_thumbnail_uri")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_style_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"source_image_url": _signed_url(payload.get("source_image_uri")),
|
||||||
|
"source_thumbnail_url": _signed_url(payload.get("source_thumbnail_uri")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_style_validation_case(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"validation_image_url": _signed_url(payload.get("validation_image_uri")),
|
||||||
|
"validation_thumbnail_url": _signed_url(payload.get("validation_thumbnail_uri")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_material(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"library_kind": "advanced",
|
||||||
|
"source_image_url": _signed_url(payload.get("source_image_uri")),
|
||||||
|
"source_thumbnail_url": _signed_url(payload.get("source_thumbnail_uri")),
|
||||||
|
"validation_image_url": _signed_url(payload.get("validation_image_uri")),
|
||||||
|
"validation_thumbnail_url": _signed_url(payload.get("validation_thumbnail_uri")),
|
||||||
|
"image_uri": payload.get("source_image_uri"),
|
||||||
|
"thumbnail_uri": payload.get("source_thumbnail_uri"),
|
||||||
|
"image_url": _signed_url(payload.get("source_image_uri")),
|
||||||
|
"thumbnail_url": _signed_url(payload.get("source_thumbnail_uri")),
|
||||||
|
"recognition_status": "confirmed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_standard_material(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
**payload,
|
||||||
|
"library_kind": "standard",
|
||||||
|
"image_url": _signed_url(payload.get("image_uri")),
|
||||||
|
"thumbnail_url": _signed_url(payload.get("thumbnail_uri")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _signed_url(uri: Any) -> str | None:
|
||||||
|
text = str(uri or "").strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return MediaService().sign_media(text)["url"]
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
@ -7,16 +7,18 @@ from typing import Any
|
||||||
from backend.routes.common import handle_request
|
from backend.routes.common import handle_request
|
||||||
from backend.services.integration_service import IntegrationService
|
from backend.services.integration_service import IntegrationService
|
||||||
from backend.services.integration_token_service import IntegrationTokenService
|
from backend.services.integration_token_service import IntegrationTokenService
|
||||||
|
from backend.services.material_catalog_resolver import MaterialCatalogResolver
|
||||||
from backend.services.wardrobe_service import WardrobeService
|
from backend.services.wardrobe_service import WardrobeService
|
||||||
from core.audit_service import AuditService
|
from core.audit_service import AuditService
|
||||||
from core.config_service import ConfigService
|
from core.config_service import ConfigService
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from core.security import require_authenticated, require_config_manager
|
from core.security import require_authenticated, require_config_manager
|
||||||
from database.db_helper import Database, load_database_settings
|
from database.db_helper import Database, load_database_settings
|
||||||
|
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
|
||||||
from database.repositories.integration_repository import IntegrationRepository
|
from database.repositories.integration_repository import IntegrationRepository
|
||||||
from database.repositories.material_repository import MaterialRepository
|
from database.repositories.material_repository import MaterialRepository
|
||||||
from database.repositories.profile_repository import ProfileRepository
|
from database.repositories.profile_repository import ProfileRepository
|
||||||
from database.repositories.wardrobe_repository import WardrobeRepository
|
from database.repositories.wardrobe_repository import AdvancedWardrobeRepository, WardrobeRepository
|
||||||
|
|
||||||
|
|
||||||
def private_companion_daily_outfit(
|
def private_companion_daily_outfit(
|
||||||
|
|
@ -82,11 +84,15 @@ def _create_integration_service() -> IntegrationService:
|
||||||
database = Database(load_database_settings())
|
database = Database(load_database_settings())
|
||||||
audit_service = AuditService(database)
|
audit_service = AuditService(database)
|
||||||
config_service = ConfigService()
|
config_service = ConfigService()
|
||||||
|
materials = MaterialRepository(database)
|
||||||
|
advanced_materials = AdvancedMaterialRepository(database)
|
||||||
wardrobe_service = WardrobeService(
|
wardrobe_service = WardrobeService(
|
||||||
wardrobe_repository=WardrobeRepository(database),
|
wardrobe_repository=WardrobeRepository(database),
|
||||||
profile_repository=ProfileRepository(database),
|
profile_repository=ProfileRepository(database),
|
||||||
material_repository=MaterialRepository(database),
|
material_repository=materials,
|
||||||
audit_service=audit_service,
|
audit_service=audit_service,
|
||||||
|
advanced_wardrobe_repository=AdvancedWardrobeRepository(database),
|
||||||
|
material_catalog=MaterialCatalogResolver(materials, advanced_materials),
|
||||||
)
|
)
|
||||||
return IntegrationService(
|
return IntegrationService(
|
||||||
wardrobe_service=wardrobe_service,
|
wardrobe_service=wardrobe_service,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""Job and queue route handlers."""
|
"""Job and queue route handlers."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
@ -11,7 +11,7 @@ from backend.services.generation_job_retry_service import GenerationJobRetryServ
|
||||||
from backend.services.queue_service import QueueService
|
from backend.services.queue_service import QueueService
|
||||||
from core.audit_service import AuditService
|
from core.audit_service import AuditService
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from core.security import require_authenticated, require_task_retry, require_write
|
from core.security import require_authenticated, require_permission, require_task_retry, require_write
|
||||||
from database.db_helper import Database, load_database_settings
|
from database.db_helper import Database, load_database_settings
|
||||||
from database.repositories.job_repository import JobRepository
|
from database.repositories.job_repository import JobRepository
|
||||||
|
|
||||||
|
|
@ -26,13 +26,17 @@ def list_jobs(
|
||||||
|
|
||||||
def action() -> dict[str, Any]:
|
def action() -> dict[str, Any]:
|
||||||
require_authenticated(ctx)
|
require_authenticated(ctx)
|
||||||
return queue_service.list_jobs(
|
result = queue_service.list_jobs(
|
||||||
status=optional_str(params.get("status")),
|
status=optional_str(params.get("status")),
|
||||||
workflow_id=optional_str(params.get("workflow_id")),
|
workflow_id=optional_str(params.get("workflow_id")),
|
||||||
profile_id=optional_str(params.get("profile_id")),
|
profile_id=optional_str(params.get("profile_id")),
|
||||||
page=int_or_default(params.get("page"), 1),
|
page=int_or_default(params.get("page"), 1),
|
||||||
page_size=int_or_default(params.get("page_size"), 30),
|
page_size=int_or_default(params.get("page_size"), 30),
|
||||||
).to_dict()
|
).to_dict()
|
||||||
|
if not ctx.has_permission("can_manage_materials"):
|
||||||
|
visible = [item for item in result["items"] if item.get("metadata", {}).get("source") != "advanced_material"]
|
||||||
|
result = {**result, "items": visible, "total": max(int(result.get("total") or 0) - (len(result["items"]) - len(visible)), 0)}
|
||||||
|
return result
|
||||||
|
|
||||||
return handle_request(ctx, action)
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
@ -46,7 +50,10 @@ def get_job(
|
||||||
|
|
||||||
def action() -> dict[str, Any]:
|
def action() -> dict[str, Any]:
|
||||||
require_authenticated(ctx)
|
require_authenticated(ctx)
|
||||||
return queue_service.get_job(task_id).to_dict()
|
task = queue_service.get_job(task_id)
|
||||||
|
if task.metadata.get("source") == "advanced_material":
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
return task.to_dict()
|
||||||
|
|
||||||
return handle_request(ctx, action)
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
@ -74,6 +81,13 @@ def cancel_job(
|
||||||
|
|
||||||
def action() -> dict[str, Any]:
|
def action() -> dict[str, Any]:
|
||||||
require_write(ctx)
|
require_write(ctx)
|
||||||
|
task = queue_service.get_job(task_id)
|
||||||
|
if task.metadata.get("source") == "advanced_material":
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
from backend.services.advanced_material_service import create_advanced_material_service
|
||||||
|
|
||||||
|
import_id = str(task.metadata.get("advanced_material_import_id") or "").strip()
|
||||||
|
return create_advanced_material_service().cancel_import(import_id, ctx)
|
||||||
return queue_service.cancel_job(task_id, ctx).to_dict()
|
return queue_service.cancel_job(task_id, ctx).to_dict()
|
||||||
|
|
||||||
return handle_request(ctx, action)
|
return handle_request(ctx, action)
|
||||||
|
|
@ -85,15 +99,140 @@ def retry_job(
|
||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
service: GenerationJobRetryService | None = None,
|
service: GenerationJobRetryService | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
retry_service = service or _create_generation_job_retry_service()
|
retry_service = service
|
||||||
|
|
||||||
def action() -> dict[str, Any]:
|
def action() -> dict[str, Any]:
|
||||||
require_task_retry(ctx)
|
require_task_retry(ctx)
|
||||||
return retry_service.retry_job(task_id, ctx, overrides=payload or {}).to_dict()
|
queue_service = _create_queue_service()
|
||||||
|
task = queue_service.get_job(task_id)
|
||||||
|
return _retry_task(task, ctx, payload=payload, retry_service=retry_service)
|
||||||
|
|
||||||
return handle_request(ctx, action)
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def retry_failed_jobs(
|
||||||
|
ctx: RequestContext,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
) -> dict:
|
||||||
|
params = payload or {}
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_task_retry(ctx)
|
||||||
|
queue_service = _create_queue_service()
|
||||||
|
limit = max(1, min(int_or_default(params.get("limit"), 100), 100))
|
||||||
|
tasks = []
|
||||||
|
seen_task_ids: set[str] = set()
|
||||||
|
for status in ("failed", "dead_letter", "cancelled"):
|
||||||
|
remaining = limit - len(tasks)
|
||||||
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
for task in queue_service.list_jobs(status=status, page=1, page_size=remaining).items:
|
||||||
|
if task.task_id not in seen_task_ids:
|
||||||
|
seen_task_ids.add(task.task_id)
|
||||||
|
tasks.append(task)
|
||||||
|
|
||||||
|
tasks = _latest_retryable_tasks(tasks)
|
||||||
|
retried: list[dict[str, Any]] = []
|
||||||
|
errors: list[dict[str, Any]] = []
|
||||||
|
retry_service: GenerationJobRetryService | None = None
|
||||||
|
for task in tasks:
|
||||||
|
try:
|
||||||
|
if task.metadata.get("source") != "advanced_material":
|
||||||
|
retry_service = retry_service or _create_generation_job_retry_service()
|
||||||
|
retried.append(_retry_task(task, ctx, retry_service=retry_service))
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(_retry_error_payload(task.task_id, exc))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"retried": retried,
|
||||||
|
"errors": errors,
|
||||||
|
"total": len(retried),
|
||||||
|
"processed": len(retried) + len(errors),
|
||||||
|
"limit": limit,
|
||||||
|
"remaining_by_status": {
|
||||||
|
status: queue_service.repository.count_by_status().get(status, 0)
|
||||||
|
for status in ("failed", "dead_letter", "cancelled")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def _latest_retryable_tasks(tasks: list[Any]) -> list[Any]:
|
||||||
|
selected: list[Any] = []
|
||||||
|
lineage_indexes: dict[tuple[str, str], int] = {}
|
||||||
|
for task in tasks:
|
||||||
|
lineage_key = _retry_lineage_key(task)
|
||||||
|
if lineage_key is None:
|
||||||
|
selected.append(task)
|
||||||
|
continue
|
||||||
|
previous_index = lineage_indexes.get(lineage_key)
|
||||||
|
if previous_index is None:
|
||||||
|
lineage_indexes[lineage_key] = len(selected)
|
||||||
|
selected.append(task)
|
||||||
|
continue
|
||||||
|
previous_task = selected[previous_index]
|
||||||
|
if _task_sort_key(task) > _task_sort_key(previous_task):
|
||||||
|
selected[previous_index] = task
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_lineage_key(task: Any) -> tuple[str, str] | None:
|
||||||
|
metadata = task.metadata if isinstance(getattr(task, "metadata", None), dict) else {}
|
||||||
|
source_id = str(metadata.get("advanced_style_source_id") or "").strip()
|
||||||
|
case_id = str(metadata.get("advanced_style_validation_case_id") or "").strip()
|
||||||
|
if task.task_type == "advanced_style_source_recognition" and source_id:
|
||||||
|
return ("source", source_id)
|
||||||
|
if task.task_type == "advanced_style_validation_generation" and case_id:
|
||||||
|
return ("validation", case_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _task_sort_key(task: Any) -> str:
|
||||||
|
return str(getattr(task, "updated_at", "") or getattr(task, "created_at", "") or "")
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_task(
|
||||||
|
task: Any,
|
||||||
|
ctx: RequestContext,
|
||||||
|
*,
|
||||||
|
payload: dict[str, Any] | None = None,
|
||||||
|
retry_service: GenerationJobRetryService | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if task.metadata.get("source") == "advanced_material":
|
||||||
|
require_permission(ctx, "can_manage_materials")
|
||||||
|
from backend.services.advanced_material_service import create_advanced_material_service
|
||||||
|
|
||||||
|
advanced_service = create_advanced_material_service()
|
||||||
|
import_id = str(task.metadata.get("advanced_material_import_id") or "").strip()
|
||||||
|
if task.task_type == "advanced_style_source_recognition":
|
||||||
|
source_id = str(task.metadata.get("advanced_style_source_id") or "").strip()
|
||||||
|
result = advanced_service.style_sets.retry_source(import_id, source_id, ctx)
|
||||||
|
elif task.task_type == "advanced_style_validation_generation":
|
||||||
|
case_id = str(task.metadata.get("advanced_style_validation_case_id") or "").strip()
|
||||||
|
result = advanced_service.style_sets.retry_validation_case(import_id, case_id, ctx)
|
||||||
|
else:
|
||||||
|
result = advanced_service.retry_import(import_id, ctx)
|
||||||
|
if isinstance(result, dict) and isinstance(result.get("task"), dict):
|
||||||
|
return result["task"]
|
||||||
|
return result
|
||||||
|
resolved_retry_service = retry_service or _create_generation_job_retry_service()
|
||||||
|
return resolved_retry_service.retry_job(task.task_id, ctx, overrides=payload or {}).to_dict()
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_error_payload(task_id: str, exc: Exception) -> dict[str, Any]:
|
||||||
|
error_code = getattr(getattr(exc, "error_code", None), "value", None) or str(getattr(exc, "error_code", "retry_failed"))
|
||||||
|
message = str(getattr(exc, "message", None) or str(exc))
|
||||||
|
raw_details = getattr(exc, "details", None)
|
||||||
|
details = dict(raw_details) if isinstance(raw_details, dict) else {}
|
||||||
|
return {
|
||||||
|
"task_id": task_id,
|
||||||
|
"error_code": error_code,
|
||||||
|
"message": message,
|
||||||
|
**({"replacement_task_id": details["replacement_task_id"]} if details.get("replacement_task_id") else {}),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def retry_dead_letter_jobs(
|
def retry_dead_letter_jobs(
|
||||||
ctx: RequestContext,
|
ctx: RequestContext,
|
||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
|
|
@ -176,3 +315,5 @@ def _create_generation_job_retry_service() -> GenerationJobRetryService:
|
||||||
queue_service=generation_service.queue_service,
|
queue_service=generation_service.queue_service,
|
||||||
generation_service=generation_service,
|
generation_service=generation_service,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,34 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from backend.routes.common import handle_request
|
from backend.routes.common import handle_request
|
||||||
|
from backend.services.model_provider_service import ModelProviderService
|
||||||
from core.astrbot_provider_bridge import list_astrbot_text_models
|
from core.astrbot_provider_bridge import list_astrbot_text_models
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from core.security import require_authenticated
|
from core.security import require_authenticated
|
||||||
|
from database.db_helper import Database, load_database_settings
|
||||||
|
from database.repositories.model_provider_repository import ModelProviderRepository
|
||||||
|
|
||||||
|
|
||||||
def list_runtime_models(ctx: RequestContext) -> dict:
|
def list_runtime_models(ctx: RequestContext, service: ModelProviderService | None = None) -> dict:
|
||||||
|
model_service = service or ModelProviderService(ModelProviderRepository(Database(load_database_settings())))
|
||||||
|
|
||||||
def action() -> dict:
|
def action() -> dict:
|
||||||
require_authenticated(ctx)
|
require_authenticated(ctx)
|
||||||
return {"items": list_astrbot_text_models()}
|
plugin_items: list[dict[str, str]] = []
|
||||||
|
providers = {item["provider_id"]: item for item in model_service.list_providers(enabled=True)}
|
||||||
|
for route in model_service.list_routes(enabled=True):
|
||||||
|
provider_id = str(route.get("provider_id") or "")
|
||||||
|
provider = providers.get(provider_id) or {}
|
||||||
|
plugin_items.append(
|
||||||
|
{
|
||||||
|
"route": str(route.get("route_name") or ""),
|
||||||
|
"provider_id": provider_id,
|
||||||
|
"name": str(provider.get("display_name") or provider_id),
|
||||||
|
"model": str(route.get("model_id") or ""),
|
||||||
|
"modality": str(route.get("modality") or ""),
|
||||||
|
"source": "plugin",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"items": [*plugin_items, *list_astrbot_text_models()]}
|
||||||
|
|
||||||
return handle_request(ctx, action)
|
return handle_request(ctx, action)
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ from typing import Any
|
||||||
|
|
||||||
from backend.routes.common import handle_request
|
from backend.routes.common import handle_request
|
||||||
from backend.services.resource_access_service import ResourceAccessService
|
from backend.services.resource_access_service import ResourceAccessService
|
||||||
|
from backend.services.material_catalog_resolver import MaterialCatalogResolver
|
||||||
from backend.services.workflow_node_material_service import WorkflowNodeMaterialService
|
from backend.services.workflow_node_material_service import WorkflowNodeMaterialService
|
||||||
from backend.services.workflow_service import WorkflowService
|
from backend.services.workflow_service import WorkflowService
|
||||||
from core.audit_service import AuditService
|
from core.audit_service import AuditService
|
||||||
|
|
@ -13,6 +14,7 @@ from core.identity import RequestContext
|
||||||
from core.security import require_authenticated, require_write
|
from core.security import require_authenticated, require_write
|
||||||
from database.db_helper import Database, load_database_settings
|
from database.db_helper import Database, load_database_settings
|
||||||
from database.repositories.image_repository import ImageRepository
|
from database.repositories.image_repository import ImageRepository
|
||||||
|
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
|
||||||
from database.repositories.job_repository import JobRepository
|
from database.repositories.job_repository import JobRepository
|
||||||
from database.repositories.material_repository import MaterialRepository
|
from database.repositories.material_repository import MaterialRepository
|
||||||
from database.repositories.profile_repository import ProfileRepository
|
from database.repositories.profile_repository import ProfileRepository
|
||||||
|
|
@ -71,7 +73,10 @@ def _create_service() -> WorkflowNodeMaterialService:
|
||||||
)
|
)
|
||||||
return WorkflowNodeMaterialService(
|
return WorkflowNodeMaterialService(
|
||||||
workflow_service,
|
workflow_service,
|
||||||
MaterialRepository(database),
|
MaterialCatalogResolver(
|
||||||
|
MaterialRepository(database),
|
||||||
|
AdvancedMaterialRepository(database),
|
||||||
|
),
|
||||||
round_repository=WorkflowRoundRepository(database),
|
round_repository=WorkflowRoundRepository(database),
|
||||||
access_service=ResourceAccessService(
|
access_service=ResourceAccessService(
|
||||||
profiles,
|
profiles,
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ from backend.services.cost_service import CostService
|
||||||
from backend.services.generation_service import GenerationService
|
from backend.services.generation_service import GenerationService
|
||||||
from backend.services.image_service import ImageService
|
from backend.services.image_service import ImageService
|
||||||
from backend.services.model_provider_runtime import ModelProviderRuntime
|
from backend.services.model_provider_runtime import ModelProviderRuntime
|
||||||
|
from backend.services.material_catalog_resolver import MaterialCatalogResolver
|
||||||
from core.astrbot_provider_bridge import astrbot_structured_text_callable
|
from core.astrbot_provider_bridge import astrbot_structured_text_callable
|
||||||
from backend.services.model_provider_bootstrap import sync_generation_provider_from_config
|
from backend.services.model_provider_bootstrap import sync_generation_provider_from_config
|
||||||
from backend.services.model_provider_service import ModelProviderService
|
from backend.services.model_provider_service import ModelProviderService
|
||||||
|
|
@ -39,6 +40,7 @@ from engines.character_flow import canonical_gradual_node_key
|
||||||
from core.security import require_authenticated, require_task_retry, require_write
|
from core.security import require_authenticated, require_task_retry, require_write
|
||||||
from database.db_helper import Database, load_config_payload, load_database_settings
|
from database.db_helper import Database, load_config_payload, load_database_settings
|
||||||
from database.repositories.image_repository import ImageRepository
|
from database.repositories.image_repository import ImageRepository
|
||||||
|
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
|
||||||
from database.repositories.job_repository import JobRepository
|
from database.repositories.job_repository import JobRepository
|
||||||
from database.repositories.material_repository import MaterialRepository
|
from database.repositories.material_repository import MaterialRepository
|
||||||
from database.repositories.model_provider_repository import ModelProviderRepository
|
from database.repositories.model_provider_repository import ModelProviderRepository
|
||||||
|
|
@ -315,6 +317,10 @@ def _create_generation_service() -> GenerationService:
|
||||||
audit_service = AuditService(database)
|
audit_service = AuditService(database)
|
||||||
workflow_repository = WorkflowRepository(database)
|
workflow_repository = WorkflowRepository(database)
|
||||||
material_repository = MaterialRepository(database)
|
material_repository = MaterialRepository(database)
|
||||||
|
material_catalog = MaterialCatalogResolver(
|
||||||
|
material_repository,
|
||||||
|
AdvancedMaterialRepository(database),
|
||||||
|
)
|
||||||
event_bus = get_default_event_bus()
|
event_bus = get_default_event_bus()
|
||||||
model_provider_service = ModelProviderService(ModelProviderRepository(database))
|
model_provider_service = ModelProviderService(ModelProviderRepository(database))
|
||||||
model_provider_runtime = ModelProviderRuntime(model_provider_service)
|
model_provider_runtime = ModelProviderRuntime(model_provider_service)
|
||||||
|
|
@ -370,10 +376,10 @@ def _create_generation_service() -> GenerationService:
|
||||||
event_bus=event_bus,
|
event_bus=event_bus,
|
||||||
default_model_route=str(generation_config.get("default_model") or "").strip() or None,
|
default_model_route=str(generation_config.get("default_model") or "").strip() or None,
|
||||||
require_resolved_model_route=True,
|
require_resolved_model_route=True,
|
||||||
material_resolver=material_repository,
|
material_resolver=material_catalog,
|
||||||
material_snapshot_service=WorkflowMaterialSnapshotService(
|
material_snapshot_service=WorkflowMaterialSnapshotService(
|
||||||
workflow_repository,
|
workflow_repository,
|
||||||
material_repository,
|
material_catalog,
|
||||||
),
|
),
|
||||||
model_assignments=model_assignments,
|
model_assignments=model_assignments,
|
||||||
prompt_translation_service=PromptTranslationService(translation_config, translation_callable),
|
prompt_translation_service=PromptTranslationService(translation_config, translation_callable),
|
||||||
|
|
|
||||||
|
|
@ -7,13 +7,15 @@ from typing import Any
|
||||||
from backend.routes.common import handle_request
|
from backend.routes.common import handle_request
|
||||||
from backend.routes.params import optional_str
|
from backend.routes.params import optional_str
|
||||||
from backend.services.wardrobe_service import WardrobeService
|
from backend.services.wardrobe_service import WardrobeService
|
||||||
|
from backend.services.material_catalog_resolver import MaterialCatalogResolver
|
||||||
from core.audit_service import AuditService
|
from core.audit_service import AuditService
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from core.security import require_authenticated, require_permission
|
from core.security import require_authenticated, require_permission
|
||||||
from database.db_helper import Database, load_database_settings
|
from database.db_helper import Database, load_database_settings
|
||||||
|
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
|
||||||
from database.repositories.material_repository import MaterialRepository
|
from database.repositories.material_repository import MaterialRepository
|
||||||
from database.repositories.profile_repository import ProfileRepository
|
from database.repositories.profile_repository import ProfileRepository
|
||||||
from database.repositories.wardrobe_repository import WardrobeRepository
|
from database.repositories.wardrobe_repository import AdvancedWardrobeRepository, WardrobeRepository
|
||||||
|
|
||||||
|
|
||||||
def list_wardrobe_items(
|
def list_wardrobe_items(
|
||||||
|
|
@ -106,9 +108,13 @@ def apply_wardrobe_template(ctx: RequestContext, profile_id: str, template_id: s
|
||||||
|
|
||||||
def _create_wardrobe_service() -> WardrobeService:
|
def _create_wardrobe_service() -> WardrobeService:
|
||||||
database = Database(load_database_settings())
|
database = Database(load_database_settings())
|
||||||
|
materials = MaterialRepository(database)
|
||||||
|
advanced_materials = AdvancedMaterialRepository(database)
|
||||||
return WardrobeService(
|
return WardrobeService(
|
||||||
wardrobe_repository=WardrobeRepository(database),
|
wardrobe_repository=WardrobeRepository(database),
|
||||||
profile_repository=ProfileRepository(database),
|
profile_repository=ProfileRepository(database),
|
||||||
material_repository=MaterialRepository(database),
|
material_repository=materials,
|
||||||
audit_service=AuditService(database),
|
audit_service=AuditService(database),
|
||||||
|
advanced_wardrobe_repository=AdvancedWardrobeRepository(database),
|
||||||
|
material_catalog=MaterialCatalogResolver(materials, advanced_materials),
|
||||||
)
|
)
|
||||||
|
|
|
||||||
文件差异内容过多而无法显示
加载差异
|
|
@ -0,0 +1,167 @@
|
||||||
|
"""Persistent worker pool for advanced-material recognition and validation."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from backend.dto.job_dto import GenerationTask
|
||||||
|
from backend.services.advanced_material_service import (
|
||||||
|
AdvancedMaterialService,
|
||||||
|
create_advanced_material_service,
|
||||||
|
)
|
||||||
|
from backend.services.worker_service import QueueWorkerPool, RetryPolicy, WorkerTaskUpdate
|
||||||
|
from core.identity import RequestContext
|
||||||
|
|
||||||
|
|
||||||
|
class AdvancedMaterialWorkerRuntime:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
service: AdvancedMaterialService,
|
||||||
|
*,
|
||||||
|
worker_count: int = 8,
|
||||||
|
ctx: RequestContext | None = None,
|
||||||
|
):
|
||||||
|
self.service = service
|
||||||
|
self.ctx = ctx or RequestContext.system("advanced-material-worker")
|
||||||
|
recognition_concurrency = _recognition_concurrency(getattr(service, "config", {}))
|
||||||
|
self.pool = QueueWorkerPool(
|
||||||
|
service.queue_service,
|
||||||
|
self._execute,
|
||||||
|
worker_count=worker_count,
|
||||||
|
worker_id_prefix="imagestudio-advanced-material",
|
||||||
|
interval_seconds=0.35,
|
||||||
|
claim_batch_size=25,
|
||||||
|
retry_policy=RetryPolicy(max_attempts=1),
|
||||||
|
task_filter=_is_advanced_material_task,
|
||||||
|
terminal_callback=self._on_terminal,
|
||||||
|
# Keep worker threads available for queue progress, but limit
|
||||||
|
# simultaneous calls to the same vision route. Vision providers
|
||||||
|
# and relay services commonly rate-limit image requests more
|
||||||
|
# aggressively than ordinary text requests.
|
||||||
|
per_route_limit=recognition_concurrency,
|
||||||
|
)
|
||||||
|
|
||||||
|
def start(self) -> dict[str, Any]:
|
||||||
|
recovery = self._recover_interrupted_tasks()
|
||||||
|
result = self.pool.start(self.ctx)
|
||||||
|
return {**result, "recovery": recovery}
|
||||||
|
|
||||||
|
def stop(self, *, timeout_seconds: float = 5.0) -> dict[str, Any]:
|
||||||
|
return self.pool.stop(timeout_seconds=timeout_seconds)
|
||||||
|
|
||||||
|
def _execute(self, task: GenerationTask) -> WorkerTaskUpdate:
|
||||||
|
return self.service.execute_task(task, self.ctx)
|
||||||
|
|
||||||
|
def _on_terminal(
|
||||||
|
self,
|
||||||
|
claimed_task: GenerationTask,
|
||||||
|
current_task: GenerationTask,
|
||||||
|
exc: Exception | None,
|
||||||
|
) -> None:
|
||||||
|
if current_task.status in {"failed", "dead_letter", "cancelled"}:
|
||||||
|
self.service.handle_task_failure(
|
||||||
|
claimed_task,
|
||||||
|
exc or RuntimeError(current_task.error_message or "advanced material task failed"),
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _recover_interrupted_tasks(self) -> dict[str, Any]:
|
||||||
|
"""Safely recover recognition, but never replay a paid image request.
|
||||||
|
|
||||||
|
Recognition is read-only and idempotent. A validation request may have
|
||||||
|
reached the remote provider before the plugin process stopped, so it is
|
||||||
|
marked failed and left for an explicit human retry.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# The pool has not started yet, so every advanced-material task still
|
||||||
|
# in running/retrying belongs to the previous process. Do not apply a
|
||||||
|
# stale-age grace period: a fast container restart must recover tasks
|
||||||
|
# written only milliseconds earlier. Do not cap the snapshot either,
|
||||||
|
# otherwise unrelated queue rows can hide advanced-material work.
|
||||||
|
candidates = self.service.queue_service.repository.list_stale(
|
||||||
|
statuses=("running", "retrying"),
|
||||||
|
updated_before=None,
|
||||||
|
limit=None,
|
||||||
|
)
|
||||||
|
requeued: list[str] = []
|
||||||
|
failed: list[str] = []
|
||||||
|
skipped: list[str] = []
|
||||||
|
for task in candidates:
|
||||||
|
if not _is_advanced_material_task(task):
|
||||||
|
skipped.append(task.task_id)
|
||||||
|
continue
|
||||||
|
interrupted = self.service.queue_service.update_task_if_status(
|
||||||
|
task.task_id,
|
||||||
|
{task.status},
|
||||||
|
{
|
||||||
|
"status": "failed",
|
||||||
|
"error_message": "task was interrupted by a previous plugin process",
|
||||||
|
"metadata": {
|
||||||
|
**task.metadata,
|
||||||
|
"recovery": {
|
||||||
|
"source": "advanced_material_startup",
|
||||||
|
"previous_status": task.status,
|
||||||
|
"observed_at": datetime.now(timezone.utc).isoformat(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
if interrupted is None:
|
||||||
|
skipped.append(task.task_id)
|
||||||
|
continue
|
||||||
|
if task.task_type in {
|
||||||
|
"advanced_material_recognition",
|
||||||
|
"advanced_style_source_recognition",
|
||||||
|
"advanced_style_consensus",
|
||||||
|
}:
|
||||||
|
queued = self.service.queue_service.update_task_if_status(
|
||||||
|
task.task_id,
|
||||||
|
{"failed"},
|
||||||
|
{
|
||||||
|
"status": "queued",
|
||||||
|
"progress": 0,
|
||||||
|
"error_message": None,
|
||||||
|
"metadata": {
|
||||||
|
**interrupted.metadata,
|
||||||
|
"recovery": {**interrupted.metadata.get("recovery", {}), "status": "requeued"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
if queued is not None:
|
||||||
|
requeued.append(task.task_id)
|
||||||
|
continue
|
||||||
|
self.service.handle_task_failure(
|
||||||
|
task,
|
||||||
|
RuntimeError("task was interrupted by a previous plugin process"),
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
failed.append(task.task_id)
|
||||||
|
return {"requeued_task_ids": requeued, "failed_task_ids": failed, "skipped_task_ids": skipped}
|
||||||
|
|
||||||
|
|
||||||
|
def create_advanced_material_worker_runtime() -> AdvancedMaterialWorkerRuntime:
|
||||||
|
return AdvancedMaterialWorkerRuntime(create_advanced_material_service())
|
||||||
|
|
||||||
|
|
||||||
|
def _is_advanced_material_task(task: GenerationTask) -> bool:
|
||||||
|
return task.metadata.get("source") == "advanced_material" and task.task_type in {
|
||||||
|
"advanced_material_recognition",
|
||||||
|
"advanced_material_validation_generation",
|
||||||
|
"advanced_style_source_recognition",
|
||||||
|
"advanced_style_consensus",
|
||||||
|
"advanced_style_validation_generation",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _recognition_concurrency(config: dict[str, Any] | None) -> int:
|
||||||
|
advanced_materials = config.get("advanced_materials") if isinstance(config, dict) else None
|
||||||
|
if not isinstance(advanced_materials, dict):
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
return min(max(int(advanced_materials.get("recognition_concurrency", 2)), 1), 8)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 2
|
||||||
文件差异内容过多而无法显示
加载差异
|
|
@ -5,6 +5,7 @@ from __future__ import annotations
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Any, Mapping
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
from backend.services.material_catalog_resolver import is_trusted_advanced_metadata
|
||||||
from backend.services.material_normalization_service import CAPSULE_TIERS, WEAR_LAYERS
|
from backend.services.material_normalization_service import CAPSULE_TIERS, WEAR_LAYERS
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -31,6 +32,7 @@ CONTRADICTIONS = (
|
||||||
("fitted", "oversized"), ("matte", "glossy"), ("short sleeve", "long sleeve"),
|
("fitted", "oversized"), ("matte", "glossy"), ("short sleeve", "long sleeve"),
|
||||||
("transparent", "opaque"), ("minimal", "ornate"),
|
("transparent", "opaque"), ("minimal", "ornate"),
|
||||||
)
|
)
|
||||||
|
ADVANCED_VERIFIED_PRIORITY_BONUS = 20.0
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|
@ -130,6 +132,11 @@ class CompositionBuilder:
|
||||||
user_adjustment = _float(item.get("user_adjustment"), 0.0)
|
user_adjustment = _float(item.get("user_adjustment"), 0.0)
|
||||||
role_bonus = 20.0 if role == "identity" else 8.0 if category in {"dress", "suit", "top", "bottom", "outerwear"} else 0.0
|
role_bonus = 20.0 if role == "identity" else 8.0 if category in {"dress", "suit", "top", "bottom", "outerwear"} else 0.0
|
||||||
lock_bonus = 100.0 if locked else 0.0
|
lock_bonus = 100.0 if locked else 0.0
|
||||||
|
advanced_verified_bonus = (
|
||||||
|
ADVANCED_VERIFIED_PRIORITY_BONUS
|
||||||
|
if is_trusted_advanced_metadata(metadata)
|
||||||
|
else 0.0
|
||||||
|
)
|
||||||
slots = _string_list(profile.get("body_slots"))
|
slots = _string_list(profile.get("body_slots"))
|
||||||
automatic_visibility = 10.0 if plan.visible_slots and set(slots) & set(plan.visible_slots) else 0.0
|
automatic_visibility = 10.0 if plan.visible_slots and set(slots) & set(plan.visible_slots) else 0.0
|
||||||
visibility_bonus = _float(item.get("visibility_bonus"), 0.0) + automatic_visibility
|
visibility_bonus = _float(item.get("visibility_bonus"), 0.0) + automatic_visibility
|
||||||
|
|
@ -137,7 +144,7 @@ class CompositionBuilder:
|
||||||
season_penalty = 12.0 if plan.season and _text(item.get("season")) and plan.season.casefold() != _text(item.get("season")).casefold() else 0.0
|
season_penalty = 12.0 if plan.season and _text(item.get("season")) and plan.season.casefold() != _text(item.get("season")).casefold() else 0.0
|
||||||
low_confidence_penalty = max(0.0, 0.80 - confidence) * 40.0
|
low_confidence_penalty = max(0.0, 0.80 - confidence) * 40.0
|
||||||
base_weight = BASE_WEIGHTS.get(category, BASE_WEIGHTS["other"])
|
base_weight = BASE_WEIGHTS.get(category, BASE_WEIGHTS["other"])
|
||||||
effective_weight = base_weight + user_adjustment + role_bonus + lock_bonus + visibility_bonus + restoration_feedback_bonus - low_confidence_penalty - season_penalty
|
effective_weight = base_weight + user_adjustment + role_bonus + lock_bonus + advanced_verified_bonus + visibility_bonus + restoration_feedback_bonus - low_confidence_penalty - season_penalty
|
||||||
tier = _text(item.get("capsule_tier") or "detailed").lower()
|
tier = _text(item.get("capsule_tier") or "detailed").lower()
|
||||||
if tier not in CAPSULE_TIERS:
|
if tier not in CAPSULE_TIERS:
|
||||||
tier = "standard"
|
tier = "standard"
|
||||||
|
|
@ -164,6 +171,7 @@ class CompositionBuilder:
|
||||||
"user_adjustment": user_adjustment,
|
"user_adjustment": user_adjustment,
|
||||||
"lock_bonus": lock_bonus,
|
"lock_bonus": lock_bonus,
|
||||||
"role_bonus": role_bonus,
|
"role_bonus": role_bonus,
|
||||||
|
"advanced_verified_bonus": advanced_verified_bonus,
|
||||||
"visibility_bonus": visibility_bonus,
|
"visibility_bonus": visibility_bonus,
|
||||||
"restoration_feedback_bonus": round(restoration_feedback_bonus, 3),
|
"restoration_feedback_bonus": round(restoration_feedback_bonus, 3),
|
||||||
"season_penalty": season_penalty,
|
"season_penalty": season_penalty,
|
||||||
|
|
|
||||||
|
|
@ -73,6 +73,47 @@ class CostService:
|
||||||
task_usage["output_tokens"],
|
task_usage["output_tokens"],
|
||||||
_usage_number(usage, "output_tokens", "completion_tokens"),
|
_usage_number(usage, "output_tokens", "completion_tokens"),
|
||||||
)
|
)
|
||||||
|
if not any((profile_id, workflow_id, node_id)):
|
||||||
|
# A style-set attempt projects its first validation case onto the
|
||||||
|
# legacy attempt row for compatibility. Bill the child cases and
|
||||||
|
# exclude that projection so the representative image is not
|
||||||
|
# counted twice.
|
||||||
|
advanced_rows = (
|
||||||
|
self._advanced_material_attempt_rows()
|
||||||
|
+ self._advanced_style_validation_case_rows()
|
||||||
|
)
|
||||||
|
for row in advanced_rows:
|
||||||
|
created_at = _parse_datetime(row["created_at"])
|
||||||
|
if since and created_at and created_at < since:
|
||||||
|
continue
|
||||||
|
provider = str(row["provider_id"] or "unknown")
|
||||||
|
if provider_id and provider != provider_id:
|
||||||
|
continue
|
||||||
|
provider_model = str(row["provider_model"] or "unknown")
|
||||||
|
model_route = str(row["model_route"] or "unknown")
|
||||||
|
usage = _json_loads(row["usage_json"])
|
||||||
|
key = (provider, provider_model, model_route)
|
||||||
|
group = groups.setdefault(key, _new_group(provider, provider_model, model_route))
|
||||||
|
if row["validation_image_uri"]:
|
||||||
|
group["image_count"] += 1
|
||||||
|
task_key = str(row["task_id"] or row["billing_id"])
|
||||||
|
group["_task_ids"].add(task_key)
|
||||||
|
task_usage = group["_usage_by_task"].setdefault(
|
||||||
|
task_key,
|
||||||
|
{"total_tokens": 0, "input_tokens": 0, "output_tokens": 0},
|
||||||
|
)
|
||||||
|
task_usage["total_tokens"] = max(
|
||||||
|
task_usage["total_tokens"],
|
||||||
|
_usage_number(usage, "total_tokens", "total"),
|
||||||
|
)
|
||||||
|
task_usage["input_tokens"] = max(
|
||||||
|
task_usage["input_tokens"],
|
||||||
|
_usage_number(usage, "input_tokens", "prompt_tokens"),
|
||||||
|
)
|
||||||
|
task_usage["output_tokens"] = max(
|
||||||
|
task_usage["output_tokens"],
|
||||||
|
_usage_number(usage, "output_tokens", "completion_tokens"),
|
||||||
|
)
|
||||||
finalized = [_finalize_group(group, prices) for group in groups.values()]
|
finalized = [_finalize_group(group, prices) for group in groups.values()]
|
||||||
totals = {
|
totals = {
|
||||||
"image_count": sum(group["image_count"] for group in finalized),
|
"image_count": sum(group["image_count"] for group in finalized),
|
||||||
|
|
@ -158,6 +199,40 @@ class CostService:
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
def _advanced_material_attempt_rows(self) -> list[Any]:
|
||||||
|
conn = self.database.connect()
|
||||||
|
try:
|
||||||
|
return conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT attempt_id AS billing_id, task_id, model_route, provider_id,
|
||||||
|
provider_model, usage_json, validation_image_uri, created_at
|
||||||
|
FROM advanced_material_validation_attempts AS attempt
|
||||||
|
WHERE (usage_json IS NOT NULL OR validation_image_uri IS NOT NULL)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM advanced_style_validation_cases AS style_case
|
||||||
|
WHERE style_case.attempt_id = attempt.attempt_id
|
||||||
|
)
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def _advanced_style_validation_case_rows(self) -> list[Any]:
|
||||||
|
conn = self.database.connect()
|
||||||
|
try:
|
||||||
|
return conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT case_id AS billing_id, task_id, model_route, provider_id,
|
||||||
|
provider_model, usage_json, validation_image_uri, created_at
|
||||||
|
FROM advanced_style_validation_cases
|
||||||
|
WHERE usage_json IS NOT NULL OR validation_image_uri IS NOT NULL
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def _new_group(provider_id: str, provider_model: str, model_route: str) -> dict[str, Any]:
|
def _new_group(provider_id: str, provider_model: str, model_route: str) -> dict[str, Any]:
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ from database.db_helper import load_config_payload, load_database_settings
|
||||||
|
|
||||||
MAX_BACKUP_FILES = 50_000
|
MAX_BACKUP_FILES = 50_000
|
||||||
MAX_RESTORE_BYTES = 10 * 1024 * 1024 * 1024
|
MAX_RESTORE_BYTES = 10 * 1024 * 1024 * 1024
|
||||||
|
PROMPT_BACKUP_PLACEHOLDER = "[EXCLUDED_FROM_BACKUP]"
|
||||||
|
|
||||||
|
|
||||||
class DataBackupService:
|
class DataBackupService:
|
||||||
|
|
@ -75,7 +76,7 @@ class DataBackupService:
|
||||||
storage = config.get("storage") if isinstance(config.get("storage"), dict) else {}
|
storage = config.get("storage") if isinstance(config.get("storage"), dict) else {}
|
||||||
media_roots = {
|
media_roots = {
|
||||||
key: resolve_data_path(storage.get(f"{key}_path") or f"data/{key}")
|
key: resolve_data_path(storage.get(f"{key}_path") or f"data/{key}")
|
||||||
for key in ("images", "thumbnails", "materials", "styles")
|
for key in ("images", "thumbnails", "materials", "advanced_materials", "styles")
|
||||||
}
|
}
|
||||||
if include_media:
|
if include_media:
|
||||||
for key, media_root in media_roots.items():
|
for key, media_root in media_roots.items():
|
||||||
|
|
@ -89,7 +90,7 @@ class DataBackupService:
|
||||||
entries.append(_entry(path, f"media/{key}/{path.relative_to(media_root).as_posix()}"))
|
entries.append(_entry(path, f"media/{key}/{path.relative_to(media_root).as_posix()}"))
|
||||||
manifest = {
|
manifest = {
|
||||||
"format": "imagestudio-full-backup",
|
"format": "imagestudio-full-backup",
|
||||||
"version": 2,
|
"version": 3,
|
||||||
"material_schema_version": "1.0",
|
"material_schema_version": "1.0",
|
||||||
"backup_id": backup_id,
|
"backup_id": backup_id,
|
||||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||||
|
|
@ -137,7 +138,7 @@ class DataBackupService:
|
||||||
shutil.copy2(db_source, db_target)
|
shutil.copy2(db_source, db_target)
|
||||||
config = load_config_payload(self.config_service.config_path)
|
config = load_config_payload(self.config_service.config_path)
|
||||||
storage = config.get("storage") if isinstance(config.get("storage"), dict) else {}
|
storage = config.get("storage") if isinstance(config.get("storage"), dict) else {}
|
||||||
for key in ("images", "thumbnails", "materials", "styles"):
|
for key in ("images", "thumbnails", "materials", "advanced_materials", "styles"):
|
||||||
source_root = temp / "media" / key
|
source_root = temp / "media" / key
|
||||||
if not source_root.exists():
|
if not source_root.exists():
|
||||||
continue
|
continue
|
||||||
|
|
@ -230,10 +231,56 @@ def _sanitize_sqlite_backup(
|
||||||
if not include_prompt_records:
|
if not include_prompt_records:
|
||||||
if "materials" in tables:
|
if "materials" in tables:
|
||||||
conn.execute("UPDATE materials SET prompt = NULL, negative_prompt = NULL")
|
conn.execute("UPDATE materials SET prompt = NULL, negative_prompt = NULL")
|
||||||
|
if "advanced_material_imports" in tables:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE advanced_material_imports "
|
||||||
|
"SET recognition_prompt = NULL, recognition_negative_prompt = NULL"
|
||||||
|
)
|
||||||
|
if "advanced_material_validation_attempts" in tables:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE advanced_material_validation_attempts "
|
||||||
|
"SET prompt = ?, negative_prompt = NULL, adjustment_text = NULL, decision_notes = NULL",
|
||||||
|
(PROMPT_BACKUP_PLACEHOLDER,),
|
||||||
|
)
|
||||||
|
if "advanced_materials" in tables:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE advanced_materials SET prompt = ?, negative_prompt = NULL",
|
||||||
|
(PROMPT_BACKUP_PLACEHOLDER,),
|
||||||
|
)
|
||||||
|
if "advanced_style_sources" in tables:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE advanced_style_sources "
|
||||||
|
"SET recognition_prompt = NULL, recognition_negative_prompt = NULL"
|
||||||
|
)
|
||||||
|
if "advanced_style_consensus_runs" in tables:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE advanced_style_consensus_runs SET prompt = NULL, negative_prompt = NULL"
|
||||||
|
)
|
||||||
|
if "advanced_style_validation_cases" in tables:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE advanced_style_validation_cases "
|
||||||
|
"SET content_prompt = ?, final_prompt = ?, negative_prompt = NULL",
|
||||||
|
(PROMPT_BACKUP_PLACEHOLDER, PROMPT_BACKUP_PLACEHOLDER),
|
||||||
|
)
|
||||||
if "generation_images" in tables:
|
if "generation_images" in tables:
|
||||||
conn.execute("UPDATE generation_images SET positive_prompt = NULL, negative_prompt = NULL")
|
conn.execute("UPDATE generation_images SET positive_prompt = NULL, negative_prompt = NULL")
|
||||||
json_columns = {
|
json_columns = {
|
||||||
"materials": ("material_id", ("metadata_json",)),
|
"materials": ("material_id", ("metadata_json",)),
|
||||||
|
"advanced_material_imports": ("import_id", ("recognition_result_json", "error_json", "metadata_json")),
|
||||||
|
"advanced_material_validation_attempts": ("attempt_id", ("usage_json", "error_json", "metadata_json")),
|
||||||
|
"advanced_materials": ("material_id", ("capsule_json", "metadata_json")),
|
||||||
|
"advanced_style_sources": (
|
||||||
|
"source_id",
|
||||||
|
("recognition_tags_json", "recognition_result_json", "error_json", "metadata_json"),
|
||||||
|
),
|
||||||
|
"advanced_style_consensus_runs": (
|
||||||
|
"consensus_id",
|
||||||
|
("source_ids_json", "tags_json", "result_json", "error_json", "metadata_json"),
|
||||||
|
),
|
||||||
|
"advanced_style_validation_cases": (
|
||||||
|
"case_id",
|
||||||
|
("usage_json", "style_review_json", "error_json", "metadata_json"),
|
||||||
|
),
|
||||||
"generation_images": ("image_id", ("metadata_json",)),
|
"generation_images": ("image_id", ("metadata_json",)),
|
||||||
"generation_tasks": ("task_id", ("request_json", "result_json", "metadata_json")),
|
"generation_tasks": ("task_id", ("request_json", "result_json", "metadata_json")),
|
||||||
"audit_logs": ("audit_id", ("before_snapshot", "after_snapshot", "metadata_json")),
|
"audit_logs": ("audit_id", ("before_snapshot", "after_snapshot", "metadata_json")),
|
||||||
|
|
@ -282,7 +329,7 @@ def _strip_sensitive_records(
|
||||||
for key, item in value.items():
|
for key, item in value.items():
|
||||||
lowered = str(key).lower()
|
lowered = str(key).lower()
|
||||||
if not include_prompt_records and lowered in prompt_keys:
|
if not include_prompt_records and lowered in prompt_keys:
|
||||||
result[key] = "[EXCLUDED_FROM_BACKUP]"
|
result[key] = PROMPT_BACKUP_PLACEHOLDER
|
||||||
continue
|
continue
|
||||||
if not include_moderation_records and lowered in moderation_keys:
|
if not include_moderation_records and lowered in moderation_keys:
|
||||||
continue
|
continue
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ from urllib.parse import urlsplit
|
||||||
|
|
||||||
from backend.dto.common import ApiError, ErrorCode
|
from backend.dto.common import ApiError, ErrorCode
|
||||||
from backend.services.image_service import ImageService
|
from backend.services.image_service import ImageService
|
||||||
|
from backend.services.material_catalog_resolver import is_trusted_advanced_metadata
|
||||||
from core.storage import VfsStorage
|
from core.storage import VfsStorage
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -61,29 +62,29 @@ class GenerationReferenceService:
|
||||||
)
|
)
|
||||||
if self.material_resolver is not None:
|
if self.material_resolver is not None:
|
||||||
for material_id, source in _material_reference_candidates(payload):
|
for material_id, source in _material_reference_candidates(payload):
|
||||||
prepared, canonical_key, byte_count = self._resolve_material(
|
for prepared, canonical_key, byte_count in self._resolve_material_references(
|
||||||
material_id,
|
material_id,
|
||||||
source=source,
|
source=source,
|
||||||
storage_cache=storage_cache,
|
storage_cache=storage_cache,
|
||||||
)
|
):
|
||||||
total_bytes = _append_reference(
|
total_bytes = _append_reference(
|
||||||
resolved,
|
resolved,
|
||||||
seen,
|
seen,
|
||||||
prepared,
|
prepared,
|
||||||
canonical_key,
|
canonical_key,
|
||||||
byte_count,
|
byte_count,
|
||||||
total_bytes,
|
total_bytes,
|
||||||
source,
|
source,
|
||||||
)
|
)
|
||||||
return tuple(resolved)
|
return tuple(resolved)
|
||||||
|
|
||||||
def _resolve_material(
|
def _resolve_material_references(
|
||||||
self,
|
self,
|
||||||
material_id: str,
|
material_id: str,
|
||||||
*,
|
*,
|
||||||
source: str,
|
source: str,
|
||||||
storage_cache: dict[str, tuple[str, int]],
|
storage_cache: dict[str, tuple[str, int]],
|
||||||
) -> tuple[str, str, int]:
|
) -> list[tuple[str, str, int]]:
|
||||||
material = self.material_resolver.get_material(material_id) if self.material_resolver else None
|
material = self.material_resolver.get_material(material_id) if self.material_resolver else None
|
||||||
if material is None:
|
if material is None:
|
||||||
raise ApiError(
|
raise ApiError(
|
||||||
|
|
@ -101,6 +102,12 @@ class GenerationReferenceService:
|
||||||
"source": source,
|
"source": source,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
metadata = material.metadata if isinstance(getattr(material, "metadata", None), dict) else {}
|
||||||
|
if is_trusted_advanced_metadata(metadata) and isinstance(metadata.get("style_set"), dict):
|
||||||
|
# Quick/direct generation consumes the verified style capsule as
|
||||||
|
# text. Source images are deliberately withheld to avoid leaking
|
||||||
|
# sample characters, clothing, composition or scenery.
|
||||||
|
return []
|
||||||
image_uri = _optional_text(material.image_uri)
|
image_uri = _optional_text(material.image_uri)
|
||||||
if not image_uri:
|
if not image_uri:
|
||||||
raise ApiError(
|
raise ApiError(
|
||||||
|
|
@ -108,7 +115,9 @@ class GenerationReferenceService:
|
||||||
"confirmed reference material has no image",
|
"confirmed reference material has no image",
|
||||||
{"material_id": material_id, "source": source},
|
{"material_id": material_id, "source": source},
|
||||||
)
|
)
|
||||||
return self._prepare_uri(image_uri, source=source, storage_cache=storage_cache)
|
# Detailed persisted rounds expand trusted style representatives only
|
||||||
|
# after the concrete route capabilities are known.
|
||||||
|
return [self._prepare_uri(image_uri, source=source, storage_cache=storage_cache)]
|
||||||
|
|
||||||
def _resolve_candidate(
|
def _resolve_candidate(
|
||||||
self,
|
self,
|
||||||
|
|
|
||||||
|
|
@ -222,7 +222,8 @@ class GenerationService:
|
||||||
node=node,
|
node=node,
|
||||||
payload=enriched_payload,
|
payload=enriched_payload,
|
||||||
)
|
)
|
||||||
execution_payload = _apply_round_reference_snapshot(enriched_payload, material_snapshot)
|
routed_material_snapshot = _route_aware_reference_snapshot(material_snapshot, route_resolution)
|
||||||
|
execution_payload = _apply_round_reference_snapshot(enriched_payload, routed_material_snapshot)
|
||||||
execution_payload, ephemeral_reference_count = _strip_ephemeral_image_data_urls(execution_payload)
|
execution_payload, ephemeral_reference_count = _strip_ephemeral_image_data_urls(execution_payload)
|
||||||
if ephemeral_reference_count:
|
if ephemeral_reference_count:
|
||||||
raise ApiError(
|
raise ApiError(
|
||||||
|
|
@ -250,7 +251,7 @@ class GenerationService:
|
||||||
)
|
)
|
||||||
reference_snapshot = {
|
reference_snapshot = {
|
||||||
**provided_reference_snapshot,
|
**provided_reference_snapshot,
|
||||||
**material_snapshot,
|
**routed_material_snapshot,
|
||||||
"reference_binding_mapping": reference_mapping,
|
"reference_binding_mapping": reference_mapping,
|
||||||
}
|
}
|
||||||
reference_snapshot, snapshot_ephemeral_count = _strip_ephemeral_image_data_urls(reference_snapshot)
|
reference_snapshot, snapshot_ephemeral_count = _strip_ephemeral_image_data_urls(reference_snapshot)
|
||||||
|
|
@ -2195,6 +2196,112 @@ def _apply_round_reference_snapshot(
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _route_aware_reference_snapshot(
|
||||||
|
snapshot: dict[str, Any],
|
||||||
|
route_resolution: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Select frozen style references according to the resolved adapter.
|
||||||
|
|
||||||
|
Ordinary materials and temporary references retain their legacy primary-
|
||||||
|
image behavior. A verified style set may add up to two representative
|
||||||
|
images only when the route explicitly supports semantic reference roles;
|
||||||
|
the adapter's global ``max_reference_images`` cap is then applied to the
|
||||||
|
final immutable list.
|
||||||
|
"""
|
||||||
|
|
||||||
|
result = copy.deepcopy(snapshot if isinstance(snapshot, dict) else {})
|
||||||
|
resolution = route_resolution if isinstance(route_resolution, dict) else {}
|
||||||
|
settings = resolution.get("settings") if isinstance(resolution.get("settings"), dict) else {}
|
||||||
|
capabilities = (
|
||||||
|
resolution.get("capabilities")
|
||||||
|
if isinstance(resolution.get("capabilities"), dict)
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
supports_roles = _route_capability_bool(
|
||||||
|
settings,
|
||||||
|
capabilities,
|
||||||
|
"supports_reference_roles",
|
||||||
|
) is True
|
||||||
|
supports_reference_images = _route_capability_bool(
|
||||||
|
settings,
|
||||||
|
capabilities,
|
||||||
|
"reference_images",
|
||||||
|
"supports_reference_images",
|
||||||
|
)
|
||||||
|
supports_style_multi_reference = supports_roles and supports_reference_images is not False
|
||||||
|
|
||||||
|
raw_limit = settings.get("max_reference_images")
|
||||||
|
if raw_limit is None:
|
||||||
|
raw_limit = capabilities.get("max_reference_images")
|
||||||
|
try:
|
||||||
|
max_references = min(max(int(raw_limit), 0), 16) if raw_limit is not None else 16
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
max_references = 16
|
||||||
|
|
||||||
|
references: list[str] = []
|
||||||
|
materials = result.get("materials") if isinstance(result.get("materials"), list) else []
|
||||||
|
for material in materials:
|
||||||
|
if not isinstance(material, dict):
|
||||||
|
continue
|
||||||
|
primary = _optional_text(material.get("image_uri"))
|
||||||
|
metadata = material.get("metadata") if isinstance(material.get("metadata"), dict) else {}
|
||||||
|
is_style_set = isinstance(metadata.get("style_set"), dict)
|
||||||
|
if is_style_set and supports_style_multi_reference:
|
||||||
|
candidates = _string_list(material.get("reference_image_uris"))
|
||||||
|
if primary and primary not in candidates:
|
||||||
|
candidates.insert(0, primary)
|
||||||
|
selected = candidates[:3]
|
||||||
|
else:
|
||||||
|
selected = [primary] if primary else []
|
||||||
|
for uri in selected:
|
||||||
|
if uri and uri not in references:
|
||||||
|
references.append(uri)
|
||||||
|
|
||||||
|
temporary = (
|
||||||
|
result.get("temporary_references")
|
||||||
|
if isinstance(result.get("temporary_references"), list)
|
||||||
|
else []
|
||||||
|
)
|
||||||
|
for item in temporary:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
uri = _optional_text(item.get("image_uri"))
|
||||||
|
if uri and uri not in references:
|
||||||
|
references.append(uri)
|
||||||
|
|
||||||
|
result["reference_uris"] = references[:max_references]
|
||||||
|
result["reference_route_policy"] = {
|
||||||
|
"supports_reference_roles": supports_roles,
|
||||||
|
"supports_reference_images": supports_reference_images,
|
||||||
|
"style_multi_reference_enabled": supports_style_multi_reference,
|
||||||
|
"max_reference_images": max_references,
|
||||||
|
"selected_reference_count": len(result["reference_uris"]),
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _route_capability_bool(
|
||||||
|
settings: dict[str, Any],
|
||||||
|
capabilities: dict[str, Any],
|
||||||
|
*keys: str,
|
||||||
|
) -> bool | None:
|
||||||
|
for source in (settings, capabilities):
|
||||||
|
for key in keys:
|
||||||
|
if key not in source:
|
||||||
|
continue
|
||||||
|
value = source.get(key)
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
if isinstance(value, (int, float)):
|
||||||
|
return bool(value)
|
||||||
|
text = str(value or "").strip().casefold()
|
||||||
|
if text in {"1", "true", "yes", "on", "enabled"}:
|
||||||
|
return True
|
||||||
|
if text in {"0", "false", "no", "off", "disabled", ""}:
|
||||||
|
return False
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _round_timeout_seconds(request: dict[str, Any], route_resolution: Any) -> int:
|
def _round_timeout_seconds(request: dict[str, Any], route_resolution: Any) -> int:
|
||||||
resolution = route_resolution if isinstance(route_resolution, dict) else {}
|
resolution = route_resolution if isinstance(route_resolution, dict) else {}
|
||||||
settings = resolution.get("settings") if isinstance(resolution.get("settings"), dict) else {}
|
settings = resolution.get("settings") if isinstance(resolution.get("settings"), dict) else {}
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,30 @@ class MaterialAnalyticsService:
|
||||||
conn = self.database.connect()
|
conn = self.database.connect()
|
||||||
try:
|
try:
|
||||||
materials = conn.execute("SELECT recognition_status, metadata_json FROM materials WHERE recognition_status != 'archived'").fetchall()
|
materials = conn.execute("SELECT recognition_status, metadata_json FROM materials WHERE recognition_status != 'archived'").fetchall()
|
||||||
|
advanced_materials = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT material.status, material.metadata_json, attempt.fidelity_score
|
||||||
|
FROM advanced_materials AS material
|
||||||
|
LEFT JOIN advanced_material_validation_attempts AS attempt
|
||||||
|
ON attempt.attempt_id = material.accepted_attempt_id
|
||||||
|
WHERE material.status != 'archived'
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
advanced_attempts = conn.execute(
|
||||||
|
"SELECT status, fidelity_score FROM advanced_material_validation_attempts"
|
||||||
|
).fetchall()
|
||||||
|
style_imports = conn.execute(
|
||||||
|
"SELECT status, metadata_json FROM advanced_material_imports"
|
||||||
|
).fetchall()
|
||||||
|
style_sources = conn.execute(
|
||||||
|
"SELECT status FROM advanced_style_sources"
|
||||||
|
).fetchall()
|
||||||
|
style_consensus_runs = conn.execute(
|
||||||
|
"SELECT status FROM advanced_style_consensus_runs"
|
||||||
|
).fetchall()
|
||||||
|
style_validation_cases = conn.execute(
|
||||||
|
"SELECT status, fidelity_score FROM advanced_style_validation_cases"
|
||||||
|
).fetchall()
|
||||||
audits = conn.execute("SELECT action, after_snapshot, metadata_json FROM audit_logs WHERE action IN ('wardrobe_match','apply_wardrobe_template','recognize_material','renormalize_material')").fetchall()
|
audits = conn.execute("SELECT action, after_snapshot, metadata_json FROM audit_logs WHERE action IN ('wardrobe_match','apply_wardrobe_template','recognize_material','renormalize_material')").fetchall()
|
||||||
tasks = conn.execute("SELECT model_route, request_json, metadata_json FROM generation_tasks").fetchall()
|
tasks = conn.execute("SELECT model_route, request_json, metadata_json FROM generation_tasks").fetchall()
|
||||||
finally:
|
finally:
|
||||||
|
|
@ -62,6 +86,26 @@ class MaterialAnalyticsService:
|
||||||
route_reasons[str(route.get("reason") or "unknown")] += 1
|
route_reasons[str(route.get("reason") or "unknown")] += 1
|
||||||
route_counts[str(row["model_route"] or route.get("selected_route") or "unresolved")] += 1
|
route_counts[str(row["model_route"] or route.get("selected_route") or "unresolved")] += 1
|
||||||
total = len(materials)
|
total = len(materials)
|
||||||
|
accepted_advanced = sum(1 for row in advanced_materials if str(row["status"]) == "active")
|
||||||
|
active_style_sets = sum(
|
||||||
|
1
|
||||||
|
for row in advanced_materials
|
||||||
|
if str(row["status"]) == "active" and _is_style_set_metadata(_json(row["metadata_json"]))
|
||||||
|
)
|
||||||
|
style_set_import_rows = [
|
||||||
|
row for row in style_imports if _is_style_set_metadata(_json(row["metadata_json"]))
|
||||||
|
]
|
||||||
|
style_source_statuses = Counter(str(row["status"] or "unknown") for row in style_sources)
|
||||||
|
style_consensus_statuses = Counter(str(row["status"] or "unknown") for row in style_consensus_runs)
|
||||||
|
style_case_statuses = Counter(str(row["status"] or "unknown") for row in style_validation_cases)
|
||||||
|
style_case_scores = [
|
||||||
|
float(row["fidelity_score"])
|
||||||
|
for row in style_validation_cases
|
||||||
|
if row["fidelity_score"] is not None
|
||||||
|
]
|
||||||
|
reviewed_attempts = [row for row in advanced_attempts if str(row["status"]) in {"accepted", "rejected"}]
|
||||||
|
accepted_attempts = sum(1 for row in reviewed_attempts if str(row["status"]) == "accepted")
|
||||||
|
scored_attempts = [float(row["fidelity_score"]) for row in reviewed_attempts if row["fidelity_score"] is not None]
|
||||||
return {
|
return {
|
||||||
"materials": {
|
"materials": {
|
||||||
"total": total,
|
"total": total,
|
||||||
|
|
@ -71,6 +115,30 @@ class MaterialAnalyticsService:
|
||||||
"needs_confirmation": needs_confirmation,
|
"needs_confirmation": needs_confirmation,
|
||||||
"categories": dict(category_counts),
|
"categories": dict(category_counts),
|
||||||
},
|
},
|
||||||
|
"advanced_materials": {
|
||||||
|
"active": accepted_advanced,
|
||||||
|
"active_style_sets": active_style_sets,
|
||||||
|
"validation_attempts": len(advanced_attempts),
|
||||||
|
"reviewed_attempts": len(reviewed_attempts),
|
||||||
|
"acceptance_rate": round(accepted_attempts / len(reviewed_attempts), 4) if reviewed_attempts else 0.0,
|
||||||
|
"average_fidelity_score": round(sum(scored_attempts) / len(scored_attempts), 4) if scored_attempts else None,
|
||||||
|
},
|
||||||
|
"advanced_style_sets": {
|
||||||
|
"imports": len(style_set_import_rows),
|
||||||
|
"accepted_imports": sum(1 for row in style_set_import_rows if str(row["status"]) == "accepted"),
|
||||||
|
"active_materials": active_style_sets,
|
||||||
|
"sources": len(style_sources),
|
||||||
|
"source_statuses": dict(style_source_statuses),
|
||||||
|
"consensus_runs": len(style_consensus_runs),
|
||||||
|
"consensus_statuses": dict(style_consensus_statuses),
|
||||||
|
"validation_cases": len(style_validation_cases),
|
||||||
|
"validation_case_statuses": dict(style_case_statuses),
|
||||||
|
"average_case_fidelity_score": (
|
||||||
|
round(sum(style_case_scores) / len(style_case_scores), 4)
|
||||||
|
if style_case_scores
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
},
|
||||||
"composition": {
|
"composition": {
|
||||||
"runs": composition_count,
|
"runs": composition_count,
|
||||||
"conflicts": conflicts,
|
"conflicts": conflicts,
|
||||||
|
|
@ -95,3 +163,11 @@ def _json(value: Any) -> dict[str, Any]:
|
||||||
except (TypeError, json.JSONDecodeError):
|
except (TypeError, json.JSONDecodeError):
|
||||||
return {}
|
return {}
|
||||||
return parsed if isinstance(parsed, dict) else {}
|
return parsed if isinstance(parsed, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _is_style_set_metadata(metadata: dict[str, Any]) -> bool:
|
||||||
|
return (
|
||||||
|
str(metadata.get("workflow_kind") or "").strip().casefold() == "style_set"
|
||||||
|
or isinstance(metadata.get("style_set"), dict)
|
||||||
|
or metadata.get("style_set") is True
|
||||||
|
)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,210 @@
|
||||||
|
"""Resolve normal and verified advanced materials through one trusted catalog.
|
||||||
|
|
||||||
|
The two libraries deliberately keep separate persistence models. Generation
|
||||||
|
and workflow code, however, only need the stable :class:`Material` contract.
|
||||||
|
This adapter is the trust boundary between persisted user-editable metadata and
|
||||||
|
the composition priority rules: reserved catalog fields are always replaced by
|
||||||
|
server-derived values and cannot be promoted by writing ordinary metadata.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from backend.dto.advanced_material_dto import AdvancedMaterial
|
||||||
|
from backend.dto.material_dto import Material, MaterialCategory
|
||||||
|
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
|
||||||
|
from database.repositories.material_repository import MaterialRepository
|
||||||
|
|
||||||
|
|
||||||
|
ADVANCED_MATERIAL_ID_PREFIX = "advmat_"
|
||||||
|
ADVANCED_VERIFIED_PRIORITY = 100
|
||||||
|
_CATALOG_RESERVED_METADATA_KEYS = frozenset(
|
||||||
|
{"library_kind", "priority_class", "material_priority", "verification"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CatalogMaterialMetadata(dict[str, Any]):
|
||||||
|
"""Dict-compatible metadata carrying an in-process catalog trust marker.
|
||||||
|
|
||||||
|
The marker is intentionally an attribute rather than a serializable key.
|
||||||
|
Data loaded from JSON can therefore never manufacture the marker. The
|
||||||
|
object remains JSON-serializable anywhere the existing ``Material`` DTO is
|
||||||
|
serialized.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__slots__ = ("_advanced_verified",)
|
||||||
|
|
||||||
|
def __init__(self, value: dict[str, Any], *, advanced_verified: bool):
|
||||||
|
super().__init__(value)
|
||||||
|
self._advanced_verified = bool(advanced_verified)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def advanced_verified(self) -> bool:
|
||||||
|
return self._advanced_verified
|
||||||
|
|
||||||
|
|
||||||
|
def is_trusted_advanced_metadata(value: Any) -> bool:
|
||||||
|
"""Return whether metadata was resolved from an active advanced record."""
|
||||||
|
|
||||||
|
return (
|
||||||
|
isinstance(value, CatalogMaterialMetadata)
|
||||||
|
and value.advanced_verified
|
||||||
|
and value.get("library_kind") == "advanced"
|
||||||
|
and value.get("priority_class") == "advanced_verified"
|
||||||
|
and value.get("material_priority") == ADVANCED_VERIFIED_PRIORITY
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MaterialCatalogResolver:
|
||||||
|
"""Expose normal and accepted advanced materials via the legacy DTO."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
materials: MaterialRepository,
|
||||||
|
advanced_materials: AdvancedMaterialRepository,
|
||||||
|
):
|
||||||
|
self.materials = materials
|
||||||
|
self.advanced_materials = advanced_materials
|
||||||
|
|
||||||
|
def get_material(self, material_id: str) -> Material | None:
|
||||||
|
normalized_id = str(material_id or "").strip()
|
||||||
|
if not normalized_id:
|
||||||
|
return None
|
||||||
|
if normalized_id.startswith(ADVANCED_MATERIAL_ID_PREFIX):
|
||||||
|
advanced = self.advanced_materials.get_material(normalized_id)
|
||||||
|
if advanced is None or advanced.status != "active":
|
||||||
|
return None
|
||||||
|
return self._advanced_to_material(advanced)
|
||||||
|
material = self.materials.get_material(normalized_id)
|
||||||
|
return self._normal_material(material) if material is not None else None
|
||||||
|
|
||||||
|
def get_category(self, category_id: str) -> MaterialCategory | None:
|
||||||
|
return self.materials.get_category(category_id)
|
||||||
|
|
||||||
|
def update_material(self, material_id: str, payload: dict[str, Any]) -> Material | None:
|
||||||
|
"""Update restoration feedback without crossing the library boundary.
|
||||||
|
|
||||||
|
Catalog identity and priority fields remain server-owned even when the
|
||||||
|
caller supplies a complete metadata replacement.
|
||||||
|
"""
|
||||||
|
|
||||||
|
normalized_id = str(material_id or "").strip()
|
||||||
|
if normalized_id.startswith(ADVANCED_MATERIAL_ID_PREFIX):
|
||||||
|
current = self.advanced_materials.get_material(normalized_id)
|
||||||
|
if current is None or current.status != "active":
|
||||||
|
return None
|
||||||
|
update = dict(payload or {})
|
||||||
|
if "metadata" in update:
|
||||||
|
update["metadata"] = _without_catalog_fields(update.get("metadata"))
|
||||||
|
updated = self.advanced_materials.update_material(normalized_id, update)
|
||||||
|
return (
|
||||||
|
self._advanced_to_material(updated)
|
||||||
|
if updated is not None and updated.status == "active"
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
update = dict(payload or {})
|
||||||
|
if "metadata" in update:
|
||||||
|
update["metadata"] = _without_catalog_fields(update.get("metadata"))
|
||||||
|
updated = self.materials.update_material(normalized_id, update)
|
||||||
|
return self._normal_material(updated) if updated is not None else None
|
||||||
|
|
||||||
|
def _normal_material(self, material: Material) -> Material:
|
||||||
|
metadata = CatalogMaterialMetadata(
|
||||||
|
{
|
||||||
|
**_without_catalog_fields(material.metadata),
|
||||||
|
"library_kind": "standard",
|
||||||
|
"priority_class": "standard",
|
||||||
|
"material_priority": 0,
|
||||||
|
"verification": {},
|
||||||
|
},
|
||||||
|
advanced_verified=False,
|
||||||
|
)
|
||||||
|
return Material(
|
||||||
|
material_id=material.material_id,
|
||||||
|
category_id=material.category_id,
|
||||||
|
display_name=material.display_name,
|
||||||
|
image_uri=material.image_uri,
|
||||||
|
thumbnail_uri=material.thumbnail_uri,
|
||||||
|
prompt=material.prompt,
|
||||||
|
negative_prompt=material.negative_prompt,
|
||||||
|
tags=list(material.tags),
|
||||||
|
recognition_status=material.recognition_status,
|
||||||
|
metadata=metadata,
|
||||||
|
created_at=material.created_at,
|
||||||
|
updated_at=material.updated_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _advanced_to_material(self, material: AdvancedMaterial) -> Material:
|
||||||
|
attempt = self.advanced_materials.get_attempt(material.accepted_attempt_id)
|
||||||
|
verification: dict[str, Any] = {
|
||||||
|
"status": "accepted",
|
||||||
|
"import_id": material.import_id,
|
||||||
|
"accepted_attempt_id": material.accepted_attempt_id,
|
||||||
|
"source_image_uri": material.source_image_uri,
|
||||||
|
"validation_image_uri": material.validation_image_uri,
|
||||||
|
"validation_thumbnail_uri": material.validation_thumbnail_uri,
|
||||||
|
"accepted_at": material.accepted_at,
|
||||||
|
}
|
||||||
|
if attempt is not None:
|
||||||
|
verification.update(
|
||||||
|
{
|
||||||
|
"attempt_number": attempt.attempt_number,
|
||||||
|
"fidelity_score": attempt.fidelity_score,
|
||||||
|
"decision": attempt.decision,
|
||||||
|
"decision_notes": attempt.decision_notes,
|
||||||
|
"model_route": attempt.model_route,
|
||||||
|
"decided_at": attempt.decided_at,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
metadata = _without_catalog_fields(material.metadata)
|
||||||
|
capsules = _generation_capsules(material.capsule, metadata)
|
||||||
|
if capsules:
|
||||||
|
metadata["generation_capsules"] = capsules
|
||||||
|
metadata = CatalogMaterialMetadata(
|
||||||
|
{
|
||||||
|
**metadata,
|
||||||
|
"library_kind": "advanced",
|
||||||
|
"priority_class": "advanced_verified",
|
||||||
|
"material_priority": ADVANCED_VERIFIED_PRIORITY,
|
||||||
|
"verification": verification,
|
||||||
|
},
|
||||||
|
advanced_verified=True,
|
||||||
|
)
|
||||||
|
return Material(
|
||||||
|
material_id=material.material_id,
|
||||||
|
category_id=material.category_id,
|
||||||
|
display_name=material.display_name,
|
||||||
|
image_uri=material.source_image_uri,
|
||||||
|
thumbnail_uri=material.source_thumbnail_uri,
|
||||||
|
prompt=material.prompt,
|
||||||
|
negative_prompt=material.negative_prompt,
|
||||||
|
tags=list(material.tags),
|
||||||
|
recognition_status="confirmed",
|
||||||
|
metadata=metadata,
|
||||||
|
created_at=material.created_at,
|
||||||
|
updated_at=material.updated_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _without_catalog_fields(value: Any) -> dict[str, Any]:
|
||||||
|
source = value if isinstance(value, dict) else {}
|
||||||
|
return {
|
||||||
|
str(key): deepcopy(child)
|
||||||
|
for key, child in source.items()
|
||||||
|
if str(key) not in _CATALOG_RESERVED_METADATA_KEYS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _generation_capsules(capsule: Any, metadata: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
source = capsule if isinstance(capsule, dict) else {}
|
||||||
|
nested = source.get("generation_capsules")
|
||||||
|
if isinstance(nested, dict):
|
||||||
|
return deepcopy(nested)
|
||||||
|
if any(isinstance(source.get(tier), dict) for tier in ("compact", "standard", "detailed")):
|
||||||
|
return deepcopy(source)
|
||||||
|
if source:
|
||||||
|
return {"detailed": deepcopy(source)}
|
||||||
|
existing = metadata.get("generation_capsules")
|
||||||
|
return deepcopy(existing) if isinstance(existing, dict) else {}
|
||||||
|
|
@ -114,7 +114,14 @@ class MaterialNormalizationService:
|
||||||
now = _utc_now()
|
now = _utc_now()
|
||||||
payload = deepcopy(dict(structured_data))
|
payload = deepcopy(dict(structured_data))
|
||||||
raw_section = payload.get("raw_analysis") if isinstance(payload.get("raw_analysis"), dict) else payload
|
raw_section = payload.get("raw_analysis") if isinstance(payload.get("raw_analysis"), dict) else payload
|
||||||
raw_attributes = self._normalize_attributes(raw_section.get("attributes"), confidence)
|
profile_input = payload.get("normalized_asset_profile")
|
||||||
|
if not isinstance(profile_input, dict):
|
||||||
|
profile_input = payload.get("asset_profile") if isinstance(payload.get("asset_profile"), dict) else {}
|
||||||
|
profile_attributes = self._normalize_attributes(profile_input.get("attributes"), confidence)
|
||||||
|
raw_attributes = {
|
||||||
|
**profile_attributes,
|
||||||
|
**self._normalize_attributes(raw_section.get("attributes"), confidence),
|
||||||
|
}
|
||||||
if not raw_attributes:
|
if not raw_attributes:
|
||||||
raw_attributes = self._attributes_from_legacy(prompt, tags, confidence)
|
raw_attributes = self._attributes_from_legacy(prompt, tags, confidence)
|
||||||
raw_analysis = {
|
raw_analysis = {
|
||||||
|
|
@ -127,9 +134,6 @@ class MaterialNormalizationService:
|
||||||
"source_payload": payload,
|
"source_payload": payload,
|
||||||
}
|
}
|
||||||
|
|
||||||
profile_input = payload.get("normalized_asset_profile")
|
|
||||||
if not isinstance(profile_input, dict):
|
|
||||||
profile_input = payload.get("asset_profile") if isinstance(payload.get("asset_profile"), dict) else {}
|
|
||||||
normalized = self._build_profile(
|
normalized = self._build_profile(
|
||||||
profile_input,
|
profile_input,
|
||||||
raw_attributes=raw_attributes,
|
raw_attributes=raw_attributes,
|
||||||
|
|
@ -195,6 +199,9 @@ class MaterialNormalizationService:
|
||||||
item.get("source_state") != "observed" or float(item.get("confidence") or 0.0) < 0.80
|
item.get("source_state") != "observed" or float(item.get("confidence") or 0.0) < 0.80
|
||||||
for item in raw_attributes.values()
|
for item in raw_attributes.values()
|
||||||
)
|
)
|
||||||
|
must_preserve = _string_list(value.get("must_preserve"))
|
||||||
|
if category == "style" and not must_preserve:
|
||||||
|
must_preserve = _attribute_prompt_parts(attributes)[:16]
|
||||||
return {
|
return {
|
||||||
"schema_version": MATERIAL_SCHEMA_VERSION,
|
"schema_version": MATERIAL_SCHEMA_VERSION,
|
||||||
"prompt_version": MATERIAL_PROMPT_VERSION,
|
"prompt_version": MATERIAL_PROMPT_VERSION,
|
||||||
|
|
@ -204,7 +211,7 @@ class MaterialNormalizationService:
|
||||||
"body_slots": body_slots,
|
"body_slots": body_slots,
|
||||||
"wear_layer": wear_layer,
|
"wear_layer": wear_layer,
|
||||||
"attributes": attributes,
|
"attributes": attributes,
|
||||||
"must_preserve": _string_list(value.get("must_preserve")),
|
"must_preserve": must_preserve,
|
||||||
"forbidden_changes": _string_list(value.get("forbidden_changes")) or _split_prompt(negative_prompt),
|
"forbidden_changes": _string_list(value.get("forbidden_changes")) or _split_prompt(negative_prompt),
|
||||||
"tags": sorted(set(tags)),
|
"tags": sorted(set(tags)),
|
||||||
"confidence": _confidence(value.get("confidence"), confidence),
|
"confidence": _confidence(value.get("confidence"), confidence),
|
||||||
|
|
|
||||||
|
|
@ -860,9 +860,16 @@ def _vision_provider_error(exc: VisionProviderError) -> dict[str, Any]:
|
||||||
"provider_id": _optional_text(exc.provider_id) or "unknown",
|
"provider_id": _optional_text(exc.provider_id) or "unknown",
|
||||||
"status_code": exc.status_code,
|
"status_code": exc.status_code,
|
||||||
"error_type": _optional_text(exc.error_type) or "provider_error",
|
"error_type": _optional_text(exc.error_type) or "provider_error",
|
||||||
|
"response_issue": str(exc)[:300],
|
||||||
}
|
}
|
||||||
if isinstance(exc.details.get("retryable"), bool):
|
if isinstance(exc.details.get("retryable"), bool):
|
||||||
failure["retryable"] = exc.details["retryable"]
|
failure["retryable"] = exc.details["retryable"]
|
||||||
|
reason = _optional_text(exc.details.get("reason") or exc.details.get("parse_error"))
|
||||||
|
if reason:
|
||||||
|
failure["reason"] = reason[:500]
|
||||||
|
structured_keys = exc.details.get("structured_keys")
|
||||||
|
if isinstance(structured_keys, list):
|
||||||
|
failure["structured_keys"] = [str(item) for item in structured_keys[:50]]
|
||||||
return failure
|
return failure
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,13 +9,14 @@ from typing import Any
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
from backend.services.model_provider_service import ModelProviderService
|
from backend.services.model_provider_service import ModelProviderService
|
||||||
|
from core.model_route_chain import model_route_candidates
|
||||||
from core.secret_service import SecretStore, resolve_secret_value
|
from core.secret_service import SecretStore, resolve_secret_value
|
||||||
from core.remote_fetch import read_http_response_limited, validate_http_url
|
from core.remote_fetch import read_http_response_limited, validate_http_url
|
||||||
from core.image_formats import detect_image_format
|
from core.image_formats import detect_image_format
|
||||||
from core.storage import VfsStorage
|
from core.storage import VfsStorage
|
||||||
from database.db_helper import load_config_payload
|
from database.db_helper import load_config_payload
|
||||||
from engines.image_provider import FallbackImageProvider, ImageProvider, ImageProviderConfig, OpenAIImageProvider
|
from engines.image_provider import FallbackImageProvider, ImageProvider, ImageProviderConfig, OpenAIImageProvider
|
||||||
from engines.vision_provider import OpenAIVisionProvider, VisionProvider, VisionProviderConfig
|
from engines.vision_provider import FallbackVisionProvider, OpenAIVisionProvider, VisionProvider, VisionProviderConfig
|
||||||
|
|
||||||
|
|
||||||
class ModelProviderRuntime:
|
class ModelProviderRuntime:
|
||||||
|
|
@ -32,22 +33,29 @@ class ModelProviderRuntime:
|
||||||
route_name = str(route_context.get("route_name") or "").strip()
|
route_name = str(route_context.get("route_name") or "").strip()
|
||||||
if not route_name:
|
if not route_name:
|
||||||
return None
|
return None
|
||||||
resolved = self.model_provider_service.resolve_route(route_name, modality="image_generation")
|
candidates: list[dict[str, Any]] = []
|
||||||
if not resolved:
|
seen: set[str] = set()
|
||||||
|
for candidate_name in model_route_candidates(route_name):
|
||||||
|
if candidate_name.startswith("astrbot:"):
|
||||||
|
continue
|
||||||
|
candidate = self.model_provider_service.resolve_route(candidate_name, modality="image_generation")
|
||||||
|
if candidate and str(candidate.get("route_id")) not in seen:
|
||||||
|
candidates.append(candidate)
|
||||||
|
seen.add(str(candidate.get("route_id")))
|
||||||
|
if not candidates:
|
||||||
return None
|
return None
|
||||||
candidates = [resolved]
|
resolved = candidates[0]
|
||||||
route_settings = resolved.get("settings") if isinstance(resolved.get("settings"), dict) else {}
|
route_settings = resolved.get("settings") if isinstance(resolved.get("settings"), dict) else {}
|
||||||
# A model selected in the UI must only call its own provider. Generic
|
# A model selected in the UI must only call its own provider. Generic
|
||||||
# cross-provider fallback can silently switch models and used to hide
|
# cross-provider fallback can silently switch models and used to hide
|
||||||
# the selected provider's real error. Safety routing is handled by the
|
# the selected provider's real error. Safety routing is handled by the
|
||||||
# generation governance layer instead.
|
# generation governance layer instead.
|
||||||
fallback_enabled = _configured_bool(
|
fallback_enabled = len(candidates) > 1 or _configured_bool(
|
||||||
route_context.get("allow_provider_fallback"),
|
route_context.get("allow_provider_fallback"),
|
||||||
route_settings.get("allow_provider_fallback"),
|
route_settings.get("allow_provider_fallback"),
|
||||||
default=False,
|
default=False,
|
||||||
)
|
)
|
||||||
if fallback_enabled:
|
if fallback_enabled:
|
||||||
seen = {str(resolved.get("route_id"))}
|
|
||||||
excluded_routes = {str(item).strip() for item in route_context.get("excluded_fallback_routes", []) if str(item).strip()} if isinstance(route_context.get("excluded_fallback_routes"), list) else set()
|
excluded_routes = {str(item).strip() for item in route_context.get("excluded_fallback_routes", []) if str(item).strip()} if isinstance(route_context.get("excluded_fallback_routes"), list) else set()
|
||||||
fallback_routes = sorted(
|
fallback_routes = sorted(
|
||||||
self.model_provider_service.list_routes(enabled=True),
|
self.model_provider_service.list_routes(enabled=True),
|
||||||
|
|
@ -104,6 +112,16 @@ class ModelProviderRuntime:
|
||||||
route_name = str(route_context.get("route_name") or "").strip()
|
route_name = str(route_context.get("route_name") or "").strip()
|
||||||
if not route_name:
|
if not route_name:
|
||||||
return None
|
return None
|
||||||
|
providers = [
|
||||||
|
provider
|
||||||
|
for candidate in model_route_candidates(route_name)
|
||||||
|
if (provider := self._vision_provider_for_single_route(candidate)) is not None
|
||||||
|
]
|
||||||
|
if not providers:
|
||||||
|
return None
|
||||||
|
return providers[0] if len(providers) == 1 else FallbackVisionProvider(providers)
|
||||||
|
|
||||||
|
def _vision_provider_for_single_route(self, route_name: str) -> VisionProvider | None:
|
||||||
if route_name.startswith("astrbot:"):
|
if route_name.startswith("astrbot:"):
|
||||||
# AstrBot owns this provider's credentials and runtime client. Do
|
# AstrBot owns this provider's credentials and runtime client. Do
|
||||||
# not mirror those secrets into ImageStudio's provider tables.
|
# not mirror those secrets into ImageStudio's provider tables.
|
||||||
|
|
@ -149,6 +167,32 @@ class ModelProviderRuntime:
|
||||||
|
|
||||||
def structured_text_callable(self, route_name: str):
|
def structured_text_callable(self, route_name: str):
|
||||||
"""Return an OpenAI-compatible JSON completion callable for a configured route."""
|
"""Return an OpenAI-compatible JSON completion callable for a configured route."""
|
||||||
|
callables = [
|
||||||
|
completion
|
||||||
|
for candidate in model_route_candidates(route_name)
|
||||||
|
if (completion := self._structured_text_callable_for_single_route(candidate)) is not None
|
||||||
|
]
|
||||||
|
if not callables:
|
||||||
|
return None
|
||||||
|
if len(callables) == 1:
|
||||||
|
return callables[0]
|
||||||
|
|
||||||
|
def complete_with_fallback(request_payload: dict[str, Any]) -> dict[str, Any] | str:
|
||||||
|
failures: list[str] = []
|
||||||
|
for completion in callables:
|
||||||
|
try:
|
||||||
|
return completion(request_payload)
|
||||||
|
except Exception as exc:
|
||||||
|
failures.append(str(exc)[:500])
|
||||||
|
raise RuntimeError(f"all configured text routes failed: {' | '.join(failures)}")
|
||||||
|
|
||||||
|
return complete_with_fallback
|
||||||
|
|
||||||
|
def _structured_text_callable_for_single_route(self, route_name: str):
|
||||||
|
if route_name.startswith("astrbot:"):
|
||||||
|
from core.astrbot_provider_bridge import astrbot_structured_text_callable
|
||||||
|
|
||||||
|
return astrbot_structured_text_callable(route_name)
|
||||||
resolved = self.model_provider_service.resolve_route(route_name)
|
resolved = self.model_provider_service.resolve_route(route_name)
|
||||||
if not resolved:
|
if not resolved:
|
||||||
return None
|
return None
|
||||||
|
|
@ -207,6 +251,37 @@ class ModelProviderRuntime:
|
||||||
return complete
|
return complete
|
||||||
|
|
||||||
def structured_vision_callable(self, route_name: str, *, storage: VfsStorage | None = None):
|
def structured_vision_callable(self, route_name: str, *, storage: VfsStorage | None = None):
|
||||||
|
callables = [
|
||||||
|
review
|
||||||
|
for candidate in model_route_candidates(route_name)
|
||||||
|
if (review := self._structured_vision_callable_for_single_route(candidate, storage=storage)) is not None
|
||||||
|
]
|
||||||
|
if not callables:
|
||||||
|
return None
|
||||||
|
if len(callables) == 1:
|
||||||
|
return callables[0]
|
||||||
|
|
||||||
|
def review_with_fallback(request_payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
failures: list[str] = []
|
||||||
|
for review in callables:
|
||||||
|
try:
|
||||||
|
return review(request_payload)
|
||||||
|
except Exception as exc:
|
||||||
|
failures.append(str(exc)[:500])
|
||||||
|
raise RuntimeError(f"all configured vision review routes failed: {' | '.join(failures)}")
|
||||||
|
|
||||||
|
return review_with_fallback
|
||||||
|
|
||||||
|
def _structured_vision_callable_for_single_route(
|
||||||
|
self,
|
||||||
|
route_name: str,
|
||||||
|
*,
|
||||||
|
storage: VfsStorage | None = None,
|
||||||
|
):
|
||||||
|
if route_name.startswith("astrbot:"):
|
||||||
|
from core.astrbot_provider_bridge import astrbot_structured_vision_callable
|
||||||
|
|
||||||
|
return astrbot_structured_vision_callable(route_name, storage=storage)
|
||||||
resolved = self.model_provider_service.resolve_route(route_name)
|
resolved = self.model_provider_service.resolve_route(route_name)
|
||||||
if not resolved:
|
if not resolved:
|
||||||
return None
|
return None
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ from __future__ import annotations
|
||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from core.model_route_chain import model_route_candidates
|
||||||
from core.secret_service import redact_provider_secret_state
|
from core.secret_service import redact_provider_secret_state
|
||||||
from database.repositories.model_provider_repository import ModelProviderRepository
|
from database.repositories.model_provider_repository import ModelProviderRepository
|
||||||
|
|
||||||
|
|
@ -49,14 +50,21 @@ class ModelProviderService:
|
||||||
return self.repository.list_routes(enabled=enabled)
|
return self.repository.list_routes(enabled=enabled)
|
||||||
|
|
||||||
def resolve_route(self, route_name: str, *, modality: str | None = None) -> dict[str, Any] | None:
|
def resolve_route(self, route_name: str, *, modality: str | None = None) -> dict[str, Any] | None:
|
||||||
resolved = self.repository.resolve_route(route_name, modality=modality)
|
for candidate in model_route_candidates(route_name):
|
||||||
if resolved or "/" not in route_name:
|
if candidate.startswith("astrbot:"):
|
||||||
return resolved
|
continue
|
||||||
|
resolved = self.repository.resolve_route(candidate, modality=modality)
|
||||||
provider_id, model_id = route_name.split("/", 1)
|
if resolved or "/" not in candidate:
|
||||||
if not provider_id or not model_id:
|
if resolved:
|
||||||
return None
|
return resolved
|
||||||
return self.repository.resolve_provider_model(provider_id, model_id, modality=modality)
|
continue
|
||||||
|
provider_id, model_id = candidate.split("/", 1)
|
||||||
|
if not provider_id or not model_id:
|
||||||
|
continue
|
||||||
|
resolved = self.repository.resolve_provider_model(provider_id, model_id, modality=modality)
|
||||||
|
if resolved:
|
||||||
|
return resolved
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _required_text(value: Any, field: str) -> str:
|
def _required_text(value: Any, field: str) -> str:
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,31 @@ class OrphanMediaService:
|
||||||
for table, columns in (
|
for table, columns in (
|
||||||
("generation_images", ("image_uri", "thumbnail_uri")),
|
("generation_images", ("image_uri", "thumbnail_uri")),
|
||||||
("materials", ("image_uri", "thumbnail_uri")),
|
("materials", ("image_uri", "thumbnail_uri")),
|
||||||
|
(
|
||||||
|
"advanced_material_imports",
|
||||||
|
("source_image_uri", "source_thumbnail_uri"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"advanced_material_validation_attempts",
|
||||||
|
("validation_image_uri", "validation_thumbnail_uri"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"advanced_materials",
|
||||||
|
(
|
||||||
|
"source_image_uri",
|
||||||
|
"source_thumbnail_uri",
|
||||||
|
"validation_image_uri",
|
||||||
|
"validation_thumbnail_uri",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"advanced_style_sources",
|
||||||
|
("source_image_uri", "source_thumbnail_uri"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"advanced_style_validation_cases",
|
||||||
|
("validation_image_uri", "validation_thumbnail_uri"),
|
||||||
|
),
|
||||||
("character_profiles", ("avatar_image_uri",)),
|
("character_profiles", ("avatar_image_uri",)),
|
||||||
):
|
):
|
||||||
for row in conn.execute(f"SELECT {', '.join(columns)} FROM {table}").fetchall():
|
for row in conn.execute(f"SELECT {', '.join(columns)} FROM {table}").fetchall():
|
||||||
|
|
|
||||||
|
|
@ -159,9 +159,19 @@ class PromptModerationService:
|
||||||
self.reviewer = reviewer
|
self.reviewer = reviewer
|
||||||
|
|
||||||
def moderate(self, *, original_prompt: str, translated_prompt: str = "", final_prompt: str = "", negative_prompt: str = "", reference_bindings: list[dict[str, Any]] | None = None) -> PromptModerationDecision:
|
def moderate(self, *, original_prompt: str, translated_prompt: str = "", final_prompt: str = "", negative_prompt: str = "", reference_bindings: list[dict[str, Any]] | None = None) -> PromptModerationDecision:
|
||||||
text = "\n".join(_text(value) for value in (original_prompt, translated_prompt, final_prompt, negative_prompt) if _text(value))
|
positive_text = "\n".join(
|
||||||
rule = self._rule_decision(text)
|
_text(value)
|
||||||
model = self._model_decision(text, reference_bindings or [])
|
for value in (original_prompt, translated_prompt, final_prompt)
|
||||||
|
if _text(value)
|
||||||
|
)
|
||||||
|
# Negative prompts describe content that should be excluded. Treating
|
||||||
|
# words such as "nudity", "gore" or "child" there as requested
|
||||||
|
# content creates false adult/prohibited decisions.
|
||||||
|
rule = self._rule_decision(positive_text)
|
||||||
|
review_text = positive_text
|
||||||
|
if negative := _text(negative_prompt):
|
||||||
|
review_text = f"{positive_text}\n\nNegative constraints (must be excluded):\n{negative}"
|
||||||
|
model = self._model_decision(review_text, reference_bindings or [])
|
||||||
return _stricter_decision(rule, model)
|
return _stricter_decision(rule, model)
|
||||||
|
|
||||||
def _rule_decision(self, text: str) -> PromptModerationDecision:
|
def _rule_decision(self, text: str) -> PromptModerationDecision:
|
||||||
|
|
@ -185,8 +195,18 @@ class PromptModerationService:
|
||||||
return _decision("safe", 0.85, [], ["no_risk_signal"], "allow", None)
|
return _decision("safe", 0.85, [], ["no_risk_signal"], "allow", None)
|
||||||
|
|
||||||
def _model_decision(self, text: str, references: list[dict[str, Any]]) -> PromptModerationDecision | None:
|
def _model_decision(self, text: str, references: list[dict[str, Any]]) -> PromptModerationDecision | None:
|
||||||
if self.reviewer is None or not bool(self.config.get("llm_review_enabled", False)):
|
if not bool(self.config.get("llm_review_enabled", False)):
|
||||||
return None
|
return None
|
||||||
|
if self.reviewer is None:
|
||||||
|
fallback = _text(self.config.get("failure_policy") or "fail_closed")
|
||||||
|
return _decision(
|
||||||
|
"uncertain" if fallback == "confirm" else "prohibited",
|
||||||
|
0.5,
|
||||||
|
["review_unavailable"],
|
||||||
|
["moderation_service_unavailable"],
|
||||||
|
"confirm_or_reject" if fallback == "confirm" else "reject",
|
||||||
|
"内容审核模型不可用,已采用保守策略。",
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
response = self.reviewer({"text": text, "reference_bindings": references, "levels": list(RISK_LEVELS), "rules_version": self.RULES_VERSION})
|
response = self.reviewer({"text": text, "reference_bindings": references, "levels": list(RISK_LEVELS), "rules_version": self.RULES_VERSION})
|
||||||
level = _text(response.get("level"))
|
level = _text(response.get("level"))
|
||||||
|
|
@ -254,7 +274,27 @@ class GenerationRouteService:
|
||||||
|
|
||||||
|
|
||||||
class GenerationFailureClassifier:
|
class GenerationFailureClassifier:
|
||||||
CONTENT_SIGNALS = ("nsfw", "safety", "content policy", "moderation", "sexual content", "adult content", "blocked prompt", "内容审核", "敏感内容")
|
CONTENT_SIGNALS = (
|
||||||
|
"nsfw",
|
||||||
|
"safety",
|
||||||
|
"content policy",
|
||||||
|
"moderation",
|
||||||
|
"sexual content",
|
||||||
|
"adult content",
|
||||||
|
"blocked prompt",
|
||||||
|
"underage",
|
||||||
|
"child sexual",
|
||||||
|
"violence",
|
||||||
|
"gore",
|
||||||
|
"terror",
|
||||||
|
"extremism",
|
||||||
|
"内容审核",
|
||||||
|
"敏感内容",
|
||||||
|
)
|
||||||
|
ADULT_SAFETY_SIGNALS = ("nsfw", "sexual content", "adult content", "nudity", "erotic", "porn")
|
||||||
|
MINOR_SAFETY_SIGNALS = ("minor", "underage", "child sexual", "csam")
|
||||||
|
VIOLENCE_SAFETY_SIGNALS = ("violence", "violent", "gore", "dismember", "beheading", "torture")
|
||||||
|
TERROR_SAFETY_SIGNALS = ("terror", "extremism", "extremist")
|
||||||
|
|
||||||
def classify(self, failure: Mapping[str, Any] | BaseException) -> dict[str, Any]:
|
def classify(self, failure: Mapping[str, Any] | BaseException) -> dict[str, Any]:
|
||||||
if isinstance(failure, Mapping):
|
if isinstance(failure, Mapping):
|
||||||
|
|
@ -269,8 +309,19 @@ class GenerationFailureClassifier:
|
||||||
detail = f"{failure} {details}"
|
detail = f"{failure} {details}"
|
||||||
provider_id = _optional_text(getattr(failure, "provider_id", None))
|
provider_id = _optional_text(getattr(failure, "provider_id", None))
|
||||||
lower = f"{error_type} {detail}".casefold()
|
lower = f"{error_type} {detail}".casefold()
|
||||||
|
safety_reason = None
|
||||||
if any(signal in lower for signal in self.CONTENT_SIGNALS):
|
if any(signal in lower for signal in self.CONTENT_SIGNALS):
|
||||||
category = "content_safety_rejection"
|
category = "content_safety_rejection"
|
||||||
|
if any(signal in lower for signal in self.MINOR_SAFETY_SIGNALS):
|
||||||
|
safety_reason = "minor"
|
||||||
|
elif any(signal in lower for signal in self.TERROR_SAFETY_SIGNALS):
|
||||||
|
safety_reason = "terror"
|
||||||
|
elif any(signal in lower for signal in self.VIOLENCE_SAFETY_SIGNALS):
|
||||||
|
safety_reason = "violence"
|
||||||
|
elif any(signal in lower for signal in self.ADULT_SAFETY_SIGNALS):
|
||||||
|
safety_reason = "adult"
|
||||||
|
else:
|
||||||
|
safety_reason = "unknown"
|
||||||
elif "quota" in lower or "credit" in lower or "balance" in lower:
|
elif "quota" in lower or "credit" in lower or "balance" in lower:
|
||||||
category = "quota_exhausted"
|
category = "quota_exhausted"
|
||||||
elif status == 429 or "rate" in lower:
|
elif status == 429 or "rate" in lower:
|
||||||
|
|
@ -287,7 +338,14 @@ class GenerationFailureClassifier:
|
||||||
category = "upstream_error"
|
category = "upstream_error"
|
||||||
else:
|
else:
|
||||||
category = "unknown"
|
category = "unknown"
|
||||||
return {"failure_class": category, "provider_id": provider_id, "status_code": status, "error_type": error_type, "summary": _redact(detail)[:500]}
|
return {
|
||||||
|
"failure_class": category,
|
||||||
|
"safety_reason": safety_reason,
|
||||||
|
"provider_id": provider_id,
|
||||||
|
"status_code": status,
|
||||||
|
"error_type": error_type,
|
||||||
|
"summary": _redact(detail)[:500],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class ImageModerationService:
|
class ImageModerationService:
|
||||||
|
|
|
||||||
|
|
@ -102,6 +102,9 @@ class SettingsService:
|
||||||
"title": "模型分工",
|
"title": "模型分工",
|
||||||
"fields": [
|
"fields": [
|
||||||
_field("material_recognition", "string", label="素材解析路由"),
|
_field("material_recognition", "string", label="素材解析路由"),
|
||||||
|
_field("advanced_material_recognition", "string", label="进阶素材识别路由"),
|
||||||
|
_field("advanced_style_consensus", "string", label="进阶画风交叉归纳路由"),
|
||||||
|
_field("advanced_material_validation_generation", "string", label="进阶素材验证生图路由"),
|
||||||
_field("profile_parse", "string", label="角色导入解析路由"),
|
_field("profile_parse", "string", label="角色导入解析路由"),
|
||||||
_field("persona_split", "string", label="人设拆解路由"),
|
_field("persona_split", "string", label="人设拆解路由"),
|
||||||
_field("prompt_planning", "string", label="提示词规划路由"),
|
_field("prompt_planning", "string", label="提示词规划路由"),
|
||||||
|
|
@ -128,6 +131,21 @@ class SettingsService:
|
||||||
_field("category_requirements", "list", label="分类附加要求"),
|
_field("category_requirements", "list", label="分类附加要求"),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "advanced_materials",
|
||||||
|
"title": "进阶素材",
|
||||||
|
"fields": [
|
||||||
|
_field("cost_budget.enabled", "bool", label="启用验证预算守卫"),
|
||||||
|
_field("cost_budget.days", "number", label="用量统计窗口(天)"),
|
||||||
|
_field("cost_budget.max_task_count", "number", label="窗口内最大验证任务数"),
|
||||||
|
_field("cost_budget.max_image_count", "number", label="窗口内最大验证图片数"),
|
||||||
|
_field("cost_budget.max_estimated_cost", "number", label="窗口内最大估算费用"),
|
||||||
|
_field("cost_budget.price_key", "string", label="计价键(Provider 或模型 ID)"),
|
||||||
|
_field("cost_budget.per_request", "number", label="每次请求单价"),
|
||||||
|
_field("cost_budget.per_image", "number", label="每张图片单价"),
|
||||||
|
_field("cost_budget.per_1k_tokens", "number", label="每千 Token 单价"),
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "prompt_governance",
|
"key": "prompt_governance",
|
||||||
"title": "提示词与内容分流",
|
"title": "提示词与内容分流",
|
||||||
|
|
@ -180,6 +198,7 @@ class SettingsService:
|
||||||
_field("images_path", "path", label="图片目录"),
|
_field("images_path", "path", label="图片目录"),
|
||||||
_field("thumbnails_path", "path", label="缩略图目录"),
|
_field("thumbnails_path", "path", label="缩略图目录"),
|
||||||
_field("materials_path", "path", label="素材目录"),
|
_field("materials_path", "path", label="素材目录"),
|
||||||
|
_field("advanced_materials_path", "path", label="进阶素材独立目录"),
|
||||||
_field("styles_path", "path", label="风格目录"),
|
_field("styles_path", "path", label="风格目录"),
|
||||||
_field("archives_path", "path", label="归档目录"),
|
_field("archives_path", "path", label="归档目录"),
|
||||||
_field("temp_path", "path", label="临时目录"),
|
_field("temp_path", "path", label="临时目录"),
|
||||||
|
|
@ -324,6 +343,30 @@ class SettingsService:
|
||||||
days = -1
|
days = -1
|
||||||
if days < 0:
|
if days < 0:
|
||||||
errors.append({"field": f"prompt_governance.retention.{key}", "message": "retention days must be zero or greater"})
|
errors.append({"field": f"prompt_governance.retention.{key}", "message": "retention days must be zero or greater"})
|
||||||
|
advanced_materials = config.get("advanced_materials", {})
|
||||||
|
if isinstance(advanced_materials, Mapping):
|
||||||
|
budget = advanced_materials.get("cost_budget", {})
|
||||||
|
if isinstance(budget, Mapping):
|
||||||
|
for key in ("days", "max_task_count", "max_image_count"):
|
||||||
|
value = budget.get(key)
|
||||||
|
if value in (None, ""):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
normalized = int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
normalized = -1
|
||||||
|
if normalized < 0:
|
||||||
|
errors.append({"field": f"advanced_materials.cost_budget.{key}", "message": "value must be zero or greater"})
|
||||||
|
for key in ("max_estimated_cost", "per_request", "per_image", "per_1k_tokens"):
|
||||||
|
value = budget.get(key)
|
||||||
|
if value in (None, ""):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
normalized_cost = float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
normalized_cost = -1
|
||||||
|
if normalized_cost < 0:
|
||||||
|
errors.append({"field": f"advanced_materials.cost_budget.{key}", "message": "value must be zero or greater"})
|
||||||
return {"valid": not errors, "errors": errors, "warnings": warnings}
|
return {"valid": not errors, "errors": errors, "warnings": warnings}
|
||||||
|
|
||||||
def diff(self, candidate: Mapping[str, Any]) -> dict[str, Any]:
|
def diff(self, candidate: Mapping[str, Any]) -> dict[str, Any]:
|
||||||
|
|
|
||||||
|
|
@ -8,13 +8,24 @@ from uuid import uuid4
|
||||||
|
|
||||||
from backend.dto.common import ApiError, ErrorCode
|
from backend.dto.common import ApiError, ErrorCode
|
||||||
from backend.dto.wardrobe_dto import WardrobeItem
|
from backend.dto.wardrobe_dto import WardrobeItem
|
||||||
from backend.services.composition_builder import CompositionBuilder, CompositionPlan
|
from backend.services.composition_builder import (
|
||||||
|
ADVANCED_VERIFIED_PRIORITY_BONUS,
|
||||||
|
CompositionBuilder,
|
||||||
|
CompositionPlan,
|
||||||
|
)
|
||||||
|
from backend.services.material_catalog_resolver import (
|
||||||
|
MaterialCatalogResolver,
|
||||||
|
is_trusted_advanced_metadata,
|
||||||
|
)
|
||||||
from backend.services.material_normalization_service import MaterialNormalizationService
|
from backend.services.material_normalization_service import MaterialNormalizationService
|
||||||
from core.audit_service import AuditService
|
from core.audit_service import AuditService
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from database.repositories.material_repository import MaterialRepository
|
from database.repositories.material_repository import MaterialRepository
|
||||||
from database.repositories.profile_repository import ProfileRepository
|
from database.repositories.profile_repository import ProfileRepository
|
||||||
from database.repositories.wardrobe_repository import WardrobeRepository
|
from database.repositories.wardrobe_repository import (
|
||||||
|
AdvancedWardrobeRepository,
|
||||||
|
WardrobeRepository,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_WARDROBE_CATEGORIES = ("top", "bottom", "dress", "shoes", "accessory")
|
DEFAULT_WARDROBE_CATEGORIES = ("top", "bottom", "dress", "shoes", "accessory")
|
||||||
|
|
@ -27,6 +38,8 @@ class WardrobeService:
|
||||||
profile_repository: ProfileRepository,
|
profile_repository: ProfileRepository,
|
||||||
material_repository: MaterialRepository,
|
material_repository: MaterialRepository,
|
||||||
audit_service: AuditService,
|
audit_service: AuditService,
|
||||||
|
advanced_wardrobe_repository: AdvancedWardrobeRepository | None = None,
|
||||||
|
material_catalog: MaterialCatalogResolver | None = None,
|
||||||
composition_builder: CompositionBuilder | None = None,
|
composition_builder: CompositionBuilder | None = None,
|
||||||
normalization_service: MaterialNormalizationService | None = None,
|
normalization_service: MaterialNormalizationService | None = None,
|
||||||
):
|
):
|
||||||
|
|
@ -34,6 +47,8 @@ class WardrobeService:
|
||||||
self.profile_repository = profile_repository
|
self.profile_repository = profile_repository
|
||||||
self.material_repository = material_repository
|
self.material_repository = material_repository
|
||||||
self.audit_service = audit_service
|
self.audit_service = audit_service
|
||||||
|
self.advanced_wardrobe_repository = advanced_wardrobe_repository
|
||||||
|
self.material_catalog = material_catalog
|
||||||
self.composition_builder = composition_builder or CompositionBuilder()
|
self.composition_builder = composition_builder or CompositionBuilder()
|
||||||
self.normalization_service = normalization_service or MaterialNormalizationService()
|
self.normalization_service = normalization_service or MaterialNormalizationService()
|
||||||
|
|
||||||
|
|
@ -49,13 +64,14 @@ class WardrobeService:
|
||||||
"wardrobe_category is required",
|
"wardrobe_category is required",
|
||||||
{"field": "wardrobe_category"},
|
{"field": "wardrobe_category"},
|
||||||
)
|
)
|
||||||
material = self.material_repository.get_material(material_id)
|
material = self._get_catalog_material(material_id)
|
||||||
if material is None or material.recognition_status != "confirmed":
|
if material is None or material.recognition_status != "confirmed":
|
||||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "confirmed material not found", {"material_id": material_id})
|
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "confirmed material not found", {"material_id": material_id})
|
||||||
|
repository = self._repository_for_material_id(material_id)
|
||||||
duplicate = next(
|
duplicate = next(
|
||||||
(
|
(
|
||||||
existing
|
existing
|
||||||
for existing in self.wardrobe_repository.list_by_profile(profile_id, wardrobe_category)
|
for existing in repository.list_by_profile(profile_id, wardrobe_category)
|
||||||
if existing.material_id == material_id
|
if existing.material_id == material_id
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
|
|
@ -63,7 +79,7 @@ class WardrobeService:
|
||||||
if duplicate is not None:
|
if duplicate is not None:
|
||||||
raise _duplicate_wardrobe_item_error(profile_id, material_id, wardrobe_category, duplicate.wardrobe_item_id)
|
raise _duplicate_wardrobe_item_error(profile_id, material_id, wardrobe_category, duplicate.wardrobe_item_id)
|
||||||
try:
|
try:
|
||||||
item = self.wardrobe_repository.create(
|
item = repository.create(
|
||||||
{
|
{
|
||||||
"wardrobe_item_id": payload.get("wardrobe_item_id") or new_wardrobe_item_id(),
|
"wardrobe_item_id": payload.get("wardrobe_item_id") or new_wardrobe_item_id(),
|
||||||
"profile_id": profile_id,
|
"profile_id": profile_id,
|
||||||
|
|
@ -95,18 +111,21 @@ class WardrobeService:
|
||||||
ctx: RequestContext,
|
ctx: RequestContext,
|
||||||
) -> list[WardrobeItem]:
|
) -> list[WardrobeItem]:
|
||||||
self._ensure_profile(profile_id, ctx)
|
self._ensure_profile(profile_id, ctx)
|
||||||
return self.wardrobe_repository.list_by_profile(profile_id, wardrobe_category)
|
items = self.wardrobe_repository.list_by_profile(profile_id, wardrobe_category)
|
||||||
|
if self.advanced_wardrobe_repository is not None:
|
||||||
|
items.extend(self.advanced_wardrobe_repository.list_by_profile(profile_id, wardrobe_category))
|
||||||
|
return sorted(items, key=lambda item: (item.is_favorite, item.created_at), reverse=True)
|
||||||
|
|
||||||
def delete_item(self, profile_id: str, wardrobe_item_id: str, ctx: RequestContext) -> WardrobeItem:
|
def delete_item(self, profile_id: str, wardrobe_item_id: str, ctx: RequestContext) -> WardrobeItem:
|
||||||
self._ensure_profile(profile_id, ctx)
|
self._ensure_profile(profile_id, ctx)
|
||||||
before = self.wardrobe_repository.get(wardrobe_item_id)
|
repository, before = self._find_wardrobe_item(wardrobe_item_id)
|
||||||
if before is None or before.profile_id != profile_id:
|
if before is None or before.profile_id != profile_id:
|
||||||
raise ApiError(
|
raise ApiError(
|
||||||
ErrorCode.RESOURCE_NOT_FOUND,
|
ErrorCode.RESOURCE_NOT_FOUND,
|
||||||
"wardrobe item not found",
|
"wardrobe item not found",
|
||||||
{"wardrobe_item_id": wardrobe_item_id},
|
{"wardrobe_item_id": wardrobe_item_id},
|
||||||
)
|
)
|
||||||
deleted = self.wardrobe_repository.delete(wardrobe_item_id)
|
deleted = repository.delete(wardrobe_item_id)
|
||||||
assert deleted is not None
|
assert deleted is not None
|
||||||
self.audit_service.record(
|
self.audit_service.record(
|
||||||
ctx=ctx,
|
ctx=ctx,
|
||||||
|
|
@ -128,7 +147,7 @@ class WardrobeService:
|
||||||
material_ids = [str(item).strip() for item in payload.get("material_ids", []) if str(item).strip()] if isinstance(payload.get("material_ids"), list) else []
|
material_ids = [str(item).strip() for item in payload.get("material_ids", []) if str(item).strip()] if isinstance(payload.get("material_ids"), list) else []
|
||||||
if not name or not material_ids:
|
if not name or not material_ids:
|
||||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "template name and material_ids are required", {"fields": ["name", "material_ids"]})
|
raise ApiError(ErrorCode.VALIDATION_FAILED, "template name and material_ids are required", {"fields": ["name", "material_ids"]})
|
||||||
owned_material_ids = {item.material_id for item in self.wardrobe_repository.list_by_profile(profile_id)}
|
owned_material_ids = {item.material_id for item in self.list_items(profile_id, None, ctx)}
|
||||||
missing = [material_id for material_id in material_ids if material_id not in owned_material_ids]
|
missing = [material_id for material_id in material_ids if material_id not in owned_material_ids]
|
||||||
if missing:
|
if missing:
|
||||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "template contains materials outside this wardrobe", {"material_ids": missing})
|
raise ApiError(ErrorCode.VALIDATION_FAILED, "template contains materials outside this wardrobe", {"material_ids": missing})
|
||||||
|
|
@ -165,13 +184,13 @@ class WardrobeService:
|
||||||
template = next((item for item in self.list_templates(profile_id, ctx) if item.get("template_id") == template_id), None)
|
template = next((item for item in self.list_templates(profile_id, ctx) if item.get("template_id") == template_id), None)
|
||||||
if template is None:
|
if template is None:
|
||||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "wardrobe template not found", {"template_id": template_id})
|
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "wardrobe template not found", {"template_id": template_id})
|
||||||
wardrobe = self.wardrobe_repository.list_by_profile(profile_id)
|
wardrobe = self.list_items(profile_id, None, ctx)
|
||||||
item_by_material = {item.material_id: item for item in wardrobe}
|
item_by_material = {item.material_id: item for item in wardrobe}
|
||||||
selected: list[dict[str, Any]] = []
|
selected: list[dict[str, Any]] = []
|
||||||
options = template.get("material_options") if isinstance(template.get("material_options"), dict) else {}
|
options = template.get("material_options") if isinstance(template.get("material_options"), dict) else {}
|
||||||
for material_id in template.get("material_ids") or []:
|
for material_id in template.get("material_ids") or []:
|
||||||
item = item_by_material.get(str(material_id))
|
item = item_by_material.get(str(material_id))
|
||||||
material = self.material_repository.get_material(str(material_id))
|
material = self._get_catalog_material(str(material_id))
|
||||||
if item is None or material is None or material.recognition_status != "confirmed":
|
if item is None or material is None or material.recognition_status != "confirmed":
|
||||||
continue
|
continue
|
||||||
selected.append({
|
selected.append({
|
||||||
|
|
@ -204,13 +223,13 @@ class WardrobeService:
|
||||||
missing_categories: list[str] = []
|
missing_categories: list[str] = []
|
||||||
material_options = payload.get("material_options") if isinstance(payload.get("material_options"), dict) else {}
|
material_options = payload.get("material_options") if isinstance(payload.get("material_options"), dict) else {}
|
||||||
for category in categories:
|
for category in categories:
|
||||||
candidates = self.wardrobe_repository.list_by_profile(profile_id, str(category))
|
candidates = self._list_category_candidates(profile_id, str(category))
|
||||||
if not candidates:
|
if not candidates:
|
||||||
missing_categories.append(str(category))
|
missing_categories.append(str(category))
|
||||||
continue
|
continue
|
||||||
scored_candidates = []
|
scored_candidates = []
|
||||||
for index, item in enumerate(candidates):
|
for index, item in enumerate(candidates):
|
||||||
material = self.material_repository.get_material(item.material_id)
|
material = self._get_catalog_material(item.material_id)
|
||||||
if material is None or material.recognition_status != "confirmed":
|
if material is None or material.recognition_status != "confirmed":
|
||||||
continue
|
continue
|
||||||
score, breakdown = _score_candidate(item, material, context)
|
score, breakdown = _score_candidate(item, material, context)
|
||||||
|
|
@ -219,7 +238,7 @@ class WardrobeService:
|
||||||
missing_categories.append(str(category))
|
missing_categories.append(str(category))
|
||||||
continue
|
continue
|
||||||
score, _order, item, material, breakdown = max(scored_candidates, key=lambda candidate: (candidate[0], candidate[1]))
|
score, _order, item, material, breakdown = max(scored_candidates, key=lambda candidate: (candidate[0], candidate[1]))
|
||||||
self.wardrobe_repository.mark_used(item.wardrobe_item_id)
|
self._repository_for_item(item).mark_used(item.wardrobe_item_id)
|
||||||
selected.append(
|
selected.append(
|
||||||
{
|
{
|
||||||
"wardrobe_item_id": item.wardrobe_item_id,
|
"wardrobe_item_id": item.wardrobe_item_id,
|
||||||
|
|
@ -243,6 +262,7 @@ class WardrobeService:
|
||||||
"usage_count": item.usage_count,
|
"usage_count": item.usage_count,
|
||||||
"score": score,
|
"score": score,
|
||||||
"score_breakdown": breakdown,
|
"score_breakdown": breakdown,
|
||||||
|
"library_kind": item.library_kind,
|
||||||
**(
|
**(
|
||||||
material_options.get(material.material_id)
|
material_options.get(material.material_id)
|
||||||
if isinstance(material_options.get(material.material_id), dict)
|
if isinstance(material_options.get(material.material_id), dict)
|
||||||
|
|
@ -300,6 +320,41 @@ class WardrobeService:
|
||||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id})
|
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id})
|
||||||
return profile
|
return profile
|
||||||
|
|
||||||
|
def _get_catalog_material(self, material_id: str):
|
||||||
|
if self.material_catalog is not None:
|
||||||
|
return self.material_catalog.get_material(material_id)
|
||||||
|
return self.material_repository.get_material(material_id)
|
||||||
|
|
||||||
|
def _repository_for_material_id(self, material_id: str) -> WardrobeRepository:
|
||||||
|
if (
|
||||||
|
self.advanced_wardrobe_repository is not None
|
||||||
|
and self.material_catalog is not None
|
||||||
|
and str(material_id or "").startswith("advmat_")
|
||||||
|
):
|
||||||
|
return self.advanced_wardrobe_repository
|
||||||
|
return self.wardrobe_repository
|
||||||
|
|
||||||
|
def _repository_for_item(self, item: WardrobeItem) -> WardrobeRepository:
|
||||||
|
if item.library_kind == "advanced" and self.advanced_wardrobe_repository is not None:
|
||||||
|
return self.advanced_wardrobe_repository
|
||||||
|
return self.wardrobe_repository
|
||||||
|
|
||||||
|
def _find_wardrobe_item(self, wardrobe_item_id: str) -> tuple[WardrobeRepository, WardrobeItem | None]:
|
||||||
|
standard = self.wardrobe_repository.get(wardrobe_item_id)
|
||||||
|
if standard is not None:
|
||||||
|
return self.wardrobe_repository, standard
|
||||||
|
if self.advanced_wardrobe_repository is not None:
|
||||||
|
advanced = self.advanced_wardrobe_repository.get(wardrobe_item_id)
|
||||||
|
if advanced is not None:
|
||||||
|
return self.advanced_wardrobe_repository, advanced
|
||||||
|
return self.wardrobe_repository, None
|
||||||
|
|
||||||
|
def _list_category_candidates(self, profile_id: str, category: str) -> list[WardrobeItem]:
|
||||||
|
candidates = self.wardrobe_repository.list_by_profile(profile_id, category)
|
||||||
|
if self.advanced_wardrobe_repository is not None:
|
||||||
|
candidates.extend(self.advanced_wardrobe_repository.list_by_profile(profile_id, category))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
|
||||||
def new_wardrobe_item_id() -> str:
|
def new_wardrobe_item_id() -> str:
|
||||||
return f"wardrobe_{uuid4().hex}"
|
return f"wardrobe_{uuid4().hex}"
|
||||||
|
|
@ -358,7 +413,7 @@ def _match_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _score_candidate(item: WardrobeItem, material, context: dict[str, Any]) -> tuple[int, dict[str, int]]:
|
def _score_candidate(item: WardrobeItem, material, context: dict[str, Any]) -> tuple[float, dict[str, float]]:
|
||||||
item_terms = _text_set(item.tags) | _text_set(material.tags) | _words(material.display_name) | _words(material.prompt)
|
item_terms = _text_set(item.tags) | _text_set(material.tags) | _words(material.display_name) | _words(material.prompt)
|
||||||
requested_tags = context["requested_tags"]
|
requested_tags = context["requested_tags"]
|
||||||
tag_overlap = len(item_terms & requested_tags)
|
tag_overlap = len(item_terms & requested_tags)
|
||||||
|
|
@ -371,6 +426,9 @@ def _score_candidate(item: WardrobeItem, material, context: dict[str, Any]) -> t
|
||||||
"prompt_hits": prompt_hits * 3,
|
"prompt_hits": prompt_hits * 3,
|
||||||
"season": 12 if context["season"] and _optional_lower(item.season) == context["season"] else 0,
|
"season": 12 if context["season"] and _optional_lower(item.season) == context["season"] else 0,
|
||||||
"style": 12 if context["style"] and _optional_lower(item.style) == context["style"] else 0,
|
"style": 12 if context["style"] and _optional_lower(item.style) == context["style"] else 0,
|
||||||
|
"advanced_verified": ADVANCED_VERIFIED_PRIORITY_BONUS
|
||||||
|
if is_trusted_advanced_metadata(getattr(material, "metadata", None))
|
||||||
|
else 0,
|
||||||
}
|
}
|
||||||
return sum(breakdown.values()), breakdown
|
return sum(breakdown.values()), breakdown
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,16 +2,20 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
import threading
|
import threading
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from backend.dto.common import ApiError
|
||||||
from backend.dto.job_dto import GenerationTask
|
from backend.dto.job_dto import GenerationTask
|
||||||
from backend.services.queue_service import QueueService
|
from backend.services.queue_service import QueueService
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
WorkerHandler = Callable[[GenerationTask], "WorkerTaskUpdate | dict[str, Any] | None"]
|
WorkerHandler = Callable[[GenerationTask], "WorkerTaskUpdate | dict[str, Any] | None"]
|
||||||
WorkerTaskFilter = Callable[[GenerationTask], bool]
|
WorkerTaskFilter = Callable[[GenerationTask], bool]
|
||||||
|
|
@ -161,7 +165,9 @@ class QueueWorker:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self.is_running():
|
if self.is_running():
|
||||||
return {"worker_id": self.worker_id, "running": True, "already_running": True}
|
return {"worker_id": self.worker_id, "running": True, "already_running": True}
|
||||||
self._stop_event.clear()
|
# A previous thread may have died without clearing state. Always
|
||||||
|
# rebuild a fresh stop event + thread so callers can revive workers.
|
||||||
|
self._stop_event = threading.Event()
|
||||||
self._thread = threading.Thread(
|
self._thread = threading.Thread(
|
||||||
target=self._run_loop,
|
target=self._run_loop,
|
||||||
args=(ctx,),
|
args=(ctx,),
|
||||||
|
|
@ -184,7 +190,17 @@ class QueueWorker:
|
||||||
|
|
||||||
def _run_loop(self, ctx: RequestContext) -> None:
|
def _run_loop(self, ctx: RequestContext) -> None:
|
||||||
while not self._stop_event.is_set():
|
while not self._stop_event.is_set():
|
||||||
result = self.run_once(ctx)
|
try:
|
||||||
|
result = self.run_once(ctx)
|
||||||
|
except Exception:
|
||||||
|
# Provider/business failures must never kill the worker thread.
|
||||||
|
# A dead thread permanently stalls claim of later queued tasks.
|
||||||
|
logger.exception(
|
||||||
|
"ImageStudio queue worker %s crashed while processing; continuing",
|
||||||
|
self.worker_id,
|
||||||
|
)
|
||||||
|
self._stop_event.wait(self.interval_seconds)
|
||||||
|
continue
|
||||||
if result.status == "idle":
|
if result.status == "idle":
|
||||||
self._stop_event.wait(self.interval_seconds)
|
self._stop_event.wait(self.interval_seconds)
|
||||||
|
|
||||||
|
|
@ -205,73 +221,147 @@ class QueueWorker:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _handle_failure(self, task: GenerationTask, exc: Exception, ctx: RequestContext) -> WorkerRunResult:
|
def _handle_failure(self, task: GenerationTask, exc: Exception, ctx: RequestContext) -> WorkerRunResult:
|
||||||
latest = self.queue_service.get_job(task.task_id)
|
"""Mark the claimed task failed without ever re-raising.
|
||||||
if latest.status == "cancelled":
|
|
||||||
self._notify_terminal(task, latest, exc)
|
Queue progress is more important than perfect failure bookkeeping. Any
|
||||||
return WorkerRunResult(
|
secondary error while recording failure must leave the worker thread
|
||||||
worker_id=self.worker_id,
|
alive so later queued work can still be claimed.
|
||||||
status="cancelled",
|
"""
|
||||||
task_id=latest.task_id,
|
|
||||||
processed=1,
|
|
||||||
error_message=latest.error_message,
|
|
||||||
)
|
|
||||||
message = _safe_error_message(exc)
|
message = _safe_error_message(exc)
|
||||||
attempt = _int(latest.metadata.get("worker_attempt"), _int(task.metadata.get("worker_attempt"), 1))
|
latest = task
|
||||||
failed = self.queue_service.update_task(
|
try:
|
||||||
task.task_id,
|
latest = self.queue_service.get_job(task.task_id)
|
||||||
{
|
except Exception:
|
||||||
"status": "failed",
|
logger.exception(
|
||||||
"error_message": message,
|
"ImageStudio queue worker %s could not reload task %s during failure handling",
|
||||||
"metadata": {
|
self.worker_id,
|
||||||
**task.metadata,
|
task.task_id,
|
||||||
"worker": {
|
)
|
||||||
"worker_id": self.worker_id,
|
latest = task
|
||||||
"status": "failed",
|
|
||||||
"error_type": type(exc).__name__,
|
try:
|
||||||
"failed_at": _now(),
|
if latest.status == "cancelled":
|
||||||
},
|
self._notify_terminal(task, latest, exc)
|
||||||
},
|
return WorkerRunResult(
|
||||||
},
|
worker_id=self.worker_id,
|
||||||
ctx,
|
status="cancelled",
|
||||||
|
task_id=latest.task_id,
|
||||||
|
processed=1,
|
||||||
|
error_message=latest.error_message,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"ImageStudio queue worker %s failed while handling cancelled task %s",
|
||||||
|
self.worker_id,
|
||||||
|
task.task_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
attempt = _int(
|
||||||
|
(latest.metadata or {}).get("worker_attempt"),
|
||||||
|
_int((task.metadata or {}).get("worker_attempt"), 1),
|
||||||
)
|
)
|
||||||
if self.retry_policy.should_retry(attempt, exc):
|
base_metadata = dict(task.metadata or {})
|
||||||
queued = self.queue_service.update_task(
|
try:
|
||||||
failed.task_id,
|
if isinstance(latest.metadata, dict):
|
||||||
|
base_metadata = {**base_metadata, **latest.metadata}
|
||||||
|
except Exception:
|
||||||
|
base_metadata = dict(task.metadata or {})
|
||||||
|
|
||||||
|
failed = latest
|
||||||
|
try:
|
||||||
|
failed = self.queue_service.update_task(
|
||||||
|
task.task_id,
|
||||||
{
|
{
|
||||||
"status": "queued",
|
"status": "failed",
|
||||||
"progress": 0,
|
"error_message": message,
|
||||||
"error_message": None,
|
|
||||||
"metadata": {
|
"metadata": {
|
||||||
**failed.metadata,
|
**base_metadata,
|
||||||
"retry": {
|
"worker": {
|
||||||
"scheduled": True,
|
"worker_id": self.worker_id,
|
||||||
"attempt": attempt,
|
"status": "failed",
|
||||||
"max_attempts": max(int(self.retry_policy.max_attempts), 1),
|
|
||||||
"next_retry_at": self.retry_policy.next_retry_at(attempt),
|
|
||||||
"last_error": message,
|
|
||||||
"error_type": type(exc).__name__,
|
"error_type": type(exc).__name__,
|
||||||
|
"failed_at": _now(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
ctx,
|
ctx,
|
||||||
)
|
)
|
||||||
self._notify_terminal(task, queued, exc)
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"ImageStudio queue worker %s could not mark task %s as failed",
|
||||||
|
self.worker_id,
|
||||||
|
task.task_id,
|
||||||
|
)
|
||||||
|
self._notify_terminal(task, latest, exc)
|
||||||
return WorkerRunResult(
|
return WorkerRunResult(
|
||||||
worker_id=self.worker_id,
|
worker_id=self.worker_id,
|
||||||
status="retry_scheduled",
|
status="failed",
|
||||||
task_id=queued.task_id,
|
task_id=task.task_id,
|
||||||
processed=1,
|
processed=1,
|
||||||
|
failed=1,
|
||||||
|
error_message=message,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if self.retry_policy.should_retry(attempt, exc):
|
||||||
|
try:
|
||||||
|
queued = self.queue_service.update_task(
|
||||||
|
failed.task_id,
|
||||||
|
{
|
||||||
|
"status": "queued",
|
||||||
|
"progress": 0,
|
||||||
|
"error_message": None,
|
||||||
|
"metadata": {
|
||||||
|
**(failed.metadata or {}),
|
||||||
|
"retry": {
|
||||||
|
"scheduled": True,
|
||||||
|
"attempt": attempt,
|
||||||
|
"max_attempts": max(int(self.retry_policy.max_attempts), 1),
|
||||||
|
"next_retry_at": self.retry_policy.next_retry_at(attempt),
|
||||||
|
"last_error": message,
|
||||||
|
"error_type": type(exc).__name__,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
ctx,
|
||||||
|
)
|
||||||
|
self._notify_terminal(task, queued, exc)
|
||||||
|
return WorkerRunResult(
|
||||||
|
worker_id=self.worker_id,
|
||||||
|
status="retry_scheduled",
|
||||||
|
task_id=queued.task_id,
|
||||||
|
processed=1,
|
||||||
|
error_message=message,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"ImageStudio queue worker %s could not requeue task %s after failure",
|
||||||
|
self.worker_id,
|
||||||
|
task.task_id,
|
||||||
|
)
|
||||||
|
self._notify_terminal(task, failed, exc)
|
||||||
|
return WorkerRunResult(
|
||||||
|
worker_id=self.worker_id,
|
||||||
|
status="failed",
|
||||||
|
task_id=failed.task_id,
|
||||||
|
processed=1,
|
||||||
|
failed=1,
|
||||||
|
error_message=failed.error_message or message,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"ImageStudio queue worker %s hit a secondary error after failing task %s",
|
||||||
|
self.worker_id,
|
||||||
|
task.task_id,
|
||||||
|
)
|
||||||
|
return WorkerRunResult(
|
||||||
|
worker_id=self.worker_id,
|
||||||
|
status="failed",
|
||||||
|
task_id=task.task_id,
|
||||||
|
processed=1,
|
||||||
|
failed=1,
|
||||||
error_message=message,
|
error_message=message,
|
||||||
)
|
)
|
||||||
self._notify_terminal(task, failed, exc)
|
|
||||||
return WorkerRunResult(
|
|
||||||
worker_id=self.worker_id,
|
|
||||||
status="failed",
|
|
||||||
task_id=failed.task_id,
|
|
||||||
processed=1,
|
|
||||||
failed=1,
|
|
||||||
error_message=failed.error_message,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _notify_terminal(
|
def _notify_terminal(
|
||||||
self,
|
self,
|
||||||
|
|
@ -422,6 +512,24 @@ def _optional_text(value: Any) -> str | None:
|
||||||
|
|
||||||
|
|
||||||
def _safe_error_message(exc: Exception) -> str:
|
def _safe_error_message(exc: Exception) -> str:
|
||||||
|
if isinstance(exc, ApiError):
|
||||||
|
code = exc.error_code.value if hasattr(exc.error_code, "value") else str(exc.error_code)
|
||||||
|
parts = [str(exc.message or "").strip(), f"[{code}]"]
|
||||||
|
if isinstance(exc.details, dict) and exc.details:
|
||||||
|
# Keep a short, single-line hint without dumping full provider payloads.
|
||||||
|
hint_keys = ("reason", "finish_reason", "provider", "model")
|
||||||
|
hints = []
|
||||||
|
for key in hint_keys:
|
||||||
|
value = exc.details.get(key)
|
||||||
|
if value is None:
|
||||||
|
continue
|
||||||
|
text_value = " ".join(str(value).split())
|
||||||
|
if text_value:
|
||||||
|
hints.append(f"{key}={text_value[:80]}")
|
||||||
|
if hints:
|
||||||
|
parts.append("(" + ", ".join(hints) + ")")
|
||||||
|
text = " ".join(part for part in parts if part)
|
||||||
|
return text[:500] if text else f"ApiError [{code}]"
|
||||||
text = " ".join(str(exc or type(exc).__name__).split())
|
text = " ".join(str(exc or type(exc).__name__).split())
|
||||||
return text[:500] if text else type(exc).__name__
|
return text[:500] if text else type(exc).__name__
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ from typing import Any
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
from backend.dto.common import ApiError, ErrorCode
|
from backend.dto.common import ApiError, ErrorCode
|
||||||
|
from backend.services.material_catalog_resolver import MaterialCatalogResolver, is_trusted_advanced_metadata
|
||||||
from database.repositories.material_repository import MaterialRepository
|
from database.repositories.material_repository import MaterialRepository
|
||||||
from database.repositories.workflow_repository import WorkflowRepository
|
from database.repositories.workflow_repository import WorkflowRepository
|
||||||
|
|
||||||
|
|
@ -19,6 +20,7 @@ _SAFE_MATERIAL_METADATA_KEYS = frozenset(
|
||||||
{
|
{
|
||||||
"normalized_asset_profile",
|
"normalized_asset_profile",
|
||||||
"generation_capsule",
|
"generation_capsule",
|
||||||
|
"generation_capsules",
|
||||||
"body_slot",
|
"body_slot",
|
||||||
"wear_layer",
|
"wear_layer",
|
||||||
"material_type",
|
"material_type",
|
||||||
|
|
@ -27,6 +29,10 @@ _SAFE_MATERIAL_METADATA_KEYS = frozenset(
|
||||||
"user_locked",
|
"user_locked",
|
||||||
"stackable",
|
"stackable",
|
||||||
"note",
|
"note",
|
||||||
|
"library_kind",
|
||||||
|
"priority_class",
|
||||||
|
"material_priority",
|
||||||
|
"verification",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -35,7 +41,7 @@ class WorkflowMaterialSnapshotService:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
workflows: WorkflowRepository,
|
workflows: WorkflowRepository,
|
||||||
materials: MaterialRepository,
|
materials: MaterialRepository | MaterialCatalogResolver,
|
||||||
):
|
):
|
||||||
self.workflows = workflows
|
self.workflows = workflows
|
||||||
self.materials = materials
|
self.materials = materials
|
||||||
|
|
@ -94,6 +100,20 @@ class WorkflowMaterialSnapshotService:
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
image_uri = normalize_persistent_reference_uri(material.image_uri, field="material.image_uri")
|
image_uri = normalize_persistent_reference_uri(material.image_uri, field="material.image_uri")
|
||||||
|
raw_metadata = material.metadata if isinstance(material.metadata, dict) else {}
|
||||||
|
metadata = _safe_material_metadata(raw_metadata)
|
||||||
|
style_set = (
|
||||||
|
raw_metadata.get("style_set")
|
||||||
|
if is_trusted_advanced_metadata(raw_metadata) and isinstance(raw_metadata.get("style_set"), dict)
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
if style_set:
|
||||||
|
metadata["style_set"] = _plain_value(style_set)
|
||||||
|
reference_image_uris = [
|
||||||
|
normalize_persistent_reference_uri(uri, field="material.metadata.style_set.reference_source_uris")
|
||||||
|
for uri in _string_list(style_set.get("reference_source_uris"))[:3]
|
||||||
|
]
|
||||||
|
reference_image_uris = list(dict.fromkeys([image_uri, *reference_image_uris]))[:3]
|
||||||
category = self.materials.get_category(material.category_id) if material.category_id else None
|
category = self.materials.get_category(material.category_id) if material.category_id else None
|
||||||
binding = binding_by_material.get(material_id, {})
|
binding = binding_by_material.get(material_id, {})
|
||||||
frozen_materials.append(
|
frozen_materials.append(
|
||||||
|
|
@ -103,6 +123,7 @@ class WorkflowMaterialSnapshotService:
|
||||||
"category_id": material.category_id,
|
"category_id": material.category_id,
|
||||||
"category_name": category.name if category else None,
|
"category_name": category.name if category else None,
|
||||||
"image_uri": image_uri,
|
"image_uri": image_uri,
|
||||||
|
"reference_image_uris": reference_image_uris,
|
||||||
"thumbnail_uri": _optional_persistent_uri(material.thumbnail_uri),
|
"thumbnail_uri": _optional_persistent_uri(material.thumbnail_uri),
|
||||||
"prompt": material.prompt,
|
"prompt": material.prompt,
|
||||||
"negative_prompt": material.negative_prompt,
|
"negative_prompt": material.negative_prompt,
|
||||||
|
|
@ -110,7 +131,7 @@ class WorkflowMaterialSnapshotService:
|
||||||
"recognition_status": material.recognition_status,
|
"recognition_status": material.recognition_status,
|
||||||
"reference_strength": _plain_value(binding.get("reference_strength")),
|
"reference_strength": _plain_value(binding.get("reference_strength")),
|
||||||
"target_node_keys": _string_list(binding.get("target_node_keys")),
|
"target_node_keys": _string_list(binding.get("target_node_keys")),
|
||||||
"metadata": _safe_material_metadata(material.metadata),
|
"metadata": metadata,
|
||||||
"source_updated_at": material.updated_at,
|
"source_updated_at": material.updated_at,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
@ -140,7 +161,11 @@ class WorkflowMaterialSnapshotService:
|
||||||
"created_at": datetime.now(UTC).isoformat(),
|
"created_at": datetime.now(UTC).isoformat(),
|
||||||
"material_ids": [item["material_id"] for item in frozen_materials],
|
"material_ids": [item["material_id"] for item in frozen_materials],
|
||||||
"reference_uris": [
|
"reference_uris": [
|
||||||
*[item["image_uri"] for item in frozen_materials],
|
*[
|
||||||
|
uri
|
||||||
|
for item in frozen_materials
|
||||||
|
for uri in item.get("reference_image_uris", [item["image_uri"]])
|
||||||
|
],
|
||||||
*[item["image_uri"] for item in frozen_temporary],
|
*[item["image_uri"] for item in frozen_temporary],
|
||||||
],
|
],
|
||||||
"prompt_context": [
|
"prompt_context": [
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ from backend.services.material_binding_schema_service import (
|
||||||
NODE_MATERIAL_BINDING_SCHEMA_VERSION,
|
NODE_MATERIAL_BINDING_SCHEMA_VERSION,
|
||||||
material_bindings_for_node,
|
material_bindings_for_node,
|
||||||
)
|
)
|
||||||
|
from backend.services.material_catalog_resolver import MaterialCatalogResolver
|
||||||
from backend.services.resource_access_service import ResourceAccessService
|
from backend.services.resource_access_service import ResourceAccessService
|
||||||
from backend.services.workflow_material_snapshot_service import (
|
from backend.services.workflow_material_snapshot_service import (
|
||||||
normalize_persistent_reference_uri,
|
normalize_persistent_reference_uri,
|
||||||
|
|
@ -58,7 +59,7 @@ class WorkflowNodeMaterialService:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
workflow_service: WorkflowService,
|
workflow_service: WorkflowService,
|
||||||
material_repository: MaterialRepository,
|
material_repository: MaterialRepository | MaterialCatalogResolver,
|
||||||
*,
|
*,
|
||||||
round_repository: WorkflowRoundRepository | None = None,
|
round_repository: WorkflowRoundRepository | None = None,
|
||||||
access_service: ResourceAccessService | None = None,
|
access_service: ResourceAccessService | None = None,
|
||||||
|
|
@ -304,6 +305,7 @@ class WorkflowNodeMaterialService:
|
||||||
material_source = source.get("material") if isinstance(source.get("material"), dict) else {}
|
material_source = source.get("material") if isinstance(source.get("material"), dict) else {}
|
||||||
strength = _reference_strength(source.get("reference_strength"))
|
strength = _reference_strength(source.get("reference_strength"))
|
||||||
colors = _string_list(material.metadata.get("colors")) if isinstance(material.metadata, dict) else []
|
colors = _string_list(material.metadata.get("colors")) if isinstance(material.metadata, dict) else []
|
||||||
|
catalog_metadata = material.metadata if isinstance(material.metadata, dict) else {}
|
||||||
return {
|
return {
|
||||||
"id": str(source.get("id") or f"node_material_{material_id}"),
|
"id": str(source.get("id") or f"node_material_{material_id}"),
|
||||||
"category": str(
|
"category": str(
|
||||||
|
|
@ -319,6 +321,10 @@ class WorkflowNodeMaterialService:
|
||||||
"group": category.name if category is not None else None,
|
"group": category.name if category is not None else None,
|
||||||
"prompt": material.prompt or material_source.get("prompt"),
|
"prompt": material.prompt or material_source.get("prompt"),
|
||||||
"colors": colors,
|
"colors": colors,
|
||||||
|
"library_kind": catalog_metadata.get("library_kind", "standard"),
|
||||||
|
"priority_class": catalog_metadata.get("priority_class", "standard"),
|
||||||
|
"material_priority": catalog_metadata.get("material_priority", 0),
|
||||||
|
"verification": deepcopy(catalog_metadata.get("verification") or {}),
|
||||||
},
|
},
|
||||||
"target_stages": [],
|
"target_stages": [],
|
||||||
"target_node_keys": [canonical_gradual_node_key(node.node_key)],
|
"target_node_keys": [canonical_gradual_node_key(node.node_key)],
|
||||||
|
|
|
||||||
51
config.yaml
51
config.yaml
|
|
@ -1,7 +1,7 @@
|
||||||
plugin:
|
plugin:
|
||||||
name: astrbot_plugin_imagestudio
|
name: astrbot_plugin_imagestudio
|
||||||
display_name: ImageStudio
|
display_name: ImageStudio
|
||||||
version: 1.0.20
|
version: 1.0.66
|
||||||
|
|
||||||
features:
|
features:
|
||||||
quick_profile: true
|
quick_profile: true
|
||||||
|
|
@ -12,7 +12,7 @@ features:
|
||||||
private_companion_integration: false
|
private_companion_integration: false
|
||||||
|
|
||||||
generation:
|
generation:
|
||||||
# default_model 是 ImageStudio 路由名;route_name 留空时复用它。
|
# default_model 鏄?ImageStudio 璺敱鍚嶏紱route_name 鐣欑┖鏃跺鐢ㄥ畠銆?
|
||||||
default_model: ""
|
default_model: ""
|
||||||
provider:
|
provider:
|
||||||
provider_id: imagestudio_default
|
provider_id: imagestudio_default
|
||||||
|
|
@ -27,9 +27,9 @@ generation:
|
||||||
enabled: true
|
enabled: true
|
||||||
|
|
||||||
vision:
|
vision:
|
||||||
# 素材识别路由;provider 中留空的连接字段会复用 generation.provider。
|
# 绱犳潗璇嗗埆璺敱锛沺rovider 涓暀绌虹殑杩炴帴瀛楁浼氬鐢?generation.provider銆?
|
||||||
# 若地址、密钥或超时不同且 provider_id 留空,会自动派生独立 Vision provider ID,避免覆盖生图配置。
|
# 鑻ュ湴鍧€銆佸瘑閽ユ垨瓒呮椂涓嶅悓涓?provider_id 鐣欑┖锛屼細鑷姩娲剧敓鐙珛 Vision provider ID锛岄伩鍏嶈鐩栫敓鍥鹃厤缃€?
|
||||||
# Vision 模型必须单独填写,不能假定生图模型具备视觉理解能力。
|
# Vision 妯″瀷蹇呴』鍗曠嫭濉啓锛屼笉鑳藉亣瀹氱敓鍥炬ā鍨嬪叿澶囪瑙夌悊瑙h兘鍔涖€?
|
||||||
default_route: material_vlm
|
default_route: material_vlm
|
||||||
provider:
|
provider:
|
||||||
provider_id: ""
|
provider_id: ""
|
||||||
|
|
@ -43,9 +43,13 @@ vision:
|
||||||
priority: 10
|
priority: 10
|
||||||
enabled: true
|
enabled: true
|
||||||
|
|
||||||
# 按功能分配模型路由。留空时回退到 generation.default_model 或 vision.default_route。
|
# 鎸夊姛鑳藉垎閰嶆ā鍨嬭矾鐢便€傜暀绌烘椂鍥為€€鍒?generation.default_model 鎴?vision.default_route銆?
|
||||||
model_assignments:
|
model_assignments:
|
||||||
material_recognition: material_vlm
|
material_recognition: material_vlm
|
||||||
|
advanced_material_recognition: material_vlm
|
||||||
|
# 留空时沿用进阶素材识别路由;填写后仅多图画风交叉归纳使用该视觉路由。
|
||||||
|
advanced_style_consensus: ""
|
||||||
|
advanced_material_validation_generation: ""
|
||||||
profile_parse: ""
|
profile_parse: ""
|
||||||
persona_split: ""
|
persona_split: ""
|
||||||
prompt_planning: ""
|
prompt_planning: ""
|
||||||
|
|
@ -68,11 +72,26 @@ model_assignments:
|
||||||
|
|
||||||
recognition_prompts:
|
recognition_prompts:
|
||||||
default_instruction: >-
|
default_instruction: >-
|
||||||
请先判断图片中素材的准确分类,再尽可能完整地提取所有可见事实,包括物品类型、主色与辅色、材质、纹理、结构、轮廓、图案、裁剪、缝线、褶皱、装饰、配件、状态、视角、光照及可复用的设计特征。不要把无法确认的推测写成事实,并明确区分确定信息与低置信度判断。根据识别结果生成一段细节充分、可直接用于生图且能够保留原素材设计的正向提示词,同时生成用于排除错误类别、错误材质、结构畸变、文字、水印和无关背景的负向提示词。仅返回 JSON,字段必须包含 prompt、negative_prompt、tags、confidence、description;tags 应简短、可检索,并包含分类、颜色、材质和关键设计元素。
|
璇峰厛鍒ゆ柇鍥剧墖涓礌鏉愮殑鍑嗙‘鍒嗙被锛屽啀灏藉彲鑳藉畬鏁村湴鎻愬彇鎵€鏈夊彲瑙佷簨瀹烇紝鍖呮嫭鐗╁搧绫诲瀷銆佷富鑹蹭笌杈呰壊銆佹潗璐ㄣ€佺汗鐞嗐€佺粨鏋勩€佽疆寤撱€佸浘妗堛€佽鍓€佺紳绾裤€佽ざ鐨便€佽楗般€侀厤浠躲€佺姸鎬併€佽瑙掋€佸厜鐓у強鍙鐢ㄧ殑璁捐鐗瑰緛銆備笉瑕佹妸鏃犳硶纭鐨勬帹娴嬪啓鎴愪簨瀹烇紝骞舵槑纭尯鍒嗙‘瀹氫俊鎭笌浣庣疆淇″害鍒ゆ柇銆傛牴鎹瘑鍒粨鏋滅敓鎴愪竴娈电粏鑺傚厖鍒嗐€佸彲鐩存帴鐢ㄤ簬鐢熷浘涓旇兘澶熶繚鐣欏師绱犳潗璁捐鐨勬鍚戞彁绀鸿瘝锛屽悓鏃剁敓鎴愮敤浜庢帓闄ら敊璇被鍒€侀敊璇潗璐ㄣ€佺粨鏋勭暩鍙樸€佹枃瀛椼€佹按鍗板拰鏃犲叧鑳屾櫙鐨勮礋鍚戞彁绀鸿瘝銆備粎杩斿洖 JSON锛屽瓧娈靛繀椤诲寘鍚?prompt銆乶egative_prompt銆乼ags銆乧onfidence銆乨escription锛泃ags 搴旂畝鐭€佸彲妫€绱紝骞跺寘鍚垎绫汇€侀鑹层€佹潗璐ㄥ拰鍏抽敭璁捐鍏冪礌銆?
|
||||||
category_requirements: []
|
category_requirements: []
|
||||||
|
|
||||||
# 提示词转译、内容审核和普通/NSFW 模型动态分流。
|
# 杩涢樁绱犳潗楠岃瘉鍥剧殑鐙珛棰勭畻瀹堝崼銆傚紑鍚悗锛屾瘡娆¢獙璇侊紙鍚嚜鍔?NSFW
|
||||||
# 默认只启用本地规则审核;LLM 转译与成人自动分流必须由管理员明确开启。
|
# 鍥為€€锛夐兘浼氬湪璋冪敤鎻愪緵鏂瑰墠妫€鏌ユ椂闂寸獥鍙e唴鐨勪换鍔°€佸浘鐗囧拰浼扮畻璐圭敤銆?
|
||||||
|
advanced_materials:
|
||||||
|
recognition_concurrency: 2
|
||||||
|
cost_budget:
|
||||||
|
enabled: false
|
||||||
|
days: 30
|
||||||
|
max_task_count: null
|
||||||
|
max_image_count: null
|
||||||
|
max_estimated_cost: null
|
||||||
|
price_key: ""
|
||||||
|
per_request: 0
|
||||||
|
per_image: 0
|
||||||
|
per_1k_tokens: 0
|
||||||
|
|
||||||
|
# 鎻愮ず璇嶈浆璇戙€佸唴瀹瑰鏍稿拰鏅€?NSFW 妯″瀷鍔ㄦ€佸垎娴併€?
|
||||||
|
# 榛樿鍙惎鐢ㄦ湰鍦拌鍒欏鏍革紱LLM 杞瘧涓庢垚浜鸿嚜鍔ㄥ垎娴佸繀椤荤敱绠$悊鍛樻槑纭紑鍚€?
|
||||||
prompt_governance:
|
prompt_governance:
|
||||||
translation:
|
translation:
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|
@ -120,20 +139,21 @@ chat_access:
|
||||||
allow_4k: false
|
allow_4k: false
|
||||||
|
|
||||||
storage:
|
storage:
|
||||||
# 这里使用逻辑 data/... 路径;AstrBot 运行时映射到
|
# 杩欓噷浣跨敤閫昏緫 data/... 璺緞锛汚strBot 杩愯鏃舵槧灏勫埌
|
||||||
# data/plugin_data/astrbot_plugin_imagestudio/...,本地开发仍映射到仓库 data/。
|
# data/plugin_data/astrbot_plugin_imagestudio/...锛屾湰鍦板紑鍙戜粛鏄犲皠鍒颁粨搴?data/銆?
|
||||||
db_path: data/db/imagestudio.db
|
db_path: data/db/imagestudio.db
|
||||||
images_path: data/images
|
images_path: data/images
|
||||||
thumbnails_path: data/thumbnails
|
thumbnails_path: data/thumbnails
|
||||||
materials_path: data/materials
|
materials_path: data/materials
|
||||||
|
advanced_materials_path: data/advanced_materials
|
||||||
styles_path: data/styles
|
styles_path: data/styles
|
||||||
archives_path: data/archives
|
archives_path: data/archives
|
||||||
temp_path: data/temp
|
temp_path: data/temp
|
||||||
|
|
||||||
database:
|
database:
|
||||||
# auto: 默认使用 SQLite;配置并启用 PostgreSQL 后自动切换
|
# auto: 榛樿浣跨敤 SQLite锛涢厤缃苟鍚敤 PostgreSQL 鍚庤嚜鍔ㄥ垏鎹?
|
||||||
# sqlite: 强制使用本地 SQLite
|
# sqlite: 寮哄埗浣跨敤鏈湴 SQLite
|
||||||
# postgresql: 强制使用 PostgreSQL,驱动或连接配置缺失时会直接报错
|
# postgresql: 寮哄埗浣跨敤 PostgreSQL锛岄┍鍔ㄦ垨杩炴帴閰嶇疆缂哄け鏃朵細鐩存帴鎶ラ敊
|
||||||
backend: auto
|
backend: auto
|
||||||
sqlite:
|
sqlite:
|
||||||
path: data/db/imagestudio.db
|
path: data/db/imagestudio.db
|
||||||
|
|
@ -150,3 +170,6 @@ security:
|
||||||
integration_token_set: false
|
integration_token_set: false
|
||||||
allowed_integration_plugins:
|
allowed_integration_plugins:
|
||||||
- astrbot_plugin_private_companion
|
- astrbot_plugin_private_companion
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,19 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import base64
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
from typing import Any, Mapping
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
from core.image_formats import detect_image_format
|
||||||
|
from core.storage import VfsStorage
|
||||||
from engines.vision_provider import (
|
from engines.vision_provider import (
|
||||||
VisionProviderError,
|
VisionProviderError,
|
||||||
VisionRecognitionRequest,
|
VisionRecognitionRequest,
|
||||||
VisionRecognitionResult,
|
VisionRecognitionResult,
|
||||||
|
vision_image_urls,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -93,6 +97,75 @@ def astrbot_structured_text_callable(route_name: str):
|
||||||
return complete
|
return complete
|
||||||
|
|
||||||
|
|
||||||
|
def astrbot_structured_vision_callable(
|
||||||
|
route_name: str,
|
||||||
|
*,
|
||||||
|
storage: VfsStorage | None = None,
|
||||||
|
):
|
||||||
|
"""Return a generic structured-image reviewer backed by AstrBot.
|
||||||
|
|
||||||
|
Unlike :func:`astrbot_vision_provider`, this adapter does not require the
|
||||||
|
response to contain a material ``prompt`` field. It is used by generated
|
||||||
|
image moderation and other JSON-only vision checks.
|
||||||
|
"""
|
||||||
|
|
||||||
|
route = str(route_name or "").strip()
|
||||||
|
if not route.startswith("astrbot:"):
|
||||||
|
return None
|
||||||
|
provider_id = route.split(":", 1)[1].strip()
|
||||||
|
provider = _provider_by_id(provider_id)
|
||||||
|
loop = _runtime_loop
|
||||||
|
if provider is None or loop is None or loop.is_closed():
|
||||||
|
return None
|
||||||
|
vfs = storage or VfsStorage()
|
||||||
|
model = str(
|
||||||
|
_call_text(provider, "get_model")
|
||||||
|
or _provider_config(provider).get("model")
|
||||||
|
or _meta_value(provider, "model")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
def review(request_payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
image = request_payload.get("image") if isinstance(request_payload.get("image"), dict) else {}
|
||||||
|
uri = str(image.get("image_uri") or image.get("thumbnail_uri") or "").strip()
|
||||||
|
if uri.startswith("storage://"):
|
||||||
|
path = vfs.ensure_file(uri)
|
||||||
|
body = path.read_bytes()
|
||||||
|
if len(body) > 25 * 1024 * 1024:
|
||||||
|
raise ValueError("image moderation input exceeds size limit")
|
||||||
|
image_format = detect_image_format(body)
|
||||||
|
if image_format is None:
|
||||||
|
raise ValueError("image moderation input is not a supported image")
|
||||||
|
uri = f"data:{image_format.mime_type};base64,{base64.b64encode(body).decode('ascii')}"
|
||||||
|
if not uri.startswith(("data:image/", "http://", "https://")):
|
||||||
|
raise ValueError("image moderation requires a storage, data, or HTTP image URI")
|
||||||
|
|
||||||
|
async def invoke() -> str:
|
||||||
|
response = await provider.text_chat(
|
||||||
|
prompt=json.dumps(request_payload, ensure_ascii=False),
|
||||||
|
image_urls=[uri],
|
||||||
|
system_prompt=(
|
||||||
|
"Review the attached image and return one JSON object only. Follow the requested actions and "
|
||||||
|
"requirements exactly. Detect age ambiguity, unexpected nudity, terrorism, high-risk violence, "
|
||||||
|
"extreme gore, and content beyond the allowed request. Never weaken a safety classification."
|
||||||
|
),
|
||||||
|
model=model or None,
|
||||||
|
)
|
||||||
|
return str(getattr(response, "completion_text", "") or "").strip()
|
||||||
|
|
||||||
|
future = asyncio.run_coroutine_threadsafe(invoke(), loop)
|
||||||
|
try:
|
||||||
|
text = future.result(timeout=ASTRBOT_VISION_TIMEOUT_SECONDS)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise RuntimeError("AstrBot structured vision provider timed out") from exc
|
||||||
|
if not text:
|
||||||
|
raise ValueError("AstrBot structured vision provider returned an empty response")
|
||||||
|
return _json_object_from_text(text)
|
||||||
|
|
||||||
|
return review
|
||||||
|
|
||||||
|
|
||||||
def astrbot_vision_provider(route_name: str):
|
def astrbot_vision_provider(route_name: str):
|
||||||
"""Return a synchronous material-vision adapter backed by AstrBot.
|
"""Return a synchronous material-vision adapter backed by AstrBot.
|
||||||
|
|
||||||
|
|
@ -140,7 +213,8 @@ class _AstrBotVisionProvider:
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
|
|
||||||
def recognize_material(self, request: VisionRecognitionRequest) -> VisionRecognitionResult:
|
def recognize_material(self, request: VisionRecognitionRequest) -> VisionRecognitionResult:
|
||||||
if not str(request.image_uri or "").startswith(("data:image/", "http://", "https://")):
|
image_urls = list(vision_image_urls(request))
|
||||||
|
if not image_urls:
|
||||||
raise VisionProviderError(
|
raise VisionProviderError(
|
||||||
"AstrBot vision input must be a data or HTTP image URL",
|
"AstrBot vision input must be a data or HTTP image URL",
|
||||||
provider_id=self.provider_id,
|
provider_id=self.provider_id,
|
||||||
|
|
@ -150,7 +224,7 @@ class _AstrBotVisionProvider:
|
||||||
async def invoke() -> str:
|
async def invoke() -> str:
|
||||||
response = await self.provider.text_chat(
|
response = await self.provider.text_chat(
|
||||||
prompt=_material_user_prompt(request),
|
prompt=_material_user_prompt(request),
|
||||||
image_urls=[request.image_uri],
|
image_urls=image_urls,
|
||||||
system_prompt=_material_system_prompt(request),
|
system_prompt=_material_system_prompt(request),
|
||||||
model=request.model or self.model or None,
|
model=request.model or self.model or None,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ from core.runtime_paths import resolve_config_path
|
||||||
from database.db_helper import load_config_payload
|
from database.db_helper import load_config_payload
|
||||||
|
|
||||||
|
|
||||||
PLUGIN_VERSION = "1.0.20"
|
PLUGIN_VERSION = "1.0.66"
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|
@ -25,6 +25,7 @@ class StorageConfig:
|
||||||
images_path: str = "data/images"
|
images_path: str = "data/images"
|
||||||
thumbnails_path: str = "data/thumbnails"
|
thumbnails_path: str = "data/thumbnails"
|
||||||
materials_path: str = "data/materials"
|
materials_path: str = "data/materials"
|
||||||
|
advanced_materials_path: str = "data/advanced_materials"
|
||||||
styles_path: str = "data/styles"
|
styles_path: str = "data/styles"
|
||||||
archives_path: str = "data/archives"
|
archives_path: str = "data/archives"
|
||||||
temp_path: str = "data/temp"
|
temp_path: str = "data/temp"
|
||||||
|
|
@ -74,6 +75,9 @@ class ConfigService:
|
||||||
images_path=str(storage.get("images_path", "data/images")),
|
images_path=str(storage.get("images_path", "data/images")),
|
||||||
thumbnails_path=str(storage.get("thumbnails_path", "data/thumbnails")),
|
thumbnails_path=str(storage.get("thumbnails_path", "data/thumbnails")),
|
||||||
materials_path=str(storage.get("materials_path", "data/materials")),
|
materials_path=str(storage.get("materials_path", "data/materials")),
|
||||||
|
advanced_materials_path=str(
|
||||||
|
storage.get("advanced_materials_path", "data/advanced_materials")
|
||||||
|
),
|
||||||
styles_path=str(storage.get("styles_path", "data/styles")),
|
styles_path=str(storage.get("styles_path", "data/styles")),
|
||||||
archives_path=str(storage.get("archives_path", "data/archives")),
|
archives_path=str(storage.get("archives_path", "data/archives")),
|
||||||
temp_path=str(storage.get("temp_path", "data/temp")),
|
temp_path=str(storage.get("temp_path", "data/temp")),
|
||||||
|
|
@ -83,3 +87,6 @@ class ConfigService:
|
||||||
|
|
||||||
def _resolve_path(path: str | Path) -> Path:
|
def _resolve_path(path: str | Path) -> Path:
|
||||||
return resolve_config_path(path)
|
return resolve_config_path(path)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
79
core/model_route_chain.py
普通文件
79
core/model_route_chain.py
普通文件
|
|
@ -0,0 +1,79 @@
|
||||||
|
"""Backward-compatible two-source model route chains.
|
||||||
|
|
||||||
|
The AstrBot configuration schema exposes model assignments as strings. Keep
|
||||||
|
that stable while allowing each assignment to carry one ImageStudio route and
|
||||||
|
one AstrBot-hosted fallback route.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
ROUTE_CHAIN_PREFIX = "route-chain:"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ModelRouteChain:
|
||||||
|
plugin: str = ""
|
||||||
|
astrbot: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def candidates(self) -> tuple[str, ...]:
|
||||||
|
values: list[str] = []
|
||||||
|
for value in (self.plugin, self.astrbot):
|
||||||
|
route = str(value or "").strip()
|
||||||
|
if route and route not in values:
|
||||||
|
values.append(route)
|
||||||
|
return tuple(values)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_model_route_chain(value: Any) -> ModelRouteChain:
|
||||||
|
route = str(value or "").strip()
|
||||||
|
if not route:
|
||||||
|
return ModelRouteChain()
|
||||||
|
if route.startswith(ROUTE_CHAIN_PREFIX):
|
||||||
|
try:
|
||||||
|
payload = json.loads(route[len(ROUTE_CHAIN_PREFIX) :])
|
||||||
|
except (TypeError, ValueError, json.JSONDecodeError):
|
||||||
|
payload = None
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
return ModelRouteChain(
|
||||||
|
plugin=_text(payload.get("plugin")),
|
||||||
|
astrbot=_astrbot_text(payload.get("astrbot")),
|
||||||
|
)
|
||||||
|
if route.startswith("astrbot:"):
|
||||||
|
return ModelRouteChain(astrbot=route)
|
||||||
|
return ModelRouteChain(plugin=route)
|
||||||
|
|
||||||
|
|
||||||
|
def encode_model_route_chain(plugin: Any = "", astrbot: Any = "") -> str:
|
||||||
|
plugin_route = _text(plugin)
|
||||||
|
astrbot_route = _astrbot_text(astrbot)
|
||||||
|
if plugin_route and not astrbot_route:
|
||||||
|
return plugin_route
|
||||||
|
if astrbot_route and not plugin_route:
|
||||||
|
return astrbot_route
|
||||||
|
if not plugin_route and not astrbot_route:
|
||||||
|
return ""
|
||||||
|
return ROUTE_CHAIN_PREFIX + json.dumps(
|
||||||
|
{"plugin": plugin_route, "astrbot": astrbot_route},
|
||||||
|
ensure_ascii=False,
|
||||||
|
separators=(",", ":"),
|
||||||
|
sort_keys=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def model_route_candidates(value: Any) -> tuple[str, ...]:
|
||||||
|
return parse_model_route_chain(value).candidates
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any) -> str:
|
||||||
|
return str(value or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _astrbot_text(value: Any) -> str:
|
||||||
|
route = _text(value)
|
||||||
|
return route if not route or route.startswith("astrbot:") else ""
|
||||||
|
|
@ -148,6 +148,7 @@ def _storage_roots(config: ImageStudioConfig) -> dict[str, str]:
|
||||||
"images": config.storage.images_path,
|
"images": config.storage.images_path,
|
||||||
"thumbnails": config.storage.thumbnails_path,
|
"thumbnails": config.storage.thumbnails_path,
|
||||||
"materials": config.storage.materials_path,
|
"materials": config.storage.materials_path,
|
||||||
|
"advanced_materials": config.storage.advanced_materials_path,
|
||||||
"styles": config.storage.styles_path,
|
"styles": config.storage.styles_path,
|
||||||
"archives": config.storage.archives_path,
|
"archives": config.storage.archives_path,
|
||||||
"temp": config.storage.temp_path,
|
"temp": config.storage.temp_path,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,109 @@
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_material_imports (
|
||||||
|
import_id TEXT PRIMARY KEY,
|
||||||
|
category_id TEXT,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
source_image_uri TEXT NOT NULL,
|
||||||
|
source_thumbnail_uri TEXT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending_recognition',
|
||||||
|
recognition_prompt TEXT,
|
||||||
|
recognition_negative_prompt TEXT,
|
||||||
|
recognition_tags_json TEXT,
|
||||||
|
recognition_result_json TEXT,
|
||||||
|
recognition_model_route TEXT,
|
||||||
|
prompt_revision INTEGER NOT NULL DEFAULT 0,
|
||||||
|
current_attempt_id TEXT,
|
||||||
|
accepted_material_id TEXT,
|
||||||
|
idempotency_key TEXT,
|
||||||
|
created_by TEXT,
|
||||||
|
error_json TEXT,
|
||||||
|
metadata_json TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY(category_id) REFERENCES material_categories(category_id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_material_imports_idempotency
|
||||||
|
ON advanced_material_imports(idempotency_key)
|
||||||
|
WHERE idempotency_key IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_material_imports_status
|
||||||
|
ON advanced_material_imports(status, updated_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_material_imports_category
|
||||||
|
ON advanced_material_imports(category_id, created_at);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_material_validation_attempts (
|
||||||
|
attempt_id TEXT PRIMARY KEY,
|
||||||
|
import_id TEXT NOT NULL,
|
||||||
|
attempt_number INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
adjustment_text TEXT,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
negative_prompt TEXT,
|
||||||
|
model_route TEXT,
|
||||||
|
provider_id TEXT,
|
||||||
|
provider_model TEXT,
|
||||||
|
task_id TEXT,
|
||||||
|
validation_image_uri TEXT,
|
||||||
|
validation_thumbnail_uri TEXT,
|
||||||
|
seed INTEGER,
|
||||||
|
width INTEGER,
|
||||||
|
height INTEGER,
|
||||||
|
usage_json TEXT,
|
||||||
|
fidelity_score REAL,
|
||||||
|
decision TEXT,
|
||||||
|
decision_notes TEXT,
|
||||||
|
error_json TEXT,
|
||||||
|
metadata_json TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
completed_at TIMESTAMP,
|
||||||
|
decided_at TIMESTAMP,
|
||||||
|
FOREIGN KEY(import_id) REFERENCES advanced_material_imports(import_id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(task_id) REFERENCES generation_tasks(task_id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_material_attempts_sequence
|
||||||
|
ON advanced_material_validation_attempts(import_id, attempt_number);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_material_attempts_status
|
||||||
|
ON advanced_material_validation_attempts(status, updated_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_material_attempts_task
|
||||||
|
ON advanced_material_validation_attempts(task_id);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_material_attempts_one_active
|
||||||
|
ON advanced_material_validation_attempts(import_id)
|
||||||
|
WHERE status IN ('queued', 'running');
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_materials (
|
||||||
|
material_id TEXT PRIMARY KEY,
|
||||||
|
import_id TEXT NOT NULL UNIQUE,
|
||||||
|
accepted_attempt_id TEXT NOT NULL UNIQUE,
|
||||||
|
category_id TEXT,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
source_image_uri TEXT NOT NULL,
|
||||||
|
source_thumbnail_uri TEXT,
|
||||||
|
validation_image_uri TEXT NOT NULL,
|
||||||
|
validation_thumbnail_uri TEXT,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
negative_prompt TEXT,
|
||||||
|
tags_json TEXT,
|
||||||
|
priority INTEGER NOT NULL DEFAULT 100,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
capsule_json TEXT,
|
||||||
|
metadata_json TEXT,
|
||||||
|
accepted_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
archived_at TIMESTAMP,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY(import_id) REFERENCES advanced_material_imports(import_id) ON DELETE RESTRICT,
|
||||||
|
FOREIGN KEY(accepted_attempt_id) REFERENCES advanced_material_validation_attempts(attempt_id) ON DELETE RESTRICT,
|
||||||
|
FOREIGN KEY(category_id) REFERENCES material_categories(category_id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_materials_catalog
|
||||||
|
ON advanced_materials(status, priority, accepted_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_materials_category
|
||||||
|
ON advanced_materials(category_id, status, priority, accepted_at);
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_wardrobe_items (
|
||||||
|
wardrobe_item_id TEXT PRIMARY KEY,
|
||||||
|
profile_id TEXT NOT NULL,
|
||||||
|
material_id TEXT NOT NULL,
|
||||||
|
wardrobe_category TEXT NOT NULL,
|
||||||
|
tags_json TEXT,
|
||||||
|
season TEXT,
|
||||||
|
style TEXT,
|
||||||
|
is_favorite INTEGER NOT NULL DEFAULT 0,
|
||||||
|
usage_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
last_used_at TIMESTAMP,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY(profile_id) REFERENCES character_profiles(profile_id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(material_id) REFERENCES advanced_materials(material_id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_wardrobe_profile
|
||||||
|
ON advanced_wardrobe_items(profile_id, wardrobe_category);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_wardrobe_profile_material
|
||||||
|
ON advanced_wardrobe_items(profile_id, material_id, wardrobe_category);
|
||||||
|
|
@ -0,0 +1,115 @@
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_style_sources (
|
||||||
|
source_id TEXT PRIMARY KEY,
|
||||||
|
import_id TEXT NOT NULL,
|
||||||
|
sort_order INTEGER NOT NULL,
|
||||||
|
is_primary INTEGER NOT NULL DEFAULT 0,
|
||||||
|
source_image_uri TEXT NOT NULL,
|
||||||
|
source_thumbnail_uri TEXT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
recognition_model_route TEXT,
|
||||||
|
provider_id TEXT,
|
||||||
|
provider_model TEXT,
|
||||||
|
task_id TEXT,
|
||||||
|
recognition_prompt TEXT,
|
||||||
|
recognition_negative_prompt TEXT,
|
||||||
|
recognition_tags_json TEXT,
|
||||||
|
recognition_result_json TEXT,
|
||||||
|
error_json TEXT,
|
||||||
|
metadata_json TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
completed_at TIMESTAMP,
|
||||||
|
excluded_at TIMESTAMP,
|
||||||
|
FOREIGN KEY(import_id) REFERENCES advanced_material_imports(import_id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(task_id) REFERENCES generation_tasks(task_id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_style_sources_order
|
||||||
|
ON advanced_style_sources(import_id, sort_order);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_style_sources_one_primary
|
||||||
|
ON advanced_style_sources(import_id)
|
||||||
|
WHERE is_primary = 1;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_style_sources_status
|
||||||
|
ON advanced_style_sources(import_id, status, updated_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_style_sources_task
|
||||||
|
ON advanced_style_sources(task_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_style_consensus_runs (
|
||||||
|
consensus_id TEXT PRIMARY KEY,
|
||||||
|
import_id TEXT NOT NULL,
|
||||||
|
revision INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
task_id TEXT,
|
||||||
|
model_route TEXT,
|
||||||
|
provider_id TEXT,
|
||||||
|
provider_model TEXT,
|
||||||
|
source_ids_json TEXT,
|
||||||
|
prompt TEXT,
|
||||||
|
negative_prompt TEXT,
|
||||||
|
tags_json TEXT,
|
||||||
|
result_json TEXT,
|
||||||
|
error_json TEXT,
|
||||||
|
metadata_json TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
completed_at TIMESTAMP,
|
||||||
|
FOREIGN KEY(import_id) REFERENCES advanced_material_imports(import_id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(task_id) REFERENCES generation_tasks(task_id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_style_consensus_revision
|
||||||
|
ON advanced_style_consensus_runs(import_id, revision);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_style_consensus_one_active
|
||||||
|
ON advanced_style_consensus_runs(import_id)
|
||||||
|
WHERE status IN ('queued', 'running');
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_style_consensus_task
|
||||||
|
ON advanced_style_consensus_runs(task_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS advanced_style_validation_cases (
|
||||||
|
case_id TEXT PRIMARY KEY,
|
||||||
|
attempt_id TEXT NOT NULL,
|
||||||
|
import_id TEXT NOT NULL,
|
||||||
|
case_key TEXT NOT NULL,
|
||||||
|
sort_order INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
task_id TEXT,
|
||||||
|
content_prompt TEXT NOT NULL,
|
||||||
|
final_prompt TEXT NOT NULL,
|
||||||
|
negative_prompt TEXT,
|
||||||
|
model_route TEXT,
|
||||||
|
provider_id TEXT,
|
||||||
|
provider_model TEXT,
|
||||||
|
seed INTEGER,
|
||||||
|
width INTEGER,
|
||||||
|
height INTEGER,
|
||||||
|
validation_image_uri TEXT,
|
||||||
|
validation_thumbnail_uri TEXT,
|
||||||
|
usage_json TEXT,
|
||||||
|
style_review_json TEXT,
|
||||||
|
fidelity_score REAL,
|
||||||
|
error_json TEXT,
|
||||||
|
metadata_json TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
completed_at TIMESTAMP,
|
||||||
|
FOREIGN KEY(attempt_id) REFERENCES advanced_material_validation_attempts(attempt_id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(import_id) REFERENCES advanced_material_imports(import_id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(task_id) REFERENCES generation_tasks(task_id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_style_validation_case_key
|
||||||
|
ON advanced_style_validation_cases(attempt_id, case_key);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_advanced_style_validation_case_order
|
||||||
|
ON advanced_style_validation_cases(attempt_id, sort_order);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_style_validation_case_status
|
||||||
|
ON advanced_style_validation_cases(import_id, attempt_id, status, updated_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_advanced_style_validation_case_task
|
||||||
|
ON advanced_style_validation_cases(task_id);
|
||||||
|
|
@ -232,6 +232,161 @@ TABLES: tuple[TableSpec, ...] = (
|
||||||
ColumnSpec("recognition_status", nullable=False),
|
ColumnSpec("recognition_status", nullable=False),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_material_imports",
|
||||||
|
"import_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("import_id", nullable=False),
|
||||||
|
ColumnSpec("category_id"),
|
||||||
|
ColumnSpec("display_name", nullable=False),
|
||||||
|
ColumnSpec("source_image_uri", nullable=False),
|
||||||
|
ColumnSpec("source_thumbnail_uri"),
|
||||||
|
ColumnSpec("status", nullable=False),
|
||||||
|
ColumnSpec("recognition_prompt"),
|
||||||
|
ColumnSpec("recognition_negative_prompt"),
|
||||||
|
ColumnSpec("recognition_tags_json"),
|
||||||
|
ColumnSpec("recognition_result_json"),
|
||||||
|
ColumnSpec("recognition_model_route"),
|
||||||
|
ColumnSpec("prompt_revision", nullable=False),
|
||||||
|
ColumnSpec("current_attempt_id"),
|
||||||
|
ColumnSpec("accepted_material_id"),
|
||||||
|
ColumnSpec("idempotency_key"),
|
||||||
|
ColumnSpec("created_by"),
|
||||||
|
ColumnSpec("error_json"),
|
||||||
|
ColumnSpec("metadata_json"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_material_validation_attempts",
|
||||||
|
"attempt_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("attempt_id", nullable=False),
|
||||||
|
ColumnSpec("import_id", nullable=False),
|
||||||
|
ColumnSpec("attempt_number", nullable=False),
|
||||||
|
ColumnSpec("status", nullable=False),
|
||||||
|
ColumnSpec("adjustment_text"),
|
||||||
|
ColumnSpec("prompt", nullable=False),
|
||||||
|
ColumnSpec("negative_prompt"),
|
||||||
|
ColumnSpec("model_route"),
|
||||||
|
ColumnSpec("provider_id"),
|
||||||
|
ColumnSpec("provider_model"),
|
||||||
|
ColumnSpec("task_id"),
|
||||||
|
ColumnSpec("validation_image_uri"),
|
||||||
|
ColumnSpec("validation_thumbnail_uri"),
|
||||||
|
ColumnSpec("seed"),
|
||||||
|
ColumnSpec("width"),
|
||||||
|
ColumnSpec("height"),
|
||||||
|
ColumnSpec("usage_json"),
|
||||||
|
ColumnSpec("fidelity_score"),
|
||||||
|
ColumnSpec("decision"),
|
||||||
|
ColumnSpec("decision_notes"),
|
||||||
|
ColumnSpec("error_json"),
|
||||||
|
ColumnSpec("metadata_json"),
|
||||||
|
ColumnSpec("completed_at"),
|
||||||
|
ColumnSpec("decided_at"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_materials",
|
||||||
|
"material_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("material_id", nullable=False),
|
||||||
|
ColumnSpec("import_id", nullable=False),
|
||||||
|
ColumnSpec("accepted_attempt_id", nullable=False),
|
||||||
|
ColumnSpec("category_id"),
|
||||||
|
ColumnSpec("display_name", nullable=False),
|
||||||
|
ColumnSpec("source_image_uri", nullable=False),
|
||||||
|
ColumnSpec("source_thumbnail_uri"),
|
||||||
|
ColumnSpec("validation_image_uri", nullable=False),
|
||||||
|
ColumnSpec("validation_thumbnail_uri"),
|
||||||
|
ColumnSpec("prompt", nullable=False),
|
||||||
|
ColumnSpec("negative_prompt"),
|
||||||
|
ColumnSpec("tags_json"),
|
||||||
|
ColumnSpec("priority", nullable=False),
|
||||||
|
ColumnSpec("status", nullable=False),
|
||||||
|
ColumnSpec("capsule_json"),
|
||||||
|
ColumnSpec("metadata_json"),
|
||||||
|
ColumnSpec("accepted_at", nullable=False),
|
||||||
|
ColumnSpec("archived_at"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_style_sources",
|
||||||
|
"source_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("source_id", nullable=False),
|
||||||
|
ColumnSpec("import_id", nullable=False),
|
||||||
|
ColumnSpec("sort_order", nullable=False),
|
||||||
|
ColumnSpec("is_primary", nullable=False),
|
||||||
|
ColumnSpec("source_image_uri", nullable=False),
|
||||||
|
ColumnSpec("source_thumbnail_uri"),
|
||||||
|
ColumnSpec("status", nullable=False),
|
||||||
|
ColumnSpec("recognition_model_route"),
|
||||||
|
ColumnSpec("provider_id"),
|
||||||
|
ColumnSpec("provider_model"),
|
||||||
|
ColumnSpec("task_id"),
|
||||||
|
ColumnSpec("recognition_prompt"),
|
||||||
|
ColumnSpec("recognition_negative_prompt"),
|
||||||
|
ColumnSpec("recognition_tags_json"),
|
||||||
|
ColumnSpec("recognition_result_json"),
|
||||||
|
ColumnSpec("error_json"),
|
||||||
|
ColumnSpec("metadata_json"),
|
||||||
|
ColumnSpec("completed_at"),
|
||||||
|
ColumnSpec("excluded_at"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_style_consensus_runs",
|
||||||
|
"consensus_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("consensus_id", nullable=False),
|
||||||
|
ColumnSpec("import_id", nullable=False),
|
||||||
|
ColumnSpec("revision", nullable=False),
|
||||||
|
ColumnSpec("status", nullable=False),
|
||||||
|
ColumnSpec("task_id"),
|
||||||
|
ColumnSpec("model_route"),
|
||||||
|
ColumnSpec("provider_id"),
|
||||||
|
ColumnSpec("provider_model"),
|
||||||
|
ColumnSpec("source_ids_json"),
|
||||||
|
ColumnSpec("prompt"),
|
||||||
|
ColumnSpec("negative_prompt"),
|
||||||
|
ColumnSpec("tags_json"),
|
||||||
|
ColumnSpec("result_json"),
|
||||||
|
ColumnSpec("error_json"),
|
||||||
|
ColumnSpec("metadata_json"),
|
||||||
|
ColumnSpec("completed_at"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_style_validation_cases",
|
||||||
|
"case_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("case_id", nullable=False),
|
||||||
|
ColumnSpec("attempt_id", nullable=False),
|
||||||
|
ColumnSpec("import_id", nullable=False),
|
||||||
|
ColumnSpec("case_key", nullable=False),
|
||||||
|
ColumnSpec("sort_order", nullable=False),
|
||||||
|
ColumnSpec("status", nullable=False),
|
||||||
|
ColumnSpec("task_id"),
|
||||||
|
ColumnSpec("content_prompt", nullable=False),
|
||||||
|
ColumnSpec("final_prompt", nullable=False),
|
||||||
|
ColumnSpec("negative_prompt"),
|
||||||
|
ColumnSpec("model_route"),
|
||||||
|
ColumnSpec("provider_id"),
|
||||||
|
ColumnSpec("provider_model"),
|
||||||
|
ColumnSpec("seed"),
|
||||||
|
ColumnSpec("width"),
|
||||||
|
ColumnSpec("height"),
|
||||||
|
ColumnSpec("validation_image_uri"),
|
||||||
|
ColumnSpec("validation_thumbnail_uri"),
|
||||||
|
ColumnSpec("usage_json"),
|
||||||
|
ColumnSpec("style_review_json"),
|
||||||
|
ColumnSpec("fidelity_score"),
|
||||||
|
ColumnSpec("error_json"),
|
||||||
|
ColumnSpec("metadata_json"),
|
||||||
|
ColumnSpec("completed_at"),
|
||||||
|
),
|
||||||
|
),
|
||||||
TableSpec(
|
TableSpec(
|
||||||
"audit_logs",
|
"audit_logs",
|
||||||
"audit_id",
|
"audit_id",
|
||||||
|
|
@ -269,6 +424,22 @@ TABLES: tuple[TableSpec, ...] = (
|
||||||
ColumnSpec("last_used_at"),
|
ColumnSpec("last_used_at"),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
TableSpec(
|
||||||
|
"advanced_wardrobe_items",
|
||||||
|
"wardrobe_item_id",
|
||||||
|
(
|
||||||
|
ColumnSpec("wardrobe_item_id", nullable=False),
|
||||||
|
ColumnSpec("profile_id", nullable=False),
|
||||||
|
ColumnSpec("material_id", nullable=False),
|
||||||
|
ColumnSpec("wardrobe_category", nullable=False),
|
||||||
|
ColumnSpec("tags_json"),
|
||||||
|
ColumnSpec("season"),
|
||||||
|
ColumnSpec("style"),
|
||||||
|
ColumnSpec("is_favorite", nullable=False),
|
||||||
|
ColumnSpec("usage_count", nullable=False),
|
||||||
|
ColumnSpec("last_used_at"),
|
||||||
|
),
|
||||||
|
),
|
||||||
TableSpec(
|
TableSpec(
|
||||||
"integration_logs",
|
"integration_logs",
|
||||||
"integration_log_id",
|
"integration_log_id",
|
||||||
|
|
|
||||||
文件差异内容过多而无法显示
加载差异
|
|
@ -160,14 +160,16 @@ class JobRepository:
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
statuses: set[str] | tuple[str, ...] | list[str],
|
statuses: set[str] | tuple[str, ...] | list[str],
|
||||||
updated_before: str,
|
updated_before: str | None,
|
||||||
limit: int = 100,
|
limit: int | None = 100,
|
||||||
) -> list[GenerationTask]:
|
) -> list[GenerationTask]:
|
||||||
"""Return oldest tasks that were left in an executable state.
|
"""Return oldest tasks that were left in an executable state.
|
||||||
|
|
||||||
Recovery decides which task sources are safe to requeue. Keeping the
|
Recovery decides which task sources are safe to requeue. Keeping the
|
||||||
JSON-source filter in the service makes this query portable across the
|
JSON-source filter in the service makes this query portable across the
|
||||||
SQLite and PostgreSQL backends.
|
SQLite and PostgreSQL backends. Startup recovery may omit both the
|
||||||
|
age boundary and limit because it runs before the new worker pool is
|
||||||
|
started and must inspect every task owned by the previous process.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
normalized_statuses = tuple(
|
normalized_statuses = tuple(
|
||||||
|
|
@ -177,6 +179,13 @@ class JobRepository:
|
||||||
return []
|
return []
|
||||||
placeholder = self.placeholder
|
placeholder = self.placeholder
|
||||||
status_placeholders = ", ".join(placeholder for _ in normalized_statuses)
|
status_placeholders = ", ".join(placeholder for _ in normalized_statuses)
|
||||||
|
age_clause = f"AND updated_at <= {placeholder}" if updated_before else ""
|
||||||
|
limit_clause = f"LIMIT {placeholder}" if limit is not None else ""
|
||||||
|
params: list[Any] = list(normalized_statuses)
|
||||||
|
if updated_before:
|
||||||
|
params.append(updated_before)
|
||||||
|
if limit is not None:
|
||||||
|
params.append(_limit(limit))
|
||||||
conn = self.database.connect()
|
conn = self.database.connect()
|
||||||
try:
|
try:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
|
|
@ -184,11 +193,11 @@ class JobRepository:
|
||||||
SELECT {TASK_COLUMNS}
|
SELECT {TASK_COLUMNS}
|
||||||
FROM generation_tasks
|
FROM generation_tasks
|
||||||
WHERE status IN ({status_placeholders})
|
WHERE status IN ({status_placeholders})
|
||||||
AND updated_at <= {placeholder}
|
{age_clause}
|
||||||
ORDER BY updated_at ASC, created_at ASC, task_id ASC
|
ORDER BY updated_at ASC, created_at ASC, task_id ASC
|
||||||
LIMIT {placeholder}
|
{limit_clause}
|
||||||
""",
|
""",
|
||||||
(*normalized_statuses, updated_before, _limit(limit)),
|
tuple(params),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
||||||
|
|
@ -25,9 +25,22 @@ WARDROBE_COLUMNS = """
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
WARDROBE_TABLES = frozenset({"wardrobe_items", "advanced_wardrobe_items"})
|
||||||
|
|
||||||
|
|
||||||
class WardrobeRepository:
|
class WardrobeRepository:
|
||||||
def __init__(self, database: Database):
|
def __init__(
|
||||||
|
self,
|
||||||
|
database: Database,
|
||||||
|
*,
|
||||||
|
table_name: str = "wardrobe_items",
|
||||||
|
library_kind: str = "standard",
|
||||||
|
):
|
||||||
|
if table_name not in WARDROBE_TABLES:
|
||||||
|
raise ValueError(f"unsupported wardrobe table: {table_name}")
|
||||||
self.database = database
|
self.database = database
|
||||||
|
self.table_name = table_name
|
||||||
|
self.library_kind = library_kind
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def placeholder(self) -> str:
|
def placeholder(self) -> str:
|
||||||
|
|
@ -39,7 +52,7 @@ class WardrobeRepository:
|
||||||
try:
|
try:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
f"""
|
f"""
|
||||||
INSERT INTO wardrobe_items (
|
INSERT INTO {self.table_name} (
|
||||||
wardrobe_item_id,
|
wardrobe_item_id,
|
||||||
profile_id,
|
profile_id,
|
||||||
material_id,
|
material_id,
|
||||||
|
|
@ -77,12 +90,12 @@ class WardrobeRepository:
|
||||||
conn = self.database.connect()
|
conn = self.database.connect()
|
||||||
try:
|
try:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
f"SELECT {WARDROBE_COLUMNS} FROM wardrobe_items WHERE wardrobe_item_id = {placeholder}",
|
f"SELECT {WARDROBE_COLUMNS} FROM {self.table_name} WHERE wardrobe_item_id = {placeholder}",
|
||||||
(wardrobe_item_id,),
|
(wardrobe_item_id,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
return _row_to_item(row) if row else None
|
return _row_to_item(row, library_kind=self.library_kind) if row else None
|
||||||
|
|
||||||
def list_by_profile(self, profile_id: str, wardrobe_category: str | None = None) -> list[WardrobeItem]:
|
def list_by_profile(self, profile_id: str, wardrobe_category: str | None = None) -> list[WardrobeItem]:
|
||||||
placeholder = self.placeholder
|
placeholder = self.placeholder
|
||||||
|
|
@ -96,7 +109,7 @@ class WardrobeRepository:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
f"""
|
f"""
|
||||||
SELECT {WARDROBE_COLUMNS}
|
SELECT {WARDROBE_COLUMNS}
|
||||||
FROM wardrobe_items
|
FROM {self.table_name}
|
||||||
WHERE {" AND ".join(where)}
|
WHERE {" AND ".join(where)}
|
||||||
ORDER BY is_favorite DESC, usage_count ASC, created_at ASC
|
ORDER BY is_favorite DESC, usage_count ASC, created_at ASC
|
||||||
""",
|
""",
|
||||||
|
|
@ -104,7 +117,7 @@ class WardrobeRepository:
|
||||||
).fetchall()
|
).fetchall()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
return [_row_to_item(row) for row in rows]
|
return [_row_to_item(row, library_kind=self.library_kind) for row in rows]
|
||||||
|
|
||||||
def delete(self, wardrobe_item_id: str) -> WardrobeItem | None:
|
def delete(self, wardrobe_item_id: str) -> WardrobeItem | None:
|
||||||
before = self.get(wardrobe_item_id)
|
before = self.get(wardrobe_item_id)
|
||||||
|
|
@ -113,7 +126,7 @@ class WardrobeRepository:
|
||||||
placeholder = self.placeholder
|
placeholder = self.placeholder
|
||||||
conn = self.database.connect()
|
conn = self.database.connect()
|
||||||
try:
|
try:
|
||||||
conn.execute(f"DELETE FROM wardrobe_items WHERE wardrobe_item_id = {placeholder}", (wardrobe_item_id,))
|
conn.execute(f"DELETE FROM {self.table_name} WHERE wardrobe_item_id = {placeholder}", (wardrobe_item_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
@ -125,7 +138,7 @@ class WardrobeRepository:
|
||||||
try:
|
try:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
f"""
|
f"""
|
||||||
UPDATE wardrobe_items
|
UPDATE {self.table_name}
|
||||||
SET usage_count = usage_count + 1,
|
SET usage_count = usage_count + 1,
|
||||||
last_used_at = CURRENT_TIMESTAMP,
|
last_used_at = CURRENT_TIMESTAMP,
|
||||||
updated_at = CURRENT_TIMESTAMP
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
|
@ -139,7 +152,18 @@ class WardrobeRepository:
|
||||||
return self.get(wardrobe_item_id)
|
return self.get(wardrobe_item_id)
|
||||||
|
|
||||||
|
|
||||||
def _row_to_item(row) -> WardrobeItem:
|
class AdvancedWardrobeRepository(WardrobeRepository):
|
||||||
|
"""Wardrobe storage whose material FK targets verified advanced assets."""
|
||||||
|
|
||||||
|
def __init__(self, database: Database):
|
||||||
|
super().__init__(
|
||||||
|
database,
|
||||||
|
table_name="advanced_wardrobe_items",
|
||||||
|
library_kind="advanced",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _row_to_item(row, *, library_kind: str = "standard") -> WardrobeItem:
|
||||||
return WardrobeItem(
|
return WardrobeItem(
|
||||||
wardrobe_item_id=row["wardrobe_item_id"],
|
wardrobe_item_id=row["wardrobe_item_id"],
|
||||||
profile_id=row["profile_id"],
|
profile_id=row["profile_id"],
|
||||||
|
|
@ -153,6 +177,7 @@ def _row_to_item(row) -> WardrobeItem:
|
||||||
last_used_at=str(row["last_used_at"]) if row["last_used_at"] else None,
|
last_used_at=str(row["last_used_at"]) if row["last_used_at"] else None,
|
||||||
created_at=str(row["created_at"]),
|
created_at=str(row["created_at"]),
|
||||||
updated_at=str(row["updated_at"]),
|
updated_at=str(row["updated_at"]),
|
||||||
|
library_kind=library_kind,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
# 进阶素材导入与还原验证工作流
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
|
||||||
|
进阶素材用于保存经过“文字提示词可还原性”验证的高可信素材。普通素材流程保持不变;进阶素材拥有独立数据库表、独立文件目录和独立后台任务,不会把验证图写入普通图库或角色工作流候选池。
|
||||||
|
|
||||||
|
## 状态机
|
||||||
|
|
||||||
|
```text
|
||||||
|
上传源图
|
||||||
|
-> recognition_queued
|
||||||
|
-> recognizing
|
||||||
|
-> ready_for_validation
|
||||||
|
-> validation_queued
|
||||||
|
-> validating
|
||||||
|
-> awaiting_review
|
||||||
|
|-- 接受 -> accepted -> advanced_materials(active)
|
||||||
|
`-- 不接受 -> adjustment_required
|
||||||
|
-> validation_queued(下一轮)
|
||||||
|
```
|
||||||
|
|
||||||
|
失败状态为 `recognition_failed` 和 `validation_failed`,均保留源图、识别结果和已完成轮次,并允许人工重试。验证生图任务不会在插件重启后自动重放,避免重复付费;识别任务可以安全恢复。
|
||||||
|
|
||||||
|
运行中取消使用导入与轮次双重 compare-and-set。提供方迟到返回时只保留脱敏后的计费归因,生成文件会被删除,导入和轮次不会被重新改回 `awaiting_review`。插件启动会处理旧进程留下的全部 `running/retrying` 进阶任务,不等待五分钟陈旧窗口。
|
||||||
|
|
||||||
|
## 隔离边界
|
||||||
|
|
||||||
|
- 普通素材表:`materials`
|
||||||
|
- 进阶导入会话:`advanced_material_imports`
|
||||||
|
- 进阶验证轮次:`advanced_material_validation_attempts`
|
||||||
|
- 已封存进阶素材:`advanced_materials`
|
||||||
|
- 普通素材目录:`storage://materials/...`
|
||||||
|
- 进阶素材目录:`storage://advanced_materials/...`
|
||||||
|
- 验证图不会创建 `generation_images` 记录,也不会进入普通图库。
|
||||||
|
- 验证生图请求只携带识别提示词,不携带源图作为 `input_images`。
|
||||||
|
|
||||||
|
## 人工审核规则
|
||||||
|
|
||||||
|
- 只有当前 `awaiting_review` 且验证图存在的轮次可以封存。
|
||||||
|
- 模型或主观评分只作为记录,不能自动封存。
|
||||||
|
- “不还原”必须填写调整描述;描述会形成新的提示词修订和验证轮次,旧轮次永久保留。
|
||||||
|
- 封存时保存原始素材作为角色引用图,验证图仅作为还原证据。
|
||||||
|
|
||||||
|
## 高优先级规则
|
||||||
|
|
||||||
|
统一素材目录通过服务端解析 `advmat_` 记录。只有 `advanced_materials.status=active` 的记录会获得可信的 `advanced_verified` 标记和优先级加成;普通素材即使伪造同名 metadata 也不会获得加成。用户明确锁定或设为必需的素材仍高于自动进阶加成。
|
||||||
|
|
||||||
|
## 内容安全、路由与预算
|
||||||
|
|
||||||
|
- 规则审核只检查正向需求;负向提示词中的 `nudity / gore / child` 等排除词不会被当成用户想生成的内容。
|
||||||
|
- 恐怖主义、极端主义、现实高危暴力和极端血腥在调用生图提供方前直接禁止并记录高优先级审计。
|
||||||
|
- 合法成人内容只有在入口开关、用户/群组白名单和 NSFW 路由同时满足时才会分流。
|
||||||
|
- 普通模型只有返回明确的成人/NSFW 内容安全拒绝时才允许向 NSFW 路由回退一次;通用安全错误、未成年人、恐暴或未知原因不会盲目回退。
|
||||||
|
- safe/sensitive 内容始终使用 `advanced_material_validation_generation` 专用模型,不被全局普通生图路由覆盖。
|
||||||
|
- `advanced_materials.cost_budget` 可配置统计窗口、任务/图片/费用上限和请求/图片/Token 单价。自动回退按最坏两次提供方请求预检。
|
||||||
|
|
||||||
|
## 主要接口
|
||||||
|
|
||||||
|
- `POST /advanced-material-imports/upload`
|
||||||
|
- `GET /advanced-material-imports`
|
||||||
|
- `GET /advanced-material-imports/{import_id}`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/retry`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/validation-attempts`
|
||||||
|
- `GET /advanced-material-imports/{import_id}/validation-attempts`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/attempts/{attempt_id}/reject`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/attempts/{attempt_id}/accept`
|
||||||
|
- `GET /advanced-materials`
|
||||||
|
- `GET /material-catalog`
|
||||||
|
|
||||||
|
上传、重试和创建验证轮次均立即返回任务信息;耗时识别和生图由持久 Worker 执行。
|
||||||
|
|
@ -0,0 +1,162 @@
|
||||||
|
# 进阶画风样本组:多图交叉提取与纯文本迁移验证
|
||||||
|
|
||||||
|
## 目标与边界
|
||||||
|
|
||||||
|
本功能只对素材根分类“风格”开放。服装、鞋袜、配饰、构图等普通与进阶素材继续使用单图导入,不改变现有接口语义。
|
||||||
|
|
||||||
|
一个进阶画风样本组接收 2~8 张同画风图片(推荐 3~6 张),将每张图片拆成完全独立、同时执行的视觉识别任务;全部可用结果完成后,再由交叉分析任务同时读取原图与逐图报告,分离共同画风、可变特征和内容污染。验证阶段不向生图模型传递任何源图,只把统一画风胶囊应用到与源样本完全不同的角色、场景和构图,以验证画风的迁移能力,而不是源图复刻能力。
|
||||||
|
|
||||||
|
最终仍封存为一个 `advmat_...` 进阶素材目录项。现有素材目录、衣橱、详细角色工作流继续通过统一 Material 合约使用它;旧的单图进阶素材不需要迁移。
|
||||||
|
|
||||||
|
## 用户流程
|
||||||
|
|
||||||
|
```text
|
||||||
|
选择“风格”
|
||||||
|
-> 上传 2~8 张样本
|
||||||
|
-> 每张样本创建独立识别任务并同时派发
|
||||||
|
-> 成功样本达到至少 2 张
|
||||||
|
-> 交叉模型同时读取全部有效原图与逐图报告
|
||||||
|
-> 生成共同画风、可变项、内容污染与异常样本报告
|
||||||
|
-> 自动规划三个与源样本语义显著不同的验证场景
|
||||||
|
-> 三个纯文本生图任务同时派发(无 input_images / image)
|
||||||
|
-> 人工对照三项迁移结果
|
||||||
|
|-- 接受 -> 封存一个高优先级进阶画风
|
||||||
|
`-- 调整 -> 重建统一胶囊 -> 使用同一组场景重新并行验证
|
||||||
|
```
|
||||||
|
|
||||||
|
## 并行任务与屏障
|
||||||
|
|
||||||
|
### 单图识别
|
||||||
|
|
||||||
|
- 每张源图拥有独立 `source_id`、`task_id`、状态、超时、重试次数、错误和识别结果。
|
||||||
|
- 同一组内的 2~8 个识别任务一次性入队;Worker 不串行等待,调度并发上限默认等于组内图片数,硬上限为 8。
|
||||||
|
- 任何一张失败都不得取消或超时其他任务,也不得共享计时器。
|
||||||
|
- 失败样本可以单独重试或排除;成功样本不少于 2 张时允许用户继续。
|
||||||
|
- 交叉分析通过数据库屏障触发:所有未排除任务进入终态,且成功数不少于 2;重复回调必须幂等,最多创建一个交叉分析任务。
|
||||||
|
|
||||||
|
### 验证生成
|
||||||
|
|
||||||
|
- 默认生成 `portrait`、`fullbody`、`novel_scene` 三个验证案例。
|
||||||
|
- 三个案例分别创建任务并同时派发,每个案例拥有独立超时、重试、取消和错误。
|
||||||
|
- 验证批次只在全部未排除案例进入终态后进入人工审核;单例失败可以单独重试。
|
||||||
|
- 所有耗时接口立即返回“已入队”,前端通过导入详情轮询状态。
|
||||||
|
|
||||||
|
## 画风交叉分析
|
||||||
|
|
||||||
|
交叉模型输入:
|
||||||
|
|
||||||
|
- 全部有效原图;
|
||||||
|
- 每张图片的结构化识别报告;
|
||||||
|
- 每张图片的内容摘要;
|
||||||
|
- 用户补充的画风要求;
|
||||||
|
- 明确的“只抽取可观察画风、不继承内容”约束。
|
||||||
|
|
||||||
|
交叉结果至少包含:
|
||||||
|
|
||||||
|
- `consensus_style`:多图稳定共同特征;
|
||||||
|
- `variable_style_features`:部分样本存在的弱特征;
|
||||||
|
- `source_content_features`:人物、服装、姿势、道具、场景与构图内容;
|
||||||
|
- `content_leakage_exclusions`:正式提示词必须排除的内容污染;
|
||||||
|
- `outlier_source_ids`:疑似异画风样本;
|
||||||
|
- `representative_source_ids`:按风格强度、内容差异和污染风险选择的 1~3 张代表图;
|
||||||
|
- `consensus_confidence` 与逐特征证据;
|
||||||
|
- `compact / standard / detailed` 三档统一画风胶囊。
|
||||||
|
|
||||||
|
共同特征的默认分级:
|
||||||
|
|
||||||
|
- 支持率不低于 60% 且置信度达标:核心画风;
|
||||||
|
- 支持率 40%~60%:可变或弱画风;
|
||||||
|
- 支持率低于 40%:不进入核心胶囊;
|
||||||
|
- 人物身份、服装、姿势、道具、文字、背景主体:进入内容污染或禁止继承项;
|
||||||
|
- 近重复图片降低证据权重,避免重复样本放大偶然特征。
|
||||||
|
|
||||||
|
## 纯文本异角色异场景验证
|
||||||
|
|
||||||
|
验证规划器先根据 `source_content_features` 生成三个语义距离显著的内容案例。案例必须改变尽可能多的内容维度:年龄、性别或物种、服装、姿势、镜头距离、室内外、背景、道具和构图。
|
||||||
|
|
||||||
|
每个案例分离保存:
|
||||||
|
|
||||||
|
- `content_prompt`:只描述新角色与新场景;
|
||||||
|
- `style_prompt`:统一画风胶囊;
|
||||||
|
- `final_prompt`:由后端可追踪地合并两者;
|
||||||
|
- `negative_prompt`:画风禁止项与内容污染排除项;
|
||||||
|
- 路由、模型、seed、输出图、用量与错误。
|
||||||
|
|
||||||
|
生图请求必须满足:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"input_images": [],
|
||||||
|
"image": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
验证输出可以由 Vision 模型依据统一画风指纹进行辅助审核,但不得以人物是否像源图作为指标。审核维度包括线条、着色、阴影、色彩规律、边缘、高光、纹理、媒介感、细节密度和内容污染。自动评分只作参考,不能自动封存。
|
||||||
|
|
||||||
|
## 人工调整与版本一致性
|
||||||
|
|
||||||
|
- 调整说明不得只追加到顶层 prompt。
|
||||||
|
- 每次调整必须生成新的共识版本,并同步重建三档胶囊、负向词与内容污染排除项。
|
||||||
|
- 使用同一组三个验证案例重新生成,便于前后对比;旧版本和旧验证结果永久保留。
|
||||||
|
- 封存时必须引用当前已审核的共识版本,杜绝“验证用新提示词、正式生图仍用旧胶囊”。
|
||||||
|
|
||||||
|
## 数据模型
|
||||||
|
|
||||||
|
在现有 `advanced_material_imports / advanced_material_validation_attempts / advanced_materials` 之外增加风格专用子表:
|
||||||
|
|
||||||
|
- `advanced_style_sources`:源图、缩略图、排序、主参考、排除状态、独立任务与识别结果;
|
||||||
|
- `advanced_style_consensus_runs`:交叉分析输入摘要、共同画风、可变项、内容污染、代表图、统一胶囊和版本号;
|
||||||
|
- `advanced_style_validation_cases`:一个共识版本下的三个异场景案例、独立任务、输出图与审核结果。
|
||||||
|
|
||||||
|
导入主记录通过 metadata 保存 `workflow_kind=style_set`、当前共识版本和批次状态。`advanced_materials.source_image_uri` 继续保存主参考图以兼容旧消费者,完整源图与最多三张代表图通过关联数据和可信 metadata 暴露。
|
||||||
|
|
||||||
|
## 接口与兼容策略
|
||||||
|
|
||||||
|
保留所有现有单图接口,增加风格组接口:
|
||||||
|
|
||||||
|
- `POST /advanced-material-imports/style-set/upload`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/style-sources/{source_id}/retry`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/style-sources/{source_id}/exclude`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/style-consensus`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/style-validation-cases/{case_id}/retry`
|
||||||
|
- `POST /advanced-material-imports/{import_id}/validation-attempts`(兼容入口;确保三场景批次存在)
|
||||||
|
- `POST /advanced-material-imports/{import_id}/attempts/{attempt_id}/reject`(携带调整说明并创建新共识版本)
|
||||||
|
- `POST /advanced-material-imports/{import_id}/attempts/{attempt_id}/accept`(封存当前已审核版本)
|
||||||
|
|
||||||
|
服务端按 `material_categories` 的规范名称确认“风格”,不信任前端标签。非风格分类上传多图必须返回明确校验错误。旧单图进阶素材仍走原接口和原状态机。
|
||||||
|
|
||||||
|
## 下游应用
|
||||||
|
|
||||||
|
- 快速角色:使用统一画风胶囊,不自动发送源图,维持当前轻量路径。
|
||||||
|
- 详细角色工作流:使用 detailed 胶囊;只有提供方明确支持参考图时才选择主参考及最多两张代表图。
|
||||||
|
- 适配器不支持原生参考角色/权重时,优先只发送主参考图,避免人物、服装和构图污染。
|
||||||
|
- 验证图永不进入普通图库、角色候选池或正式参考图集合。
|
||||||
|
|
||||||
|
## 开发队列与验收状态
|
||||||
|
|
||||||
|
- [x] P0:新增风格样本、共识版本和验证案例迁移、DTO 与仓储。
|
||||||
|
- [x] P0:后端只允许“风格”使用 2~8 张,多图上传原子落盘,失败时清理新文件。
|
||||||
|
- [x] P0:逐图任务独立入队、独立超时/重试/错误,批次同时派发并提供幂等屏障。
|
||||||
|
- [x] P0:交叉分析同时读取全部有效原图和逐图报告,生成带证据的统一画风结构与三档胶囊。
|
||||||
|
- [x] P0:验证规划生成三个与源内容显著不同的案例;生图请求不得携带任何源图。
|
||||||
|
- [x] P0:三个验证案例独立并行、可单独重试,失败不影响其他案例。
|
||||||
|
- [x] P1:人工调整创建新共识版本并同步重建胶囊;封存只能引用当前已审核版本。
|
||||||
|
- [x] P1:统一目录继续输出一个 `advmat_`,可信 metadata 携带代表源图但不暴露伪造优先级。
|
||||||
|
- [x] P1:前端仅在选择“风格”时启用多图上传、排序、主参考、排除和逐图状态。
|
||||||
|
- [x] P1:前端展示当前共识版本、共同画风、可变项、内容污染、异常样本和三案例验证。
|
||||||
|
- [x] P2:备份恢复、孤儿媒体、成本预算、统计与日志覆盖新增表和文件。
|
||||||
|
- [x] P2:迁移、仓储、服务、Worker 恢复、权限、路由、契约、类型检查和深夜模式测试。
|
||||||
|
- [x] P2:完整后端测试、前端契约、类型检查、生产构建和 `git diff --check` 全部通过。
|
||||||
|
|
||||||
|
## 验收标准
|
||||||
|
|
||||||
|
1. 非风格分类无法创建多图组;旧单图进阶流程无回归。
|
||||||
|
2. 风格组支持 2~8 张,所有单图识别任务同时进入队列且无共享超时。
|
||||||
|
3. 单图失败可单独重试、排除;至少两张成功后可以交叉分析。
|
||||||
|
4. 交叉结果能追溯每个核心特征来自哪些图片,并分离源内容污染。
|
||||||
|
5. 三个验证案例的角色、场景和构图与源样本显著不同,且 provider 请求没有源图。
|
||||||
|
6. 三个案例独立并行,任一失败不会覆盖其他任务状态。
|
||||||
|
7. 人工调整后统一胶囊版本发生变化,封存素材使用新胶囊。
|
||||||
|
8. 最终只产生一个进阶画风素材,验证图保持隔离。
|
||||||
|
9. 旧数据库可平滑迁移,插件重启可恢复识别任务但不会自动重复付费验证。
|
||||||
|
10. 全量自动化测试与静态构建通过,测试过程不调用真实付费模型。
|
||||||
文件差异内容过多而无法显示
加载差异
|
|
@ -0,0 +1,83 @@
|
||||||
|
# ImageStudio 前端 UI 审计
|
||||||
|
|
||||||
|
日期:2026-07-21
|
||||||
|
范围:`frontend/standalone-web` 工作台、共享 API 类型、导航与 Gallery 页面
|
||||||
|
方法:Impeccable `audit` 技术检查、源码静态审计、基线 typecheck/build/contract tests
|
||||||
|
|
||||||
|
## 项目盘点
|
||||||
|
|
||||||
|
### 技术栈与入口
|
||||||
|
|
||||||
|
- Vue 3 Composition API + TypeScript + Vite 6。
|
||||||
|
- 独立 Web 入口:`frontend/standalone-web/src/main.ts` → `App.vue`。
|
||||||
|
- AstrBot 插件页入口:`frontend/plugin-page/src/main.ts`,通过 `astrbot-page-bridge` 注入后复用 `standalone-web/src/App.vue`。
|
||||||
|
- API 统一入口:`frontend/shared/api/client.ts`;路径常量集中在 `frontend/shared/api/endpoints.ts`,基础路径为 `/api/v1/plugins/extensions/astrbot_plugin_imagestudio`。
|
||||||
|
- 当前无 Vue Router;页面切换由 `activeNav` + URL 查询参数 `view` / `module` / `materialView` / `profile` 维护,并使用 `history.replaceState`。
|
||||||
|
|
||||||
|
### 页面与主要组件
|
||||||
|
|
||||||
|
- 工作台页面:overview、generate、queue、performance、gallery、profiles、materials、settings、logs。
|
||||||
|
- 主要页面组件:`GalleryPage.vue`、`ProfilesPage.vue`、`AdvancedMaterialImportPage.vue`、`SettingsPage.vue`、`BackupPage.vue`、`LogsPage.vue`。
|
||||||
|
- 主要复用组件:`AppNavigationRail.vue`、`StateCard.vue`、`EmptyState.vue`、`MetricCardGrid.vue`、多个 Dialog/Drawer 组件。
|
||||||
|
- 复杂业务子域:workflow、profiles、materials;多数页面仍由 `App.vue` 组合和持有状态。
|
||||||
|
|
||||||
|
### 不能改变的契约
|
||||||
|
|
||||||
|
- 不改变导航 key、module 映射、URL 查询参数语义及插件页/独立 Web 双入口。
|
||||||
|
- 不改变 `frontend/shared/api/endpoints.ts` 中的 endpoint 名称、HTTP 方法、请求体字段和响应类型。
|
||||||
|
- 不改变 `frontend/shared/types/**` 的数据结构,尤其是 image、job、workflow、profile、material、settings、storage 相关类型。
|
||||||
|
- 不改变生成、队列、图库批量操作、工作流轮次/分支、角色卡、素材识别、设置备份与日志的现有交互语义。
|
||||||
|
- 不删除 AstrBot plugin page bridge、媒体签名/载荷流程、后端连接状态与错误恢复路径。
|
||||||
|
|
||||||
|
## Audit Health Score
|
||||||
|
|
||||||
|
| 维度 | 分数 | 关键发现 |
|
||||||
|
|---|---:|---|
|
||||||
|
| Accessibility | 2/4 | 已有语义按钮、`aria-current`、`aria-pressed`、状态 live region;但部分表单控件缺少显式 label,图片预览/弹层焦点管理与键盘闭环需要统一验证。 |
|
||||||
|
| Performance | 2/4 | 生产构建可用;`App.vue` 单文件约 22k 行、Web JS gzip 约 211.5 kB,且存在 `transition: width`、`transition: max-height` 等布局属性动画。 |
|
||||||
|
| Theming | 2/4 | 有 dark/light 变量和主色持久化;但 tokens 集中在 `App.vue`,大量页面级颜色/阴影/渐变仍混杂,主题边界难以复用。 |
|
||||||
|
| Responsive Design | 2/4 | Gallery 等页面有 1180/900/560 断点;工作台整体仍依赖 244px rail、宽 topbar 与多列面板,窄桌面窗口存在拥挤/溢出风险。 |
|
||||||
|
| Anti-Patterns | 2/4 | 本地 detector 命中布局属性动画、圆角元素厚边、侧边/顶部强调条、占位图片检测;背景网格、玻璃模糊和多层渐变也提高了视觉噪声。 |
|
||||||
|
| **Total** | **10/20** | **Acceptable:功能基础稳定,但需要有边界的结构化 UI 重构。** |
|
||||||
|
|
||||||
|
## Anti-Patterns Verdict
|
||||||
|
|
||||||
|
**部分通过,仍有明显 AI/模板化痕迹。** 具体包括:工作台背景的装饰性网格、多个 surface 的渐变与 blur、状态卡片的顶部强调条、导航 active 状态的侧边强调、圆角 + 宽阴影组合,以及大单体 App 文件导致的重复视觉词汇难以治理。它们不是功能阻塞,但会让工具界面显得“装饰先于任务”。
|
||||||
|
|
||||||
|
## 问题清单与优先级
|
||||||
|
|
||||||
|
### P0 Blocking
|
||||||
|
|
||||||
|
- 当前没有确认到会阻塞主要任务完成的 P0 UI 问题。基线功能检查全部通过。
|
||||||
|
|
||||||
|
### P1 Major
|
||||||
|
|
||||||
|
- **P1-01:工作台壳层与业务页面耦合过重**:`frontend/standalone-web/src/App.vue` 约 22k 行,同时承载导航、数据加载、弹层、生成器、队列、图库、素材与设置。影响:任何视觉调整都容易触碰业务状态,回归面大。
|
||||||
|
- **P1-02:桌面窄窗口的结构风险**:导航 rail、sticky topbar、双栏工作区和多个固定最小宽度并存,约 1024–1280px 宽度下容易造成操作区压缩、横向滚动或首屏信息层级失衡。
|
||||||
|
- **P1-03:主题 token 没有形成可复用层**:核心变量主要位于 `App.vue` 的全局 style,页面组件继续直接组合 `var(--panel)`、`var(--border)`、颜色混合和阴影。影响:dark/light 与未来页面统一成本高。
|
||||||
|
- **P1-04:交互状态覆盖不均**:部分按钮有 disabled/hover/focus,弹层、批量操作、加载、空态、错误态的状态表达不完全统一;需要以组件级状态矩阵补齐。
|
||||||
|
- **P1-05:可访问性需专项修复**:`GalleryPage.vue` 搜索框和批量 checkbox 等控件依赖邻近文本,部分复杂弹层/预览需要确认 focus return、Escape、焦点陷阱与可读名称;不能只依赖视觉状态。
|
||||||
|
- **P1-06:性能边界**:`App.vue` 产生单一大 JS/CSS 包,构建已给出超过 500 kB 的 chunk 警告;本轮不改业务加载策略,但应避免新增全局样式和重型运行时依赖。
|
||||||
|
|
||||||
|
### P2 Minor
|
||||||
|
|
||||||
|
- **P2-01:视觉节奏不一致**:8/10/12/14/16/18/22/24 等间距和 7/8/10/12 等圆角并存,需抽取有限的 spacing/radius scale。
|
||||||
|
- **P2-02:装饰噪声偏高**:背景网格、渐变、backdrop-filter 在多个层级重复,降低任务区域的对比度和层级清晰度。
|
||||||
|
- **P2-03:状态色与表面色混用**:good/warn/bad/idle 的 border、背景、顶部条规则分散在多个选择器,需集中到语义状态 tokens。
|
||||||
|
- **P2-04:图库卡片信息密度不稳定**:grid/list/inspector 三种模式的操作按钮、选中态和媒体占比不完全一致,批量操作区在窄桌面易成为第二工具栏。
|
||||||
|
- **P2-05:部分过渡动画直接改变布局属性**:检测命中 `transition: width` 与 `transition: max-height`;应优先改为 transform/opacity 或 grid 行过渡。
|
||||||
|
- **P2-06:图片替代文本规则不统一**:多数业务图片有 alt,但预览/通知缩略图存在空 alt 或依赖上下文的情况,需要区分装饰图与内容图。
|
||||||
|
|
||||||
|
## 正向发现
|
||||||
|
|
||||||
|
- 业务 API 与类型文件集中,页面重构可以保持数据契约不变。
|
||||||
|
- 导航、状态卡、空态、预览对话框已有复用组件,不需要推倒重来。
|
||||||
|
- Gallery 已具备搜索、筛选、grid/list、批量操作、预览、错误和 loading 路径,适合作为第一批页面。
|
||||||
|
- 基线 `npm.cmd run typecheck`、`npm.cmd run build:web`、`npm.cmd run test:contracts` 均通过。
|
||||||
|
|
||||||
|
## 来源与边界
|
||||||
|
|
||||||
|
- 本地源码:`frontend/standalone-web/src/App.vue`、`frontend/standalone-web/src/features/gallery/GalleryPage.vue`、`frontend/standalone-web/src/components/AppNavigationRail.vue`、`frontend/shared/api/client.ts`、`frontend/shared/api/endpoints.ts`、`frontend/shared/types/**`。
|
||||||
|
- 本地配置:`frontend/package.json`、`frontend/standalone-web/vite.config.ts`、`frontend/plugin-page/vite.config.ts`。
|
||||||
|
- Impeccable 本地 detector:命中 5 项静态提示,未替代人工审计。
|
||||||
|
- 未使用外部网络资料;本次目标是对现有仓库实现做代码级审计。
|
||||||
|
|
@ -0,0 +1,164 @@
|
||||||
|
# ImageStudio UI 重构后续开发队列
|
||||||
|
|
||||||
|
日期:2026-07-21
|
||||||
|
基线分支:`codex/ui-redesign-gallery`
|
||||||
|
范围:仅覆盖本轮 UI 重构尚未完成的事项;不包含后端功能新增。
|
||||||
|
|
||||||
|
## 当前结论
|
||||||
|
|
||||||
|
- 已完成:共享视觉 token、工作台壳层、主要页面统一 surface/间距/圆角/状态/focus、Gallery 首批重构、桌面横向溢出修复、静态 detector 检查。
|
||||||
|
- 尚未完成:真实 AstrBot 后端数据验收、逐页深度视觉精修、完整键盘/焦点审计、多个桌面尺寸验证、性能拆包、提交与发布收口。
|
||||||
|
- 当前分支仍有未提交源码和文档改动;主支未修改。
|
||||||
|
|
||||||
|
## P0:交付阻断项
|
||||||
|
|
||||||
|
### Q0-01 真实 AstrBot 后端联调
|
||||||
|
|
||||||
|
**目标**:在真实 plugin-page bridge 和后端 API 下验证 UI,不再只依赖 preview mode。
|
||||||
|
**涉及**:`frontend/plugin-page/src/main.ts`、`frontend/shared/api/client.ts`、所有主要页面。
|
||||||
|
**验收**:
|
||||||
|
|
||||||
|
- plugin-page 能加载真实 bootstrap、dashboard、profiles、images、jobs、settings、logs。
|
||||||
|
- 后端未连接、401、超时、空数据、部分数据错误状态均有可读反馈。
|
||||||
|
- 真实媒体签名、预览、刷新和批量操作不出现空白或死状态。
|
||||||
|
|
||||||
|
### Q0-02 保护当前未提交改动并完成分支交付
|
||||||
|
|
||||||
|
**目标**:确认 `GalleryPage.vue` 原有改动与本轮改动的归属,完成 diff review、提交和 PR。
|
||||||
|
**验收**:
|
||||||
|
|
||||||
|
- `git diff --check` 通过。
|
||||||
|
- 无构建产物污染 `web/` 或 `pages/imagestudio/`。
|
||||||
|
- 用户确认后创建 commit/PR;未确认前不合并主支。
|
||||||
|
|
||||||
|
## P1:发布前必须完成
|
||||||
|
|
||||||
|
### Q1-01 逐页深度视觉精修
|
||||||
|
|
||||||
|
当前统一主要通过共享 CSS 层完成,以下页面还需要逐页检查内容层级、密度和操作优先级:
|
||||||
|
|
||||||
|
- Overview:指标条、监控摘要、队列摘要、最近图片之间的层级和密度。
|
||||||
|
- Generate:预览区、提示词输入、模型选择、生成操作和结果信息的空间分配。
|
||||||
|
- Queue:过滤、任务状态、进度、详情和批量操作的优先级。
|
||||||
|
- Performance:指标、趋势/明细、空态和失败态。
|
||||||
|
- Profiles:master/detail/wardrobe 三栏在有数据、无数据和 sealed 状态下的层级。
|
||||||
|
- Materials:导入、识别、确认、筛选、详情和空态。
|
||||||
|
- Settings:section 导航、配置编辑、保存/校验/回滚状态。
|
||||||
|
- Logs:筛选、日志列表、错误状态和长文本换行。
|
||||||
|
- Workflow:节点流、轮次、分支、候选图、审查 dialog、素材 drawer。
|
||||||
|
|
||||||
|
**验收**:每页保留现有功能,并有明确的主操作、次操作、危险操作和恢复路径。
|
||||||
|
|
||||||
|
### Q1-02 完整可访问性审计
|
||||||
|
|
||||||
|
**涉及**:所有 `*.vue` 页面和 Dialog/Drawer 组件。
|
||||||
|
**任务**:
|
||||||
|
|
||||||
|
- 为搜索、筛选、checkbox、select、textarea、icon-only button 补齐稳定 label。
|
||||||
|
- 验证 Tab 顺序、Enter/Space、Escape、焦点回收和 dialog focus trap。
|
||||||
|
- 检查 heading 层级、landmark、`aria-current`、`aria-expanded`、`aria-selected`、`aria-live`。
|
||||||
|
- 检查真实图片 alt、装饰图空 alt、加载/失败图片的替代内容。
|
||||||
|
- 使用键盘完成 Gallery 批量操作、Profiles 选择、Workflow 节点操作和 Settings 保存。
|
||||||
|
|
||||||
|
**验收**:关键路径不依赖鼠标;焦点在 dark/light 两主题下可见。
|
||||||
|
|
||||||
|
### Q1-03 多尺寸响应式验收
|
||||||
|
|
||||||
|
**必须验证尺寸**:
|
||||||
|
|
||||||
|
- 1024×768:窄桌面,检查 rail、topbar、双栏/三栏区域。
|
||||||
|
- 1280×800:常见桌面工作区。
|
||||||
|
- 1440×900:宽桌面,检查内容是否过度拉伸。
|
||||||
|
- 1600×900:超宽窗口,检查 max-width 和阅读线长。
|
||||||
|
|
||||||
|
**验收**:无横向溢出;sticky topbar/rail 不遮挡内容;批量工具栏和 dialog 不被裁切。
|
||||||
|
|
||||||
|
### Q1-04 状态矩阵补齐
|
||||||
|
|
||||||
|
为每个主要页面记录并验证:default、hover、focus、active/selected、disabled、loading、empty、error、success、backend disconnected。
|
||||||
|
重点组件:按钮、tabs、filters、cards、dialogs、drawers、图片预览、表单保存栏。
|
||||||
|
|
||||||
|
## P2:质量和维护性
|
||||||
|
|
||||||
|
### Q2-01 视觉回归测试
|
||||||
|
|
||||||
|
- 为 9 个主要 view 建立最小 Playwright/浏览器 smoke test。
|
||||||
|
- 固定至少一组 dark/light 截图或 DOM 断言。
|
||||||
|
- 断言 `scrollWidth === clientWidth`、页面标题、主要 landmark 和关键操作存在。
|
||||||
|
- 将真实 backend 不可用场景纳入 preview-mode regression。
|
||||||
|
|
||||||
|
### Q2-02 前端拆包与性能优化
|
||||||
|
|
||||||
|
**现状**:Web JS gzip 约 211.6 kB,Vite 报告单 chunk 超过 500 kB。
|
||||||
|
**任务**:
|
||||||
|
|
||||||
|
- 评估按页面动态导入 Generate、Profiles、Materials、Settings、Workflow。
|
||||||
|
- 保证 plugin-page bridge 首屏和 `App.vue` 的 URL 参数恢复不受影响。
|
||||||
|
- 避免新增 UI 运行时依赖;对大图片列表保持懒加载和稳定的媒体 URL。
|
||||||
|
- 对生成预览、Workflow 候选图和 Materials grid 做渲染数量边界检查。
|
||||||
|
|
||||||
|
**验收**:构建 chunk 警告下降或有明确的保留理由;交互没有新增延迟。
|
||||||
|
|
||||||
|
### Q2-03 样式边界整理
|
||||||
|
|
||||||
|
- 将 `App.vue` 中新增的全局 override 按壳层、页面、组件拆到可定位样式文件。
|
||||||
|
- 避免继续增长 22k 行级别的单体 `App.vue`。
|
||||||
|
- 保留 `tokens.css` 作为唯一视觉 token 来源,减少页面内直接写颜色/圆角/阴影。
|
||||||
|
- 清理重复的局部样式和已被全局层覆盖的旧规则。
|
||||||
|
|
||||||
|
### Q2-04 主题和对比度验证
|
||||||
|
|
||||||
|
- 验证 dark/light 下正文、placeholder、disabled、warning、danger、success 的对比度。
|
||||||
|
- 复核用户自定义 primary/accent 颜色的极端值,避免 focus 和文字失去对比度。
|
||||||
|
- 记录至少一组自动化 contrast 检查结果。
|
||||||
|
|
||||||
|
## P3:可选增强
|
||||||
|
|
||||||
|
### Q3-01 设计文档和组件清单
|
||||||
|
|
||||||
|
- 为 token、button、input、surface、status、dialog、empty state 建立简短使用约定。
|
||||||
|
- 在 `docs/` 维护页面状态矩阵和可复用组件清单。
|
||||||
|
|
||||||
|
### Q3-02 真实数据密度优化
|
||||||
|
|
||||||
|
- 用真实 profiles、materials、images、jobs、logs 数据压测长标题、长 prompt、长错误消息。
|
||||||
|
- 检查分页/滚动/虚拟化需求,避免只在空数据预览态下看起来稳定。
|
||||||
|
|
||||||
|
### Q3-03 发布前人工验收
|
||||||
|
|
||||||
|
- 在 AstrBot plugin page 中完成一次完整生成、图库复用、角色选择、素材导入、设置保存、日志查看流程。
|
||||||
|
- 记录阻塞项、截图和最终版本信息。
|
||||||
|
|
||||||
|
## 推荐执行顺序
|
||||||
|
|
||||||
|
1. `Q0-01` 真实后端联调。
|
||||||
|
2. `Q1-01` 逐页深度视觉精修。
|
||||||
|
3. `Q1-02` 可访问性审计与修复。
|
||||||
|
4. `Q1-03` 四种桌面尺寸验收。
|
||||||
|
5. `Q1-04` 状态矩阵补齐。
|
||||||
|
6. `Q2-01` 回归测试。
|
||||||
|
7. `Q2-02` 拆包优化。
|
||||||
|
8. `Q2-03` 样式边界整理。
|
||||||
|
9. `Q2-04` 主题对比度验证。
|
||||||
|
10. `Q0-02` 最终 diff review、commit 和 PR。
|
||||||
|
11. `Q3-03` 真实插件页发布前验收。
|
||||||
|
|
||||||
|
## 暂不列入本队列
|
||||||
|
|
||||||
|
- 后端 API 新功能。
|
||||||
|
- 多租户权限链、持久 Worker、数据库迁移等后端架构事项。
|
||||||
|
- 更换 Vue/Vite/TypeScript 或引入新的 UI 框架。
|
||||||
|
|
||||||
|
|
||||||
|
## Execution update (2026-07-21)
|
||||||
|
|
||||||
|
- Q0-01: source-level bridge/error/preview paths validated; live AstrBot host acceptance remains pending.
|
||||||
|
- Q1-01: shared visual layer, page-level surface hierarchy, action states, and overview narrow-desktop override completed; all nine views smoke-tested.
|
||||||
|
- Q1-02: stable search/workbench/status labels added; image preview dialog now traps focus and restores focus; existing confirmation dialog trap retained.
|
||||||
|
- Q1-03: 1024x768, 1280x800, 1440x900, and 1600x900 passed across all nine views with no horizontal overflow.
|
||||||
|
- Q1-04: state matrix recorded in docs/ui-redesign-state-matrix-2026-07-21.md.
|
||||||
|
- Q2-01: added frontend/tests/ui-redesign-smoke.test.mjs and frontend/tests/ui-theme-contract.test.mjs; 7 UI contract tests pass.
|
||||||
|
- Q2-02: page and workflow components use defineAsyncComponent; production chunks are split and the largest JS chunk is below the prior warning threshold.
|
||||||
|
- Q2-03: new workbench overrides moved from App.vue into frontend/standalone-web/src/styles/workbench.css.
|
||||||
|
- Q2-04: dark/light token contrast checks added; measured text pair ratios are 16.40, 7.52, 15.14, and 4.59.
|
||||||
|
- Q0-02: diff review, build-artifact cleanup, full validation, commit, and PR are the remaining delivery actions.
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
# ImageStudio 全页面 UI 统一性检查
|
||||||
|
|
||||||
|
日期:2026-07-21
|
||||||
|
分支:`codex/ui-redesign-gallery`
|
||||||
|
|
||||||
|
## 覆盖范围
|
||||||
|
|
||||||
|
- 工作台壳层、导航 rail、topbar、主题和全局状态。
|
||||||
|
- Overview、Generate、Queue、Performance、Gallery、Profiles、Materials、Settings、Logs。
|
||||||
|
- Workflow 子组件、Profiles 子面板、Settings 子面板、Dialogs/Drawers。
|
||||||
|
- 独立 Web 与 AstrBot plugin-page 两个 Vite 入口。
|
||||||
|
|
||||||
|
## 统一规则
|
||||||
|
|
||||||
|
- 视觉 token:`frontend/standalone-web/src/styles/tokens.css`。
|
||||||
|
- 统一 surface:`var(--panel)` / `var(--panel-muted)`,默认取消装饰性宽阴影。
|
||||||
|
- 统一形状:小控件 6–8px,页面 surface 10px,状态 pill 使用 999px。
|
||||||
|
- 统一间距:4/8/12/16/20/24px。
|
||||||
|
- 统一 focus:主色 3px focus ring,表单和按钮保留键盘可见焦点。
|
||||||
|
- 统一状态:good/warn/bad/idle 使用语义边框和背景,不再依赖顶部/侧边粗色条。
|
||||||
|
- 统一动效:保留必要状态反馈;移除布局属性过渡,支持 `prefers-reduced-motion`。
|
||||||
|
- 统一响应式:修复 1265px 桌面窗口下 Overview/Gallery 横向溢出,9 个主要 view 均通过 smoke test。
|
||||||
|
|
||||||
|
## 结果
|
||||||
|
|
||||||
|
- Impeccable detector:0 条命中。
|
||||||
|
- 浏览器 smoke test:`overview`、`generate`、`queue`、`performance`、`images`、`profiles`、`materials`、`settings`、`logs` 均成功加载。
|
||||||
|
- 桌面窗口检查:`scrollWidth === clientWidth`,未发现横向溢出。
|
||||||
|
- plugin-page bridge 入口与独立 Web 入口均可构建。
|
||||||
|
|
||||||
|
## 验证命令
|
||||||
|
|
||||||
|
- `npm.cmd run typecheck`
|
||||||
|
- `npm.cmd run test:contracts`:19/19 通过
|
||||||
|
- `npm.cmd run build:web`
|
||||||
|
- `npm.cmd run build:plugin`
|
||||||
|
- `node C:\Users\Administrator\.agents\skills\impeccable\scripts\detect.mjs --json frontend/standalone-web/src/App.vue frontend/standalone-web/src/components frontend/standalone-web/src/features`
|
||||||
|
|
||||||
|
## 已知遗留
|
||||||
|
|
||||||
|
- Web JS gzip 仍约 211.6 kB,构建保留 Vite 的大 chunk 警告;这是后续代码拆分/动态导入工作,不在本轮视觉重构中处理。
|
||||||
|
- 未连接真实 AstrBot 后端,因此 smoke test 验证的是前端预览态、路由切换和布局,不替代真实 API/插件页数据联调。
|
||||||
|
|
||||||
|
|
||||||
|
## Final execution evidence
|
||||||
|
|
||||||
|
- Browser smoke: 36 checks across 9 views and 4 desktop sizes; all passed with scrollWidth equal to clientWidth.
|
||||||
|
- Frontend UI tests: 7/7 passed.
|
||||||
|
- Contract tests: 25/25 passed.
|
||||||
|
- Typecheck: passed.
|
||||||
|
- Plugin build: passed.
|
||||||
|
- Standalone build: passed.
|
||||||
|
- Generated web/pages artifacts were removed from the working tree after validation.
|
||||||
|
- Live AstrBot plugin-page acceptance is explicitly pending and documented in docs/ui-redesign-integration-validation-2026-07-21.md.
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
# UI Integration Validation
|
||||||
|
|
||||||
|
Date: 2026-07-21
|
||||||
|
Branch: codex/ui-redesign-gallery
|
||||||
|
|
||||||
|
## Local checks
|
||||||
|
|
||||||
|
- Plugin bridge source keeps ready/context handshake, GET/POST request routing, timeout handling, JSON-safe payload cloning, and error unwrapping.
|
||||||
|
- Direct API base remains /api/v1/plugins/extensions/astrbot_plugin_imagestudio.
|
||||||
|
- Plugin-page production build passed.
|
||||||
|
- Standalone-web production build passed.
|
||||||
|
- No local AstrBot host was available on the checked ports; no real bootstrap or signed-media response was claimed.
|
||||||
|
|
||||||
|
## Checked failure paths
|
||||||
|
|
||||||
|
- Direct transport reports network_unreachable when the API is unavailable.
|
||||||
|
- HTML/non-JSON responses are converted to invalid_api_response with a bounded preview.
|
||||||
|
- 401/HTTP failures remain ApiClientError values and are surfaced through the backend connection banner.
|
||||||
|
- Preview mode is explicit and write actions are blocked until a connected backend with write permission is present.
|
||||||
|
- Media URLs use the plugin bridge signing path instead of unauthenticated direct img requests.
|
||||||
|
|
||||||
|
## Required host acceptance
|
||||||
|
|
||||||
|
Run the following in an AstrBot plugin page with a real session:
|
||||||
|
|
||||||
|
1. Load ui/bootstrap, dashboard, profiles, images, jobs, settings, logs.
|
||||||
|
2. Verify signed image preview, refresh, batch selection, retry/cancel, settings save, and log filtering.
|
||||||
|
3. Verify 401, timeout, empty data, partial data, and backend restart recovery.
|
||||||
|
4. Record AstrBot version, ImageStudio plugin version, and screenshots.
|
||||||
|
|
||||||
|
Status: source-level integration is ready; live host acceptance is pending because no AstrBot plugin host is running in this workspace.
|
||||||
|
|
@ -0,0 +1,77 @@
|
||||||
|
# ImageStudio 桌面端 UI 重构方案
|
||||||
|
|
||||||
|
日期:2026-07-21
|
||||||
|
分支:`codex/ui-redesign-gallery`
|
||||||
|
原则:保留业务逻辑、路由查询参数、API 与数据结构;先改一个页面,再扩展共享视觉层。
|
||||||
|
|
||||||
|
## 设计方向
|
||||||
|
|
||||||
|
ImageStudio 是桌面端创作工具,不采用营销网站的 hero、宣传卡片或装饰性动效。视觉方向为“安静的工作台”:冷中性背景、单一主色作为动作/选中/状态强调,内容区保持高对比和稳定密度;圆角、阴影、渐变只服务层级,不作为装饰。
|
||||||
|
|
||||||
|
## P0:先保证安全边界
|
||||||
|
|
||||||
|
本项目当前没有已确认的 P0 UI 阻塞项。P0 阶段只包含保护措施:
|
||||||
|
|
||||||
|
- 保留现有 URL 参数:`view`、`module`、`materialView`、`profile`。
|
||||||
|
- 保留 plugin-page bridge、API endpoint、shared types 和现有事件 emit。
|
||||||
|
- 每批修改前后运行 `npm.cmd run typecheck`、`npm.cmd run build:web`,并运行 `npm.cmd run test:contracts`。
|
||||||
|
- 不删除当前工作树已有的 `GalleryPage.vue` 未提交修改;本分支在其基础上继续。
|
||||||
|
|
||||||
|
## P1:首批桌面端可用性重构
|
||||||
|
|
||||||
|
### P1-01 只重构 Gallery 页面
|
||||||
|
|
||||||
|
目标文件:
|
||||||
|
|
||||||
|
- `frontend/standalone-web/src/features/gallery/GalleryPage.vue`
|
||||||
|
- 必要时复用而不改逻辑:`frontend/standalone-web/src/components/ImagePreviewDialog.vue`、`frontend/standalone-web/src/components/EmptyState.vue`、`frontend/standalone-web/src/components/StateCard.vue`
|
||||||
|
- 契约测试:`frontend/tests/production-data-boundary.test.mjs` 与图库相关测试
|
||||||
|
|
||||||
|
实施内容:
|
||||||
|
|
||||||
|
- 保持 props、emits、筛选值、批量 action、endpoint 调用和预览行为不变。
|
||||||
|
- 重排为稳定的桌面工作区:页面标题/主操作 → 搜索筛选 → 结果区 + inspector;减少重复 surface。
|
||||||
|
- 统一按钮、输入框、筛选 tabs、选中态、禁用态、loading、error、empty 状态。
|
||||||
|
- 让 grid/list 在 1024px–1440px 桌面宽度下优先保持主要内容可读,inspector 只在有选择时占据空间。
|
||||||
|
- 为搜索、批量选择、卡片操作和图片预览补齐可见 focus、名称、Escape/关闭路径检查。
|
||||||
|
- 不新增依赖,不引入营销式动画;保留现有 reduced-motion 规则并覆盖新过渡。
|
||||||
|
|
||||||
|
### P1-02 抽取最小共享视觉 token
|
||||||
|
|
||||||
|
候选文件:
|
||||||
|
|
||||||
|
- 新增 `frontend/standalone-web/src/styles/tokens.css` 或现有入口可接受的等价 token 文件。
|
||||||
|
- 调整 `frontend/standalone-web/src/App.vue` 的全局工作台变量接入 token。
|
||||||
|
|
||||||
|
范围:颜色角色、spacing、radius、border、shadow、focus ring、motion duration、z-index;只抽取已经在现有 UI 中出现的语义,不改变默认主题含义。
|
||||||
|
|
||||||
|
## P2:扩展一致性
|
||||||
|
|
||||||
|
- `frontend/standalone-web/src/components/AppNavigationRail.vue`:统一 active/hover/focus/compact rail,不改变导航 key 或 pin 行为。
|
||||||
|
- `frontend/standalone-web/src/features/profiles/ProfilesPage.vue`、`ProfileMasterPane.vue`、`ProfileDetailPane.vue`、`ProfileWardrobePane.vue`:应用同一 surface、表单和状态矩阵。
|
||||||
|
- `frontend/standalone-web/src/features/materials/AdvancedMaterialImportPage.vue`:统一导入步骤、loading/error/empty 和内容密度。
|
||||||
|
- `frontend/standalone-web/src/features/settings/SettingsPage.vue` 与 settings panels:统一 section、保存/校验/回滚状态。
|
||||||
|
- `frontend/standalone-web/src/features/workflow/*.vue`:只做视觉层和焦点/状态修复,不改变 workflow route、round、branch、review API。
|
||||||
|
- `frontend/standalone-web/src/features/logs/LogsPage.vue` 与 queue/performance 区块:统一状态色、表格/列表密度和窄桌面布局。
|
||||||
|
|
||||||
|
## P2:技术收口
|
||||||
|
|
||||||
|
- 将 `App.vue` 的局部视觉规则迁移到可定位的页面/组件样式,降低后续回归风险;不在第一批做大规模逻辑拆分。
|
||||||
|
- 评估路由页面的动态导入,但只有在不影响 plugin-page bridge 和首屏加载契约时才实施。
|
||||||
|
- 将布局属性过渡替换为 transform/opacity 或明确的 grid track 过渡。
|
||||||
|
- 统一图片 loading/失败/alt 规则,并复核对话框 focus return。
|
||||||
|
|
||||||
|
## 交付顺序与验证门
|
||||||
|
|
||||||
|
1. Gallery 页面视觉与交互状态;通过 typecheck、build:web、contract tests。
|
||||||
|
2. Gallery 桌面窗口验证:1280×800、1440×900、1024×768;检查横向溢出、sticky 区域、键盘焦点和空/错/加载状态。
|
||||||
|
3. 共享 tokens 接入;再次跑同一验证门,并确认 plugin build 不受影响。
|
||||||
|
4. 导航、profiles、materials、settings、workflow、logs/queue 分批推进,每批单独验证。
|
||||||
|
5. 最后一轮执行 Impeccable `polish`:桌面窗口、溢出、状态、可访问性与设计一致性。
|
||||||
|
|
||||||
|
## 明确不做
|
||||||
|
|
||||||
|
- 不重写后端、不改 API endpoint、不迁移数据结构。
|
||||||
|
- 不更换 Vue/Vite/TypeScript 技术栈。
|
||||||
|
- 不引入新的 UI 框架或图标依赖。
|
||||||
|
- 不添加不必要的全屏动画、营销式 hero、装饰性玻璃卡片或渐变文字。
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
# UI State Matrix
|
||||||
|
|
||||||
|
Date: 2026-07-21
|
||||||
|
Branch: codex/ui-redesign-gallery
|
||||||
|
|
||||||
|
## Coverage
|
||||||
|
|
||||||
|
| Area | default | hover | focus | selected | disabled | loading | empty | error | success | disconnected |
|
||||||
|
|---|---|---|---|---|---|---|---|---|---|---|
|
||||||
|
| Navigation rail | yes | yes | yes | aria-current=page | n/a | n/a | n/a | n/a | n/a | yes |
|
||||||
|
| Generate composer | yes | yes | yes | mode button | yes | submit text | preview empty | inline error | result card | write blocked |
|
||||||
|
| Queue | yes | yes | yes | filter/task | action disabled | refresh text | empty state | task error | completed status | read-only |
|
||||||
|
| Gallery | yes | yes | yes | card/batch | batch disabled | media loading | empty state | media fallback | selection feedback | read-only |
|
||||||
|
| Profiles | yes | yes | yes | profile/tab | sealed/read-only | pane loading | empty pane | inline error | saved state | read-only |
|
||||||
|
| Materials | yes | yes | yes | filter/category | permission disabled | operation busy | empty state | action error | operation message | read-only |
|
||||||
|
| Settings | yes | yes | yes | section/tab | permission disabled | save/reload | missing schema | validation error | saved message | read-only |
|
||||||
|
| Logs | yes | yes | yes | filter | refresh disabled | load text | empty state | error state | refreshed state | unavailable |
|
||||||
|
| Workflow | yes | yes | yes | node/candidate | sealed/locked | task progress | candidate empty | node error | adopted state | read-only |
|
||||||
|
|
||||||
|
## Keyboard paths
|
||||||
|
|
||||||
|
- Global search: focus, ArrowUp/ArrowDown, Enter, Escape.
|
||||||
|
- Navigation and tabs: Tab, Enter, Space, aria-current/aria-pressed.
|
||||||
|
- Confirm dialog: Escape, Tab loop, focus return.
|
||||||
|
- Image preview dialog: Escape, Tab loop, focus return, zoom controls.
|
||||||
|
- Backend banner: retry is keyboard reachable and status is aria-live.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
The matrix is backed by shared states in App.vue and feature components. Real backend disconnected states are represented by the existing preview/error/blocked paths; live plugin-host acceptance remains a deployment-bound check.
|
||||||
|
|
@ -65,6 +65,7 @@ class ImageGenerationRequest:
|
||||||
count: int = 1
|
count: int = 1
|
||||||
input_images: tuple[str, ...] = ()
|
input_images: tuple[str, ...] = ()
|
||||||
metadata: dict[str, Any] = field(default_factory=dict)
|
metadata: dict[str, Any] = field(default_factory=dict)
|
||||||
|
timeout_seconds: int | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|
@ -142,7 +143,12 @@ class OpenAIImageProvider:
|
||||||
**self.config.extra_headers,
|
**self.config.extra_headers,
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
response = self._transport(self.config.endpoint_url(), payload, headers, self.config.timeout_seconds)
|
response = self._transport(
|
||||||
|
self.config.endpoint_url(),
|
||||||
|
payload,
|
||||||
|
headers,
|
||||||
|
_generation_request_timeout_seconds(request.timeout_seconds, self.config.timeout_seconds),
|
||||||
|
)
|
||||||
except ImageProviderError as exc:
|
except ImageProviderError as exc:
|
||||||
if exc.provider_id != "unknown":
|
if exc.provider_id != "unknown":
|
||||||
raise
|
raise
|
||||||
|
|
@ -299,6 +305,14 @@ def _post_json(url: str, payload: JsonDict, headers: dict[str, str], timeout_sec
|
||||||
return _parse_json_body(body)
|
return _parse_json_body(body)
|
||||||
|
|
||||||
|
|
||||||
|
def _generation_request_timeout_seconds(value: Any, fallback: Any) -> int:
|
||||||
|
try:
|
||||||
|
timeout = int(value if value is not None else fallback)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
timeout = 180
|
||||||
|
return min(max(timeout, 10), 3600)
|
||||||
|
|
||||||
|
|
||||||
def _parse_json_body(body: str) -> JsonDict:
|
def _parse_json_body(body: str) -> JsonDict:
|
||||||
try:
|
try:
|
||||||
parsed = json.loads(body)
|
parsed = json.loads(body)
|
||||||
|
|
|
||||||
|
|
@ -160,6 +160,7 @@ class SingleFlowEngine:
|
||||||
count=count,
|
count=count,
|
||||||
input_images=_normalize_input_images(request.get("input_images") or request.get("image")),
|
input_images=_normalize_input_images(request.get("input_images") or request.get("image")),
|
||||||
metadata={"task_id": task.task_id, "model_route": model_route},
|
metadata={"task_id": task.task_id, "model_route": model_route},
|
||||||
|
timeout_seconds=_optional_timeout_seconds(request.get("timeout_seconds")),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
assets: list[MockGeneratedAsset] = []
|
assets: list[MockGeneratedAsset] = []
|
||||||
|
|
@ -270,6 +271,34 @@ def _output_uris(
|
||||||
normalized_extension = extension if str(extension).startswith(".") else f".{extension}"
|
normalized_extension = extension if str(extension).startswith(".") else f".{extension}"
|
||||||
scope = request.get("output_scope") if isinstance(request.get("output_scope"), dict) else None
|
scope = request.get("output_scope") if isinstance(request.get("output_scope"), dict) else None
|
||||||
task_stem = _safe_file_stem(task.task_id)
|
task_stem = _safe_file_stem(task.task_id)
|
||||||
|
if scope and scope.get("kind") == "advanced_material_validation":
|
||||||
|
import_id = _safe_file_stem(str(scope.get("import_id") or "import"))
|
||||||
|
attempt_id = _safe_file_stem(str(scope.get("attempt_id") or "attempt"))
|
||||||
|
attempt_number = _safe_file_stem(str(scope.get("attempt_number") or "1"))
|
||||||
|
filename = (
|
||||||
|
f"validation_{attempt_number}__{attempt_id}__{task_stem}_{index + 1:02d}"
|
||||||
|
f"{normalized_extension}"
|
||||||
|
)
|
||||||
|
relative = f"attempts/{import_id}/{attempt_id}/{filename}"
|
||||||
|
thumbnail_relative = f"attempts/{import_id}/{attempt_id}/thumbnail__{filename}"
|
||||||
|
return (
|
||||||
|
f"storage://advanced_materials/{relative}",
|
||||||
|
f"storage://advanced_materials/{thumbnail_relative}",
|
||||||
|
)
|
||||||
|
|
||||||
|
if scope and scope.get("kind") == "advanced_style_validation":
|
||||||
|
import_id = _safe_file_stem(str(scope.get("import_id") or "import"))
|
||||||
|
attempt_id = _safe_file_stem(str(scope.get("attempt_id") or "attempt"))
|
||||||
|
case_id = _safe_file_stem(str(scope.get("case_id") or "case"))
|
||||||
|
case_key = _safe_file_stem(str(scope.get("case_key") or "validation"))
|
||||||
|
filename = f"{case_key}__{case_id}__{task_stem}_{index + 1:02d}{normalized_extension}"
|
||||||
|
relative = f"style-validations/{import_id}/{attempt_id}/{case_id}/{filename}"
|
||||||
|
thumbnail_relative = f"style-validations/{import_id}/{attempt_id}/{case_id}/thumbnail__{filename}"
|
||||||
|
return (
|
||||||
|
f"storage://advanced_materials/{relative}",
|
||||||
|
f"storage://advanced_materials/{thumbnail_relative}",
|
||||||
|
)
|
||||||
|
|
||||||
if not scope or not scope.get("round_id") or not scope.get("candidate_id"):
|
if not scope or not scope.get("round_id") or not scope.get("candidate_id"):
|
||||||
filename = f"{task_stem}_{index + 1}{normalized_extension}"
|
filename = f"{task_stem}_{index + 1}{normalized_extension}"
|
||||||
return (
|
return (
|
||||||
|
|
@ -295,6 +324,26 @@ def _output_uris(
|
||||||
|
|
||||||
def _output_scope_metadata(request: dict[str, Any]) -> dict[str, Any]:
|
def _output_scope_metadata(request: dict[str, Any]) -> dict[str, Any]:
|
||||||
scope = request.get("output_scope") if isinstance(request.get("output_scope"), dict) else None
|
scope = request.get("output_scope") if isinstance(request.get("output_scope"), dict) else None
|
||||||
|
if scope and scope.get("kind") == "advanced_material_validation":
|
||||||
|
allowed = ("kind", "import_id", "attempt_id", "attempt_number")
|
||||||
|
return {
|
||||||
|
"scoped_output": True,
|
||||||
|
"output_scope": {
|
||||||
|
key: str(scope[key])
|
||||||
|
for key in allowed
|
||||||
|
if scope.get(key) is not None and str(scope.get(key)).strip()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if scope and scope.get("kind") == "advanced_style_validation":
|
||||||
|
allowed = ("kind", "import_id", "attempt_id", "case_id", "case_key")
|
||||||
|
return {
|
||||||
|
"scoped_output": True,
|
||||||
|
"output_scope": {
|
||||||
|
key: str(scope[key])
|
||||||
|
for key in allowed
|
||||||
|
if scope.get(key) is not None and str(scope.get(key)).strip()
|
||||||
|
},
|
||||||
|
}
|
||||||
if not scope or not scope.get("round_id") or not scope.get("candidate_id"):
|
if not scope or not scope.get("round_id") or not scope.get("candidate_id"):
|
||||||
return {}
|
return {}
|
||||||
allowed = (
|
allowed = (
|
||||||
|
|
@ -329,6 +378,15 @@ def _normalize_input_images(value: Any) -> tuple[str, ...]:
|
||||||
return (text,) if text else ()
|
return (text,) if text else ()
|
||||||
|
|
||||||
|
|
||||||
|
def _optional_timeout_seconds(value: Any) -> int | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return min(max(int(value), 10), 3600)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _image_bytes(
|
def _image_bytes(
|
||||||
b64_json: str | None,
|
b64_json: str | None,
|
||||||
url: str | None,
|
url: str | None,
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ JsonDict = dict[str, Any]
|
||||||
HttpTransport = Callable[[str, JsonDict, dict[str, str], int], JsonDict]
|
HttpTransport = Callable[[str, JsonDict, dict[str, str], int], JsonDict]
|
||||||
MAX_PROVIDER_JSON_BYTES = 4 * 1024 * 1024
|
MAX_PROVIDER_JSON_BYTES = 4 * 1024 * 1024
|
||||||
MAX_PROVIDER_ERROR_BYTES = 64 * 1024
|
MAX_PROVIDER_ERROR_BYTES = 64 * 1024
|
||||||
|
MAX_VISION_IMAGES = 8
|
||||||
|
|
||||||
|
|
||||||
class VisionProvider(Protocol):
|
class VisionProvider(Protocol):
|
||||||
|
|
@ -52,6 +53,7 @@ class VisionRecognitionRequest:
|
||||||
tags: tuple[str, ...] = ()
|
tags: tuple[str, ...] = ()
|
||||||
model: str | None = None
|
model: str | None = None
|
||||||
metadata: dict[str, Any] = field(default_factory=dict)
|
metadata: dict[str, Any] = field(default_factory=dict)
|
||||||
|
image_uris: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|
@ -98,7 +100,7 @@ class OpenAIVisionProvider:
|
||||||
provider_id=self.provider_id,
|
provider_id=self.provider_id,
|
||||||
error_type="configuration_error",
|
error_type="configuration_error",
|
||||||
)
|
)
|
||||||
if not (_remote_image_url(request.image_uri) or _remote_image_url(request.thumbnail_uri)):
|
if not vision_image_urls(request):
|
||||||
raise VisionProviderError(
|
raise VisionProviderError(
|
||||||
"vision image must be supplied as an HTTP(S) URL or data:image URL",
|
"vision image must be supplied as an HTTP(S) URL or data:image URL",
|
||||||
provider_id=self.provider_id,
|
provider_id=self.provider_id,
|
||||||
|
|
@ -136,6 +138,52 @@ class OpenAIVisionProvider:
|
||||||
return _parse_vision_response(self.provider_id, model, response)
|
return _parse_vision_response(self.provider_id, model, response)
|
||||||
|
|
||||||
|
|
||||||
|
class FallbackVisionProvider:
|
||||||
|
"""Try vision providers in priority order and preserve failure context."""
|
||||||
|
|
||||||
|
def __init__(self, providers: list[VisionProvider]):
|
||||||
|
if not providers:
|
||||||
|
raise ValueError("at least one vision provider is required")
|
||||||
|
self.providers = providers
|
||||||
|
self.provider_id = providers[0].provider_id
|
||||||
|
|
||||||
|
def recognize_material(self, request: VisionRecognitionRequest) -> VisionRecognitionResult:
|
||||||
|
failures: list[dict[str, Any]] = []
|
||||||
|
for provider in self.providers:
|
||||||
|
try:
|
||||||
|
result = provider.recognize_material(request)
|
||||||
|
if failures:
|
||||||
|
return VisionRecognitionResult(
|
||||||
|
provider_id=result.provider_id,
|
||||||
|
model=result.model,
|
||||||
|
prompt=result.prompt,
|
||||||
|
negative_prompt=result.negative_prompt,
|
||||||
|
tags=result.tags,
|
||||||
|
confidence=result.confidence,
|
||||||
|
description=result.description,
|
||||||
|
structured_data=result.structured_data,
|
||||||
|
raw_metadata={**result.raw_metadata, "route_fallback_failures": failures},
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
except VisionProviderError as exc:
|
||||||
|
failures.append(
|
||||||
|
{
|
||||||
|
"provider_id": exc.provider_id,
|
||||||
|
"status_code": exc.status_code,
|
||||||
|
"error_type": exc.error_type,
|
||||||
|
"message": str(exc),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
last = failures[-1]
|
||||||
|
raise VisionProviderError(
|
||||||
|
"all configured vision routes failed",
|
||||||
|
provider_id=str(last["provider_id"]),
|
||||||
|
status_code=last["status_code"],
|
||||||
|
error_type="fallback_exhausted",
|
||||||
|
details={"failures": failures},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class MockVisionProvider:
|
class MockVisionProvider:
|
||||||
provider_id = "mock"
|
provider_id = "mock"
|
||||||
|
|
||||||
|
|
@ -180,12 +228,36 @@ def _user_content(request: VisionRecognitionRequest) -> list[dict[str, Any]]:
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
image_url = _remote_image_url(request.image_uri) or _remote_image_url(request.thumbnail_uri)
|
for image_url in vision_image_urls(request):
|
||||||
if image_url:
|
|
||||||
content.append({"type": "image_url", "image_url": {"url": image_url}})
|
content.append({"type": "image_url", "image_url": {"url": image_url}})
|
||||||
return content
|
return content
|
||||||
|
|
||||||
|
|
||||||
|
def vision_image_urls(request: VisionRecognitionRequest) -> tuple[str, ...]:
|
||||||
|
"""Return ordered, deduplicated multimodal inputs for one vision request.
|
||||||
|
|
||||||
|
``image_uri`` remains the primary-image compatibility field. New callers
|
||||||
|
may add a bounded group through ``image_uris``. The thumbnail preserves
|
||||||
|
the legacy fallback behavior and is used only when no source image is
|
||||||
|
valid, so it never becomes an accidental extra style sample.
|
||||||
|
"""
|
||||||
|
|
||||||
|
resolved: list[str] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for value in (request.image_uri, *request.image_uris):
|
||||||
|
image_url = _remote_image_url(value)
|
||||||
|
if image_url is None or image_url in seen:
|
||||||
|
continue
|
||||||
|
seen.add(image_url)
|
||||||
|
resolved.append(image_url)
|
||||||
|
if len(resolved) >= MAX_VISION_IMAGES:
|
||||||
|
return tuple(resolved)
|
||||||
|
if resolved:
|
||||||
|
return tuple(resolved)
|
||||||
|
thumbnail_url = _remote_image_url(request.thumbnail_uri)
|
||||||
|
return (thumbnail_url,) if thumbnail_url else ()
|
||||||
|
|
||||||
|
|
||||||
def _system_instruction(request: VisionRecognitionRequest) -> str:
|
def _system_instruction(request: VisionRecognitionRequest) -> str:
|
||||||
configured = str(request.metadata.get("recognition_instruction") or "").strip()
|
configured = str(request.metadata.get("recognition_instruction") or "").strip()
|
||||||
fallback = (
|
fallback = (
|
||||||
|
|
|
||||||
5
frontend/package-lock.json
自动生成
5
frontend/package-lock.json
自动生成
|
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "astrbot-plugin-imagestudio-frontend",
|
"name": "astrbot-plugin-imagestudio-frontend",
|
||||||
"version": "1.0.20",
|
"version": "1.0.66",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "astrbot-plugin-imagestudio-frontend",
|
"name": "astrbot-plugin-imagestudio-frontend",
|
||||||
"version": "1.0.20",
|
"version": "1.0.66",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitejs/plugin-vue": "^5.2.0",
|
"@vitejs/plugin-vue": "^5.2.0",
|
||||||
"pinia": "^2.3.0",
|
"pinia": "^2.3.0",
|
||||||
|
|
@ -1531,3 +1531,4 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "astrbot-plugin-imagestudio-frontend",
|
"name": "astrbot-plugin-imagestudio-frontend",
|
||||||
"version": "1.0.20",
|
"version": "1.0.66",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|
@ -10,7 +10,8 @@
|
||||||
"build:web": "vite build --config standalone-web/vite.config.ts",
|
"build:web": "vite build --config standalone-web/vite.config.ts",
|
||||||
"build": "npm run build:plugin && npm run build:web",
|
"build": "npm run build:plugin && npm run build:web",
|
||||||
"typecheck": "vue-tsc --noEmit",
|
"typecheck": "vue-tsc --noEmit",
|
||||||
"test:contracts": "node --test tests/*.test.mjs"
|
"test:contracts": "node --test tests/*.test.mjs",
|
||||||
|
"test:ui": "node --test tests/ui-redesign-smoke.test.mjs tests/ui-theme-contract.test.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitejs/plugin-vue": "^5.2.0",
|
"@vitejs/plugin-vue": "^5.2.0",
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
|
import { LONG_TASK_TIMEOUT_MS } from "../config/timeouts"
|
||||||
|
|
||||||
const CHANNEL = "astrbot-plugin-page"
|
const CHANNEL = "astrbot-plugin-page"
|
||||||
const READY_RETRY_MS = 250
|
const READY_RETRY_MS = 250
|
||||||
const DEFAULT_REQUEST_TIMEOUT_MS = 30000
|
const DEFAULT_REQUEST_TIMEOUT_MS = 30000
|
||||||
const LONG_TASK_REQUEST_TIMEOUT_MS = 300000
|
|
||||||
const LONG_TASK_ENDPOINT = /(?:^|\/)(?:generate|retry|review|execute-character|expand|governance-preview|probe-provider|probe-model|recognize|re-recognize|renormalize|renormalize-batch|import-pack|migrate|restore)(?:\/|$)/
|
const LONG_TASK_ENDPOINT = /(?:^|\/)(?:generate|retry|review|execute-character|expand|governance-preview|probe-provider|probe-model|recognize|re-recognize|renormalize|renormalize-batch|import-pack|migrate|restore)(?:\/|$)/
|
||||||
|
|
||||||
type PendingRequest = {
|
type PendingRequest = {
|
||||||
|
|
@ -87,7 +88,7 @@ export function installAstrBotPluginPageBridge() {
|
||||||
const cloneablePayload = toPostMessagePayload(payload)
|
const cloneablePayload = toPostMessagePayload(payload)
|
||||||
return new Promise<T>((resolve, reject) => {
|
return new Promise<T>((resolve, reject) => {
|
||||||
const timeoutMs = action === "api:post" && LONG_TASK_ENDPOINT.test(endpoint)
|
const timeoutMs = action === "api:post" && LONG_TASK_ENDPOINT.test(endpoint)
|
||||||
? LONG_TASK_REQUEST_TIMEOUT_MS
|
? LONG_TASK_TIMEOUT_MS
|
||||||
: DEFAULT_REQUEST_TIMEOUT_MS
|
: DEFAULT_REQUEST_TIMEOUT_MS
|
||||||
const timer = window.setTimeout(() => {
|
const timer = window.setTimeout(() => {
|
||||||
pending.delete(requestId)
|
pending.delete(requestId)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { API_BASE } from "./endpoints"
|
import { API_BASE } from "./endpoints"
|
||||||
|
import { LONG_TASK_TIMEOUT_MS } from "../config/timeouts"
|
||||||
import type { ApiResponse, AstrBotApiResponse } from "../types/api"
|
import type { ApiResponse, AstrBotApiResponse } from "../types/api"
|
||||||
|
|
||||||
export type ApiTransport = "plugin-bridge" | "direct-fetch"
|
export type ApiTransport = "plugin-bridge" | "direct-fetch"
|
||||||
|
|
@ -10,7 +11,6 @@ const PLUGIN_BRIDGE_DISCOVERY_TIMEOUT_MS = 2500
|
||||||
const PLUGIN_BRIDGE_READY_TIMEOUT_MS = 1200
|
const PLUGIN_BRIDGE_READY_TIMEOUT_MS = 1200
|
||||||
const PLUGIN_BRIDGE_GET_TIMEOUT_MS = 15000
|
const PLUGIN_BRIDGE_GET_TIMEOUT_MS = 15000
|
||||||
const PLUGIN_BRIDGE_POST_TIMEOUT_MS = 30000
|
const PLUGIN_BRIDGE_POST_TIMEOUT_MS = 30000
|
||||||
const PLUGIN_BRIDGE_LONG_TASK_TIMEOUT_MS = 300000
|
|
||||||
const LONG_TASK_ENDPOINT = /(?:^|\/)(?:generate|retry|review|execute-character|expand|governance-preview|probe-provider|probe-model|recognize|re-recognize|renormalize|renormalize-batch|import-pack|migrate|restore)(?:\/|$)/
|
const LONG_TASK_ENDPOINT = /(?:^|\/)(?:generate|retry|review|execute-character|expand|governance-preview|probe-provider|probe-model|recognize|re-recognize|renormalize|renormalize-batch|import-pack|migrate|restore)(?:\/|$)/
|
||||||
|
|
||||||
type PluginBridge = NonNullable<Window["AstrBotPluginPage"]>
|
type PluginBridge = NonNullable<Window["AstrBotPluginPage"]>
|
||||||
|
|
@ -167,7 +167,7 @@ async function requestViaPluginBridge<T>(
|
||||||
|
|
||||||
function pluginBridgePostTimeout(endpoint: string) {
|
function pluginBridgePostTimeout(endpoint: string) {
|
||||||
return LONG_TASK_ENDPOINT.test(endpoint)
|
return LONG_TASK_ENDPOINT.test(endpoint)
|
||||||
? PLUGIN_BRIDGE_LONG_TASK_TIMEOUT_MS
|
? LONG_TASK_TIMEOUT_MS
|
||||||
: PLUGIN_BRIDGE_POST_TIMEOUT_MS
|
: PLUGIN_BRIDGE_POST_TIMEOUT_MS
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,7 @@ export const endpoints = {
|
||||||
jobDelete: (taskId: string) => `jobs/${taskId}`,
|
jobDelete: (taskId: string) => `jobs/${taskId}`,
|
||||||
jobCancel: (taskId: string) => `jobs/${taskId}/cancel`,
|
jobCancel: (taskId: string) => `jobs/${taskId}/cancel`,
|
||||||
jobRetry: (taskId: string) => `jobs/${taskId}/retry`,
|
jobRetry: (taskId: string) => `jobs/${taskId}/retry`,
|
||||||
|
jobRetryFailed: "jobs/failed/retry",
|
||||||
jobClearFailed: "jobs/failed/clear",
|
jobClearFailed: "jobs/failed/clear",
|
||||||
jobClearTerminal: "jobs/terminal/clear",
|
jobClearTerminal: "jobs/terminal/clear",
|
||||||
jobDeadLetterRetry: "jobs/dead-letter/retry",
|
jobDeadLetterRetry: "jobs/dead-letter/retry",
|
||||||
|
|
@ -98,6 +99,29 @@ export const endpoints = {
|
||||||
materialRecognize: (materialId: string) => `materials/${materialId}/recognize`,
|
materialRecognize: (materialId: string) => `materials/${materialId}/recognize`,
|
||||||
materialReRecognize: (materialId: string) => `materials/${materialId}/re-recognize`,
|
materialReRecognize: (materialId: string) => `materials/${materialId}/re-recognize`,
|
||||||
materialConfirm: (materialId: string) => `materials/${materialId}/confirm`,
|
materialConfirm: (materialId: string) => `materials/${materialId}/confirm`,
|
||||||
|
advancedMaterialImports: "advanced-material-imports",
|
||||||
|
advancedMaterialImportUpload: "advanced-material-imports/upload",
|
||||||
|
advancedMaterialStyleSetUpload: "advanced-material-imports/style-set/upload",
|
||||||
|
advancedMaterialImport: (importId: string) => `advanced-material-imports/${importId}`,
|
||||||
|
advancedMaterialImportDelete: (importId: string) => `advanced-material-imports/${importId}`,
|
||||||
|
advancedMaterialImportRetry: (importId: string) => `advanced-material-imports/${importId}/retry`,
|
||||||
|
advancedMaterialStyleSourceRetry: (importId: string, sourceId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/style-sources/${sourceId}/retry`,
|
||||||
|
advancedMaterialStyleSourceExclude: (importId: string, sourceId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/style-sources/${sourceId}/exclude`,
|
||||||
|
advancedMaterialStyleConsensus: (importId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/style-consensus`,
|
||||||
|
advancedMaterialStyleValidationCaseRetry: (importId: string, caseId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/style-validation-cases/${caseId}/retry`,
|
||||||
|
advancedMaterialValidationAttempts: (importId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/validation-attempts`,
|
||||||
|
advancedMaterialAttemptAccept: (importId: string, attemptId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/attempts/${attemptId}/accept`,
|
||||||
|
advancedMaterialAttemptReject: (importId: string, attemptId: string) =>
|
||||||
|
`advanced-material-imports/${importId}/attempts/${attemptId}/reject`,
|
||||||
|
advancedMaterials: "advanced-materials",
|
||||||
|
advancedMaterial: (materialId: string) => `advanced-materials/${materialId}`,
|
||||||
|
materialCatalog: "material-catalog",
|
||||||
assetImportPack: "assets/import-pack",
|
assetImportPack: "assets/import-pack",
|
||||||
wardrobe: (profileId: string) => `profiles/${profileId}/wardrobe`,
|
wardrobe: (profileId: string) => `profiles/${profileId}/wardrobe`,
|
||||||
wardrobeImportMaterial: (profileId: string) => `profiles/${profileId}/wardrobe/import-material`,
|
wardrobeImportMaterial: (profileId: string) => `profiles/${profileId}/wardrobe/import-material`,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
export const LONG_TASK_TIMEOUT_SECONDS = 900
|
||||||
|
export const LONG_TASK_TIMEOUT_MS = LONG_TASK_TIMEOUT_SECONDS * 1000
|
||||||
|
|
@ -0,0 +1,354 @@
|
||||||
|
export type AdvancedMaterialImportStatus =
|
||||||
|
| "recognition_queued"
|
||||||
|
| "pending_recognition"
|
||||||
|
| "recognizing"
|
||||||
|
| "pending_validation"
|
||||||
|
| "ready_for_validation"
|
||||||
|
| "validation_queued"
|
||||||
|
| "validating"
|
||||||
|
| "validation_failed"
|
||||||
|
| "recognition_failed"
|
||||||
|
| "pending_review"
|
||||||
|
| "awaiting_review"
|
||||||
|
| "adjustment_required"
|
||||||
|
| "accepted"
|
||||||
|
| "rejected"
|
||||||
|
| "failed"
|
||||||
|
| "cancelled"
|
||||||
|
| "archived"
|
||||||
|
|
||||||
|
export type AdvancedMaterialValidationAttemptStatus =
|
||||||
|
| "queued"
|
||||||
|
| "running"
|
||||||
|
| "succeeded"
|
||||||
|
| "completed"
|
||||||
|
| "awaiting_review"
|
||||||
|
| "failed"
|
||||||
|
| "accepted"
|
||||||
|
| "rejected"
|
||||||
|
| "cancelled"
|
||||||
|
|
||||||
|
export type AdvancedMaterialStatus = "active" | "archived"
|
||||||
|
|
||||||
|
export type AdvancedStyleSourceStatus =
|
||||||
|
| "uploaded"
|
||||||
|
| "recognition_queued"
|
||||||
|
| "recognizing"
|
||||||
|
| "recognized"
|
||||||
|
| "completed"
|
||||||
|
| "failed"
|
||||||
|
| "excluded"
|
||||||
|
| "cancelled"
|
||||||
|
|
||||||
|
export type AdvancedStyleConsensusStatus =
|
||||||
|
| "queued"
|
||||||
|
| "running"
|
||||||
|
| "completed"
|
||||||
|
| "failed"
|
||||||
|
|
||||||
|
export type AdvancedStyleValidationScenario = "portrait" | "fullbody" | "novel_scene" | string
|
||||||
|
|
||||||
|
export interface AdvancedMaterialError {
|
||||||
|
code?: string
|
||||||
|
message?: string
|
||||||
|
details?: Record<string, unknown>
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleSource {
|
||||||
|
source_id: string
|
||||||
|
import_id?: string
|
||||||
|
sort_order: number
|
||||||
|
is_primary: boolean
|
||||||
|
excluded: boolean
|
||||||
|
status: AdvancedStyleSourceStatus | string
|
||||||
|
filename?: string | null
|
||||||
|
source_image_uri?: string | null
|
||||||
|
source_thumbnail_uri?: string | null
|
||||||
|
source_image_url?: string | null
|
||||||
|
source_thumbnail_url?: string | null
|
||||||
|
image_uri?: string | null
|
||||||
|
thumbnail_uri?: string | null
|
||||||
|
image_url?: string | null
|
||||||
|
thumbnail_url?: string | null
|
||||||
|
task_id?: string | null
|
||||||
|
recognition_prompt?: string | null
|
||||||
|
recognition_negative_prompt?: string | null
|
||||||
|
recognition_tags: string[]
|
||||||
|
recognition_result: Record<string, unknown>
|
||||||
|
retry_count?: number
|
||||||
|
error: AdvancedMaterialError
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
created_at?: string
|
||||||
|
updated_at?: string
|
||||||
|
completed_at?: string | null
|
||||||
|
excluded_at?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleConsensusFeature {
|
||||||
|
trait?: string
|
||||||
|
label?: string
|
||||||
|
description?: string
|
||||||
|
supporting_source_ids?: string[]
|
||||||
|
supporting_images?: string[]
|
||||||
|
support_ratio?: number
|
||||||
|
confidence?: number
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleConsensus {
|
||||||
|
consensus_id?: string | null
|
||||||
|
version_id?: string | null
|
||||||
|
revision?: number | null
|
||||||
|
version_number?: number | null
|
||||||
|
status: AdvancedStyleConsensusStatus | string
|
||||||
|
consensus_style: AdvancedStyleConsensusFeature[] | Record<string, unknown>
|
||||||
|
variable_style_features: AdvancedStyleConsensusFeature[]
|
||||||
|
source_content_features: AdvancedStyleConsensusFeature[] | string[]
|
||||||
|
content_leakage_exclusions: string[]
|
||||||
|
outlier_source_ids: string[]
|
||||||
|
representative_source_ids: string[]
|
||||||
|
consensus_confidence?: number | null
|
||||||
|
generation_capsules: Record<string, unknown>
|
||||||
|
source_ids?: string[]
|
||||||
|
tags?: string[]
|
||||||
|
result?: Record<string, unknown>
|
||||||
|
prompt?: string | null
|
||||||
|
negative_prompt?: string | null
|
||||||
|
task_id?: string | null
|
||||||
|
error: AdvancedMaterialError
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
created_at?: string
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleValidationCase {
|
||||||
|
case_id: string
|
||||||
|
import_id?: string
|
||||||
|
attempt_id?: string | null
|
||||||
|
scenario: AdvancedStyleValidationScenario
|
||||||
|
case_key?: string
|
||||||
|
sort_order?: number
|
||||||
|
title?: string | null
|
||||||
|
status: AdvancedMaterialValidationAttemptStatus | string
|
||||||
|
content_prompt?: string | null
|
||||||
|
style_prompt?: string | null
|
||||||
|
final_prompt?: string | null
|
||||||
|
negative_prompt?: string | null
|
||||||
|
validation_image_uri?: string | null
|
||||||
|
validation_thumbnail_uri?: string | null
|
||||||
|
validation_image_url?: string | null
|
||||||
|
validation_thumbnail_url?: string | null
|
||||||
|
task_id?: string | null
|
||||||
|
provider_id?: string | null
|
||||||
|
provider_model?: string | null
|
||||||
|
model_route?: string | null
|
||||||
|
seed?: number | null
|
||||||
|
input_image_count?: number
|
||||||
|
style_scores: Record<string, unknown>
|
||||||
|
style_review?: Record<string, unknown>
|
||||||
|
rendering_layers?: Record<string, number>
|
||||||
|
content_novelty: Record<string, unknown>
|
||||||
|
usage?: Record<string, unknown>
|
||||||
|
fidelity_score?: number | null
|
||||||
|
error: AdvancedMaterialError
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
created_at?: string
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialImport {
|
||||||
|
import_id: string
|
||||||
|
category_id?: string | null
|
||||||
|
display_name: string
|
||||||
|
source_image_uri?: string | null
|
||||||
|
source_thumbnail_uri?: string | null
|
||||||
|
source_image_url?: string | null
|
||||||
|
source_thumbnail_url?: string | null
|
||||||
|
status: AdvancedMaterialImportStatus | string
|
||||||
|
recognition_prompt?: string | null
|
||||||
|
recognition_negative_prompt?: string | null
|
||||||
|
recognition_tags: string[]
|
||||||
|
recognition_result: Record<string, unknown>
|
||||||
|
recognition_model_route?: string | null
|
||||||
|
prompt_revision?: number | null
|
||||||
|
current_attempt_id?: string | null
|
||||||
|
accepted_material_id?: string | null
|
||||||
|
task_id?: string | null
|
||||||
|
workflow_kind?: "single" | "style_set" | string
|
||||||
|
sources?: AdvancedStyleSource[]
|
||||||
|
consensus?: AdvancedStyleConsensus | null
|
||||||
|
validation_cases?: AdvancedStyleValidationCase[]
|
||||||
|
error: AdvancedMaterialError
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
created_by?: string | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialValidationAttempt {
|
||||||
|
attempt_id: string
|
||||||
|
import_id: string
|
||||||
|
attempt_number: number
|
||||||
|
status: AdvancedMaterialValidationAttemptStatus | string
|
||||||
|
adjustment_text?: string | null
|
||||||
|
prompt?: string | null
|
||||||
|
negative_prompt?: string | null
|
||||||
|
model_route?: string | null
|
||||||
|
provider_id?: string | null
|
||||||
|
provider_model?: string | null
|
||||||
|
task_id?: string | null
|
||||||
|
validation_image_uri?: string | null
|
||||||
|
validation_thumbnail_uri?: string | null
|
||||||
|
validation_image_url?: string | null
|
||||||
|
validation_thumbnail_url?: string | null
|
||||||
|
seed?: number | null
|
||||||
|
width?: number | null
|
||||||
|
height?: number | null
|
||||||
|
usage: Record<string, unknown>
|
||||||
|
fidelity_score?: number | null
|
||||||
|
decision?: string | null
|
||||||
|
decision_notes?: string | null
|
||||||
|
error: AdvancedMaterialError
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
validation_mode?: "single" | "style_cross_scene" | string
|
||||||
|
validation_cases?: AdvancedStyleValidationCase[]
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
completed_at?: string | null
|
||||||
|
decided_at?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterial {
|
||||||
|
material_id: string
|
||||||
|
import_id: string
|
||||||
|
accepted_attempt_id: string
|
||||||
|
category_id?: string | null
|
||||||
|
display_name: string
|
||||||
|
source_image_uri?: string | null
|
||||||
|
source_thumbnail_uri?: string | null
|
||||||
|
source_image_url?: string | null
|
||||||
|
source_thumbnail_url?: string | null
|
||||||
|
validation_image_uri?: string | null
|
||||||
|
validation_thumbnail_uri?: string | null
|
||||||
|
validation_image_url?: string | null
|
||||||
|
validation_thumbnail_url?: string | null
|
||||||
|
prompt?: string | null
|
||||||
|
negative_prompt?: string | null
|
||||||
|
tags: string[]
|
||||||
|
priority: number
|
||||||
|
status: AdvancedMaterialStatus | string
|
||||||
|
capsule: Record<string, unknown>
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
accepted_at?: string | null
|
||||||
|
archived_at?: string | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialImportListResult {
|
||||||
|
items: AdvancedMaterialImport[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
page_size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialValidationAttemptListResult {
|
||||||
|
items: AdvancedMaterialValidationAttempt[]
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialListResult {
|
||||||
|
items: AdvancedMaterial[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
page_size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MaterialCatalogEntry {
|
||||||
|
material_id: string
|
||||||
|
material_type?: "advanced" | "standard" | string
|
||||||
|
library_kind?: "advanced" | "standard" | string
|
||||||
|
display_name: string
|
||||||
|
category_id?: string | null
|
||||||
|
image_uri?: string | null
|
||||||
|
image_url?: string | null
|
||||||
|
thumbnail_uri?: string | null
|
||||||
|
thumbnail_url?: string | null
|
||||||
|
prompt?: string | null
|
||||||
|
negative_prompt?: string | null
|
||||||
|
tags: string[]
|
||||||
|
priority?: number
|
||||||
|
status: string
|
||||||
|
recognition_status?: string
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
created_at?: string
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MaterialCatalogResult {
|
||||||
|
items: MaterialCatalogEntry[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
page_size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialUploadRequest {
|
||||||
|
image_data_url: string
|
||||||
|
display_name: string
|
||||||
|
category_id: string
|
||||||
|
filename: string
|
||||||
|
content_type?: string
|
||||||
|
size_bytes: number
|
||||||
|
upload_source: "file" | "paste" | "drop"
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialUploadResult {
|
||||||
|
import: AdvancedMaterialImport
|
||||||
|
task?: Record<string, unknown> | null
|
||||||
|
task_id?: string | null
|
||||||
|
queued?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleSetUploadImage {
|
||||||
|
client_source_id?: string
|
||||||
|
image_data_url: string
|
||||||
|
filename: string
|
||||||
|
content_type?: string
|
||||||
|
size_bytes: number
|
||||||
|
upload_source: "file" | "paste" | "drop"
|
||||||
|
sort_order: number
|
||||||
|
is_primary: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleSetUploadRequest {
|
||||||
|
display_name: string
|
||||||
|
category_id: string
|
||||||
|
images: AdvancedStyleSetUploadImage[]
|
||||||
|
metadata: Record<string, unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialValidationAttemptRequest {
|
||||||
|
adjustment_text?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedMaterialDecisionRequest {
|
||||||
|
adjustment_text?: string
|
||||||
|
style_adjustment_text?: string
|
||||||
|
validation_instruction?: string
|
||||||
|
reuse_validation_scenarios?: boolean
|
||||||
|
decision_notes?: string
|
||||||
|
fidelity_score?: number
|
||||||
|
validation_reference_enabled?: boolean
|
||||||
|
validation_reference_source_id?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedStyleConsensusRequest {
|
||||||
|
analysis_strategy?: "text_only" | "vision_assisted"
|
||||||
|
included_source_ids?: string[]
|
||||||
|
validation_reference_enabled?: boolean
|
||||||
|
validation_reference_source_id?: string
|
||||||
|
style_adjustment_text?: string
|
||||||
|
validation_instruction?: string
|
||||||
|
}
|
||||||
|
|
@ -11,6 +11,7 @@ export interface WardrobeItem {
|
||||||
last_used_at?: string | null
|
last_used_at?: string | null
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
|
library_kind?: "standard" | "advanced" | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WardrobeMatchResult {
|
export interface WardrobeMatchResult {
|
||||||
|
|
@ -26,6 +27,7 @@ export interface WardrobeMatchResult {
|
||||||
style?: string | null
|
style?: string | null
|
||||||
is_favorite: boolean
|
is_favorite: boolean
|
||||||
usage_count: number
|
usage_count: number
|
||||||
|
library_kind?: "standard" | "advanced" | string
|
||||||
score: number
|
score: number
|
||||||
score_breakdown: Record<string, number>
|
score_breakdown: Record<string, number>
|
||||||
}>
|
}>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
import type { CostUsageSummary } from "../types/cost"
|
import type { CostUsageSummary } from "../types/cost"
|
||||||
import type { GenerationJob } from "../types/job"
|
import type { GenerationJob } from "../types/job"
|
||||||
|
|
||||||
|
const BACKEND_NAIVE_UTC_TIMESTAMP = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/
|
||||||
|
const TERMINAL_JOB_STATUSES = new Set(["completed", "succeeded", "failed", "cancelled", "dead_letter", "superseded"])
|
||||||
|
|
||||||
export function normalizeStatus(status: string): string {
|
export function normalizeStatus(status: string): string {
|
||||||
return String(status || "").trim().toLowerCase()
|
return String(status || "").trim().toLowerCase()
|
||||||
}
|
}
|
||||||
|
|
@ -58,7 +61,9 @@ export function formatCostEstimate(summary: CostUsageSummary): string {
|
||||||
|
|
||||||
export function formatTime(value?: string): string {
|
export function formatTime(value?: string): string {
|
||||||
if (!value) return "-"
|
if (!value) return "-"
|
||||||
const date = new Date(value)
|
const parsed = timestamp(value)
|
||||||
|
if (!parsed) return value
|
||||||
|
const date = new Date(parsed)
|
||||||
if (Number.isNaN(date.getTime())) return value
|
if (Number.isNaN(date.getTime())) return value
|
||||||
return new Intl.DateTimeFormat("zh-CN", {
|
return new Intl.DateTimeFormat("zh-CN", {
|
||||||
month: "2-digit",
|
month: "2-digit",
|
||||||
|
|
@ -69,17 +74,43 @@ export function formatTime(value?: string): string {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function timestamp(value: string): number {
|
export function timestamp(value: string): number {
|
||||||
const parsed = Date.parse(value)
|
const text = String(value || "").trim()
|
||||||
|
const normalized = BACKEND_NAIVE_UTC_TIMESTAMP.test(text)
|
||||||
|
? `${text.replace(" ", "T")}Z`
|
||||||
|
: text
|
||||||
|
const parsed = Date.parse(normalized)
|
||||||
return Number.isFinite(parsed) ? parsed : 0
|
return Number.isFinite(parsed) ? parsed : 0
|
||||||
}
|
}
|
||||||
|
|
||||||
export function waitTime(job: GenerationJob): string {
|
export function waitTime(job: GenerationJob): string {
|
||||||
const start = timestamp(job.created_at)
|
const start = timestamp(job.created_at)
|
||||||
if (!start) return "-"
|
if (!start) return "-"
|
||||||
const minutes = Math.max(0, Math.round((Date.now() - start) / 60000))
|
const status = normalizeStatus(job.status)
|
||||||
if (minutes < 1) return "刚刚"
|
const terminal = TERMINAL_JOB_STATUSES.has(status)
|
||||||
|
const persistedEnd = terminal ? timestamp(job.updated_at) : 0
|
||||||
|
const elapsedSeconds = Math.max(0, Math.round(((persistedEnd || Date.now()) - start) / 1000))
|
||||||
|
const elapsed = formatDurationSeconds(elapsedSeconds)
|
||||||
|
const timeout = jobTimeoutSeconds(job)
|
||||||
|
return timeout ? `${elapsed} / 上限 ${formatDurationSeconds(timeout)}` : elapsed
|
||||||
|
}
|
||||||
|
|
||||||
|
export function jobTimeoutSeconds(job: GenerationJob): number | undefined {
|
||||||
|
const requestValue = job.request?.timeout_seconds
|
||||||
|
const metadataValue = job.metadata?.timeout_seconds
|
||||||
|
const value = requestValue ?? metadataValue
|
||||||
|
const timeout = Number(value)
|
||||||
|
if (!Number.isFinite(timeout) || timeout <= 0) return undefined
|
||||||
|
return Math.round(timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDurationSeconds(value: number): string {
|
||||||
|
const seconds = Math.max(0, Math.round(value))
|
||||||
|
if (seconds < 60) return seconds < 1 ? "刚刚" : `${seconds} 秒`
|
||||||
|
const minutes = Math.round(seconds / 60)
|
||||||
if (minutes < 60) return `${minutes} 分钟`
|
if (minutes < 60) return `${minutes} 分钟`
|
||||||
return `${Math.round(minutes / 60)} 小时`
|
const hours = Math.floor(minutes / 60)
|
||||||
|
const remainder = minutes % 60
|
||||||
|
return remainder ? `${hours} 小时 ${remainder} 分钟` : `${hours} 小时`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function shortId(value: string): string {
|
export function shortId(value: string): string {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
|
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
|
||||||
|
import "./styles/tokens.css"
|
||||||
|
import "./styles/workbench.css"
|
||||||
import AppNavigationRail from "./components/AppNavigationRail.vue"
|
import AppNavigationRail from "./components/AppNavigationRail.vue"
|
||||||
import ConfirmDialog from "./components/ConfirmDialog.vue"
|
import ConfirmDialog from "./components/ConfirmDialog.vue"
|
||||||
import EmptyState from "./components/EmptyState.vue"
|
import EmptyState from "./components/EmptyState.vue"
|
||||||
|
|
@ -10,17 +12,22 @@ import MaterialOperationDialog from "./components/MaterialOperationDialog.vue"
|
||||||
import { MATERIAL_BODY_SLOT_OPTIONS } from "./material-labels"
|
import { MATERIAL_BODY_SLOT_OPTIONS } from "./material-labels"
|
||||||
import MetricCardGrid from "./components/MetricCardGrid.vue"
|
import MetricCardGrid from "./components/MetricCardGrid.vue"
|
||||||
import StateCard from "./components/StateCard.vue"
|
import StateCard from "./components/StateCard.vue"
|
||||||
import GalleryPage from "./features/gallery/GalleryPage.vue"
|
const AdvancedMaterialImportPage = defineAsyncComponent(() => import("./features/materials/AdvancedMaterialImportPage.vue"))
|
||||||
|
import {
|
||||||
|
parseMaterialLibraryView,
|
||||||
|
type MaterialLibraryView,
|
||||||
|
} from "./features/materials/advanced-material-state"
|
||||||
|
const GalleryPage = defineAsyncComponent(() => import("./features/gallery/GalleryPage.vue"))
|
||||||
import type { GalleryImage } from "./features/gallery/types"
|
import type { GalleryImage } from "./features/gallery/types"
|
||||||
import LogsPage from "./features/logs/LogsPage.vue"
|
const LogsPage = defineAsyncComponent(() => import("./features/logs/LogsPage.vue"))
|
||||||
import { navItems, visibleNavItems } from "./features/navigation/navigation-config"
|
import { navItems, visibleNavItems } from "./features/navigation/navigation-config"
|
||||||
import {
|
import {
|
||||||
profileGenerationKind,
|
profileGenerationKind,
|
||||||
type ProfileGenerationKind,
|
type ProfileGenerationKind,
|
||||||
} from "./features/profiles/profile-ui"
|
} from "./features/profiles/profile-ui"
|
||||||
import ProfilesPage from "./features/profiles/ProfilesPage.vue"
|
const ProfilesPage = defineAsyncComponent(() => import("./features/profiles/ProfilesPage.vue"))
|
||||||
import type { ProfileImageTarget } from "./features/profiles/types"
|
import type { ProfileImageTarget } from "./features/profiles/types"
|
||||||
import SettingsPage from "./features/settings/SettingsPage.vue"
|
const SettingsPage = defineAsyncComponent(() => import("./features/settings/SettingsPage.vue"))
|
||||||
import {
|
import {
|
||||||
cleanImportedProfileValue,
|
cleanImportedProfileValue,
|
||||||
createDefaultQuickProfileQuestionnaire,
|
createDefaultQuickProfileQuestionnaire,
|
||||||
|
|
@ -29,14 +36,14 @@ import {
|
||||||
type ExternalProfileImportDraft,
|
type ExternalProfileImportDraft,
|
||||||
type QuickProfileQuestionnaire,
|
type QuickProfileQuestionnaire,
|
||||||
} from "./features/quick-profile/profile-import"
|
} from "./features/quick-profile/profile-import"
|
||||||
import WorkflowCompareDialog from "./features/workflow/WorkflowCompareDialog.vue"
|
const WorkflowCompareDialog = defineAsyncComponent(() => import("./features/workflow/WorkflowCompareDialog.vue"))
|
||||||
import WorkflowBranchPanel from "./features/workflow/WorkflowBranchPanel.vue"
|
const WorkflowBranchPanel = defineAsyncComponent(() => import("./features/workflow/WorkflowBranchPanel.vue"))
|
||||||
import WorkflowCandidatePool from "./features/workflow/WorkflowCandidatePool.vue"
|
const WorkflowCandidatePool = defineAsyncComponent(() => import("./features/workflow/WorkflowCandidatePool.vue"))
|
||||||
import WorkflowComposer from "./features/workflow/WorkflowComposer.vue"
|
const WorkflowComposer = defineAsyncComponent(() => import("./features/workflow/WorkflowComposer.vue"))
|
||||||
import WorkflowDependencyContextCard from "./features/workflow/WorkflowDependencyContextCard.vue"
|
const WorkflowDependencyContextCard = defineAsyncComponent(() => import("./features/workflow/WorkflowDependencyContextCard.vue"))
|
||||||
import WorkflowGenerationReviewDialog from "./features/workflow/WorkflowGenerationReviewDialog.vue"
|
const WorkflowGenerationReviewDialog = defineAsyncComponent(() => import("./features/workflow/WorkflowGenerationReviewDialog.vue"))
|
||||||
import WorkflowMaterialDrawer from "./features/workflow/WorkflowMaterialDrawer.vue"
|
const WorkflowMaterialDrawer = defineAsyncComponent(() => import("./features/workflow/WorkflowMaterialDrawer.vue"))
|
||||||
import WorkflowRoundPanel from "./features/workflow/WorkflowRoundPanel.vue"
|
const WorkflowRoundPanel = defineAsyncComponent(() => import("./features/workflow/WorkflowRoundPanel.vue"))
|
||||||
import {
|
import {
|
||||||
CHARACTER_WORKFLOW_PREVIEW_NODE_SPECS,
|
CHARACTER_WORKFLOW_PREVIEW_NODE_SPECS,
|
||||||
canonicalCharacterWorkflowNodeKey,
|
canonicalCharacterWorkflowNodeKey,
|
||||||
|
|
@ -125,6 +132,7 @@ import type {
|
||||||
WorkflowNodeMaterialBindingsSaveRequest,
|
WorkflowNodeMaterialBindingsSaveRequest,
|
||||||
} from "../../shared/types/workflow-material"
|
} from "../../shared/types/workflow-material"
|
||||||
import type { WardrobeItem } from "../../shared/types/wardrobe"
|
import type { WardrobeItem } from "../../shared/types/wardrobe"
|
||||||
|
import type { MaterialCatalogEntry } from "../../shared/types/advanced-material"
|
||||||
import type { UiActionCard, UiDetailRow, UiMetricCard } from "../../shared/types/ui"
|
import type { UiActionCard, UiDetailRow, UiMetricCard } from "../../shared/types/ui"
|
||||||
import { uniqueBy, uniqueStrings } from "../../shared/utils/collections"
|
import { uniqueBy, uniqueStrings } from "../../shared/utils/collections"
|
||||||
import {
|
import {
|
||||||
|
|
@ -377,6 +385,8 @@ interface QuickProfileMaterialOption {
|
||||||
colors: [string, string, string]
|
colors: [string, string, string]
|
||||||
imageUrl?: string
|
imageUrl?: string
|
||||||
source?: "backend"
|
source?: "backend"
|
||||||
|
advanced?: boolean
|
||||||
|
priority?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
interface QuickProfileMaterialCategorySpec {
|
interface QuickProfileMaterialCategorySpec {
|
||||||
|
|
@ -650,6 +660,7 @@ const capabilityProfiles = ref<CapabilityProfile[]>([])
|
||||||
const runtimeModelOptions = ref<RuntimeModelOption[]>([])
|
const runtimeModelOptions = ref<RuntimeModelOption[]>([])
|
||||||
const materialCategories = ref<MaterialCategory[]>([])
|
const materialCategories = ref<MaterialCategory[]>([])
|
||||||
const materials = ref<MaterialListResult | null>(null)
|
const materials = ref<MaterialListResult | null>(null)
|
||||||
|
const materialCatalog = ref<MaterialCatalogEntry[]>([])
|
||||||
const profileWardrobeItemsByProfileId = ref<Record<string, WardrobeItem[]>>({})
|
const profileWardrobeItemsByProfileId = ref<Record<string, WardrobeItem[]>>({})
|
||||||
const profileWardrobeErrorsByProfileId = ref<Record<string, string>>({})
|
const profileWardrobeErrorsByProfileId = ref<Record<string, string>>({})
|
||||||
const profileWardrobeLoadingByProfileId = ref<Record<string, boolean>>({})
|
const profileWardrobeLoadingByProfileId = ref<Record<string, boolean>>({})
|
||||||
|
|
@ -659,6 +670,7 @@ const profileGenerationBusyByProfileId = ref<Record<string, ProfileGenerationMod
|
||||||
const profileGenerationErrorsByProfileId = ref<Record<string, string>>({})
|
const profileGenerationErrorsByProfileId = ref<Record<string, string>>({})
|
||||||
|
|
||||||
const activeNav = ref<NavKey>(initialNav())
|
const activeNav = ref<NavKey>(initialNav())
|
||||||
|
const materialLibraryView = ref<MaterialLibraryView>(initialMaterialLibraryView())
|
||||||
const activeGenerateMode = ref<GenerateMode>("image")
|
const activeGenerateMode = ref<GenerateMode>("image")
|
||||||
const workflowEntryConfirmed = ref(false)
|
const workflowEntryConfirmed = ref(false)
|
||||||
const workflowEntryFromProfile = ref(false)
|
const workflowEntryFromProfile = ref(false)
|
||||||
|
|
@ -1100,14 +1112,46 @@ const materialCategoryNameById = computed(() => {
|
||||||
const entries = materialCategories.value.map((category) => [category.category_id, category.name] as const)
|
const entries = materialCategories.value.map((category) => [category.category_id, category.name] as const)
|
||||||
return new Map(entries)
|
return new Map(entries)
|
||||||
})
|
})
|
||||||
|
const materialHeroTitle = computed(() =>
|
||||||
|
materialLibraryView.value === "standard"
|
||||||
|
? "角色参考素材工作台"
|
||||||
|
: materialLibraryView.value === "advanced"
|
||||||
|
? "高还原度进阶素材库"
|
||||||
|
: "进阶素材识别与验证",
|
||||||
|
)
|
||||||
|
const materialHeroDetail = computed(() =>
|
||||||
|
materialLibraryView.value === "standard"
|
||||||
|
? "集中管理参考图、识别结果、分类、素材包导入和角色衣橱绑定,后续角色工作流会从这里读取可确认素材。"
|
||||||
|
: materialLibraryView.value === "advanced"
|
||||||
|
? "只展示经过源图与验证图人工对照、明确封存的高优先级素材;数据和图片与普通素材严格隔离。"
|
||||||
|
: "导入源图后自动识别并生成验证图,可根据还原度多轮调整描述,确认满意后再封存入库。",
|
||||||
|
)
|
||||||
|
const advancedCatalogMaterials = computed<Material[]>(() =>
|
||||||
|
materialCatalog.value
|
||||||
|
.filter((entry) => catalogEntryKind(entry) === "advanced" && normalizeStatus(entry.status) !== "archived")
|
||||||
|
.map(materialFromCatalogEntry),
|
||||||
|
)
|
||||||
|
const combinedConfirmedMaterials = computed<Material[]>(() =>
|
||||||
|
uniqueBy(
|
||||||
|
[
|
||||||
|
...advancedCatalogMaterials.value,
|
||||||
|
...(materials.value?.items ?? []).filter(
|
||||||
|
(material) => normalizeStatus(material.recognition_status) === "confirmed",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
(material) => material.material_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
const backendQuickProfileMaterialOptions = computed<QuickProfileMaterialOption[]>(() =>
|
const backendQuickProfileMaterialOptions = computed<QuickProfileMaterialOption[]>(() =>
|
||||||
(materials.value?.items ?? [])
|
combinedConfirmedMaterials.value
|
||||||
.filter((material) => normalizeStatus(material.recognition_status) === "confirmed")
|
|
||||||
.map(quickProfileMaterialOptionFromBackend)
|
.map(quickProfileMaterialOptionFromBackend)
|
||||||
.filter((material): material is QuickProfileMaterialOption => Boolean(material)),
|
.filter((material): material is QuickProfileMaterialOption => Boolean(material)),
|
||||||
)
|
)
|
||||||
const quickProfileSelectableMaterials = computed<QuickProfileMaterialOption[]>(() => {
|
const quickProfileSelectableMaterials = computed<QuickProfileMaterialOption[]>(() => {
|
||||||
return backendQuickProfileMaterialOptions.value
|
return [...backendQuickProfileMaterialOptions.value].sort((left, right) => {
|
||||||
|
const advancedDelta = Number(Boolean(right.advanced)) - Number(Boolean(left.advanced))
|
||||||
|
return advancedDelta || Number(right.priority || 0) - Number(left.priority || 0)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
const rawMaterialLibraryCards = computed<MaterialLibraryCard[]>(() => {
|
const rawMaterialLibraryCards = computed<MaterialLibraryCard[]>(() => {
|
||||||
const backendItems = materials.value?.items ?? []
|
const backendItems = materials.value?.items ?? []
|
||||||
|
|
@ -1560,7 +1604,11 @@ const selectedProfileWardrobeLoading = computed(
|
||||||
)
|
)
|
||||||
const profileWardrobeMaterials = computed<Material[]>(() =>
|
const profileWardrobeMaterials = computed<Material[]>(() =>
|
||||||
uniqueBy(
|
uniqueBy(
|
||||||
[...(materials.value?.items ?? []), ...Object.values(wardrobeMaterialRecords.value)],
|
[
|
||||||
|
...advancedCatalogMaterials.value,
|
||||||
|
...(materials.value?.items ?? []),
|
||||||
|
...Object.values(wardrobeMaterialRecords.value),
|
||||||
|
],
|
||||||
(material) => material.material_id,
|
(material) => material.material_id,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
@ -2387,11 +2435,7 @@ const selectedWorkflowRoundCreateHint = computed(() => {
|
||||||
? `将以 ${likedCount} 张成功且喜欢的候选创建下一轮。`
|
? `将以 ${likedCount} 张成功且喜欢的候选创建下一轮。`
|
||||||
: "请先把 1–3 张生成成功的候选标记为“喜欢”,再开始下一轮。"
|
: "请先把 1–3 张生成成功的候选标记为“喜欢”,再开始下一轮。"
|
||||||
})
|
})
|
||||||
const confirmedWorkflowMaterials = computed(() =>
|
const confirmedWorkflowMaterials = computed(() => combinedConfirmedMaterials.value)
|
||||||
(materials.value?.items ?? []).filter(
|
|
||||||
(material) => normalizeStatus(material.recognition_status) === "confirmed",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
const selectedWorkflowNodeMaterialIds = computed(
|
const selectedWorkflowNodeMaterialIds = computed(
|
||||||
() => workflowNodeMaterialDetail.value?.material_bindings.selected_material_ids ?? [],
|
() => workflowNodeMaterialDetail.value?.material_bindings.selected_material_ids ?? [],
|
||||||
)
|
)
|
||||||
|
|
@ -3269,7 +3313,7 @@ const selectedQueueJobRows = computed<QueueDetailRow[]>(() => {
|
||||||
{ label: "状态", value: statusLabel(job.status) },
|
{ label: "状态", value: statusLabel(job.status) },
|
||||||
{ label: "模型路由", value: job.model_route || "-" },
|
{ label: "模型路由", value: job.model_route || "-" },
|
||||||
{ label: "进度", value: `${progressValue(job)}%` },
|
{ label: "进度", value: `${progressValue(job)}%` },
|
||||||
{ label: "等待时间", value: waitTime(job) },
|
{ label: "耗时 / 后端时限", value: waitTime(job) },
|
||||||
{ label: "角色", value: context.profileName || "未关联角色" },
|
{ label: "角色", value: context.profileName || "未关联角色" },
|
||||||
{ label: "工作流", value: context.workflowName || "未关联工作流" },
|
{ label: "工作流", value: context.workflowName || "未关联工作流" },
|
||||||
{ label: "节点", value: context.nodeName || "未关联节点" },
|
{ label: "节点", value: context.nodeName || "未关联节点" },
|
||||||
|
|
@ -3321,6 +3365,20 @@ const queueActionCards = computed<QueueActionCard[]>(() => {
|
||||||
!executingId && job && canWrite && canRetry && failedJobs.value.some((item) => item.task_id === job.task_id),
|
!executingId && job && canWrite && canRetry && failedJobs.value.some((item) => item.task_id === job.task_id),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "retry-all-failed",
|
||||||
|
title: "一键重试全部失败任务",
|
||||||
|
detail: !canManageQueue
|
||||||
|
? "当前账号缺少任务重试权限。"
|
||||||
|
: failedJobs.value.length
|
||||||
|
? `当前检测到 ${failedJobs.value.length} 条失败、取消或死信记录;将逐条创建替代任务,旧记录会标记为已被重试替代。`
|
||||||
|
: "当前没有可重试的失败、取消或死信记录。",
|
||||||
|
badge: "BATCH",
|
||||||
|
endpoint: endpoints.jobRetryFailed,
|
||||||
|
action: executingId === "retry-all-failed" ? "批量处理中" : "一键重试全部",
|
||||||
|
tone: "warn",
|
||||||
|
enabled: Boolean(!executingId && canWrite && canRetry && failedJobs.value.length > 0),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "cancel",
|
id: "cancel",
|
||||||
title: "取消运行任务",
|
title: "取消运行任务",
|
||||||
|
|
@ -4305,6 +4363,10 @@ async function loadAll() {
|
||||||
lastUpdated.value = new Date().toISOString()
|
lastUpdated.value = new Date().toISOString()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function initialMaterialLibraryView(): MaterialLibraryView {
|
||||||
|
return parseMaterialLibraryView(new URLSearchParams(window.location.search).get("materialView"))
|
||||||
|
}
|
||||||
|
|
||||||
function initialProfilePageId() {
|
function initialProfilePageId() {
|
||||||
return new URLSearchParams(window.location.search).get("profile")?.trim() ?? ""
|
return new URLSearchParams(window.location.search).get("profile")?.trim() ?? ""
|
||||||
}
|
}
|
||||||
|
|
@ -4691,16 +4753,18 @@ async function loadMaterials() {
|
||||||
materialActionMessage.value = ""
|
materialActionMessage.value = ""
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const [categories, firstMaterialPage] = await Promise.all([
|
const [categories, firstMaterialPage, catalogItems] = await Promise.all([
|
||||||
getJson<MaterialCategory[]>(endpoints.materialCategories),
|
getJson<MaterialCategory[]>(endpoints.materialCategories),
|
||||||
getJson<MaterialListResult>(endpoints.materials, {
|
getJson<MaterialListResult>(endpoints.materials, {
|
||||||
page: 1,
|
page: 1,
|
||||||
page_size: 100,
|
page_size: 100,
|
||||||
}),
|
}),
|
||||||
|
loadMaterialCatalog(),
|
||||||
])
|
])
|
||||||
const materialList = await loadRemainingMaterialPages(firstMaterialPage)
|
const materialList = await loadRemainingMaterialPages(firstMaterialPage)
|
||||||
materialCategories.value = categories
|
materialCategories.value = categories
|
||||||
materials.value = materialList
|
materials.value = materialList
|
||||||
|
materialCatalog.value = catalogItems
|
||||||
if (!materialCategorySyncAttempted.value && bootstrap.value?.permissions.can_manage_materials) {
|
if (!materialCategorySyncAttempted.value && bootstrap.value?.permissions.can_manage_materials) {
|
||||||
materialCategorySyncAttempted.value = true
|
materialCategorySyncAttempted.value = true
|
||||||
void ensureDefaultMaterialCategories(categories)
|
void ensureDefaultMaterialCategories(categories)
|
||||||
|
|
@ -4708,12 +4772,33 @@ async function loadMaterials() {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
materialCategories.value = []
|
materialCategories.value = []
|
||||||
materials.value = null
|
materials.value = null
|
||||||
|
materialCatalog.value = []
|
||||||
materialsError.value = errorMessage(err)
|
materialsError.value = errorMessage(err)
|
||||||
} finally {
|
} finally {
|
||||||
loadingMaterials.value = false
|
loadingMaterials.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadMaterialCatalog(): Promise<MaterialCatalogEntry[]> {
|
||||||
|
try {
|
||||||
|
const payload = await getJson<{ items?: MaterialCatalogEntry[] } | MaterialCatalogEntry[]>(endpoints.materialCatalog, {
|
||||||
|
page: 1,
|
||||||
|
page_size: 200,
|
||||||
|
})
|
||||||
|
const items = Array.isArray(payload) ? payload : payload.items ?? []
|
||||||
|
return items
|
||||||
|
.filter((item) => normalizeStatus(item.status) !== "archived")
|
||||||
|
.sort((left, right) => {
|
||||||
|
const advancedDelta = Number(catalogEntryKind(right) === "advanced") - Number(catalogEntryKind(left) === "advanced")
|
||||||
|
return advancedDelta || Number(right.priority || 0) - Number(left.priority || 0)
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
// Older backends do not expose the unified catalog. Ordinary materials
|
||||||
|
// remain usable while the advanced-material migration is unavailable.
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function loadRemainingMaterialPages(firstPage: MaterialListResult): Promise<MaterialListResult> {
|
async function loadRemainingMaterialPages(firstPage: MaterialListResult): Promise<MaterialListResult> {
|
||||||
const pageSize = Math.max(1, firstPage.page_size)
|
const pageSize = Math.max(1, firstPage.page_size)
|
||||||
const pageCount = Math.ceil(firstPage.total / pageSize)
|
const pageCount = Math.ceil(firstPage.total / pageSize)
|
||||||
|
|
@ -4951,13 +5036,20 @@ function setProfileWardrobeLoading(profileId: string, loading: boolean) {
|
||||||
|
|
||||||
async function hydrateWardrobeMaterials(items: WardrobeItem[]) {
|
async function hydrateWardrobeMaterials(items: WardrobeItem[]) {
|
||||||
const knownIds = new Set([
|
const knownIds = new Set([
|
||||||
|
...advancedCatalogMaterials.value.map((material) => material.material_id),
|
||||||
...(materials.value?.items ?? []).map((material) => material.material_id),
|
...(materials.value?.items ?? []).map((material) => material.material_id),
|
||||||
...Object.keys(wardrobeMaterialRecords.value),
|
...Object.keys(wardrobeMaterialRecords.value),
|
||||||
])
|
])
|
||||||
const missingIds = uniqueStrings(items.map((item) => item.material_id).filter((materialId) => !knownIds.has(materialId)))
|
const missingIds = uniqueStrings(items.map((item) => item.material_id).filter((materialId) => !knownIds.has(materialId)))
|
||||||
if (!missingIds.length) return
|
if (!missingIds.length) return
|
||||||
const loaded = await Promise.allSettled(
|
const loaded = await Promise.allSettled(
|
||||||
missingIds.map((materialId) => getJson<Material>(endpoints.material(materialId))),
|
missingIds.map((materialId) =>
|
||||||
|
getJson<Material>(
|
||||||
|
materialId.startsWith("advmat_")
|
||||||
|
? endpoints.advancedMaterial(materialId)
|
||||||
|
: endpoints.material(materialId),
|
||||||
|
),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
const records = loaded
|
const records = loaded
|
||||||
.filter((result): result is PromiseFulfilledResult<Material> => result.status === "fulfilled")
|
.filter((result): result is PromiseFulfilledResult<Material> => result.status === "fulfilled")
|
||||||
|
|
@ -4981,6 +5073,19 @@ function selectRailItem(item: NavItem) {
|
||||||
setActiveNav(item.key, item.module)
|
setActiveNav(item.key, item.module)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setMaterialLibraryView(view: MaterialLibraryView) {
|
||||||
|
materialLibraryView.value = view
|
||||||
|
const url = new URL(window.location.href)
|
||||||
|
url.searchParams.set("view", "materials")
|
||||||
|
url.searchParams.set("materialView", view)
|
||||||
|
window.history.replaceState({}, "", `${url.pathname}${url.search}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAdvancedMaterialChanged() {
|
||||||
|
lastUpdated.value = new Date().toISOString()
|
||||||
|
materialCatalog.value = await loadMaterialCatalog()
|
||||||
|
}
|
||||||
|
|
||||||
function reuseGalleryImage(image: GalleryImage) {
|
function reuseGalleryImage(image: GalleryImage) {
|
||||||
selectedGalleryImageId.value = image.image_id
|
selectedGalleryImageId.value = image.image_id
|
||||||
selectedGenerateImageId.value = image.image_id
|
selectedGenerateImageId.value = image.image_id
|
||||||
|
|
@ -5171,6 +5276,38 @@ function materialCategoryCanonicalName(name: string) {
|
||||||
return labels[name] ?? name
|
return labels[name] ?? name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function materialFromCatalogEntry(entry: MaterialCatalogEntry): Material {
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
const kind = catalogEntryKind(entry)
|
||||||
|
const priority = Number(entry.priority || entry.metadata?.material_priority || 0)
|
||||||
|
return {
|
||||||
|
material_id: entry.material_id,
|
||||||
|
category_id: entry.category_id ?? null,
|
||||||
|
display_name: entry.display_name,
|
||||||
|
image_uri: entry.image_uri ?? null,
|
||||||
|
thumbnail_uri: entry.thumbnail_uri ?? null,
|
||||||
|
image_url: entry.image_url || entry.image_uri || null,
|
||||||
|
thumbnail_url: entry.thumbnail_url || entry.thumbnail_uri || null,
|
||||||
|
prompt: entry.prompt ?? null,
|
||||||
|
negative_prompt: entry.negative_prompt ?? null,
|
||||||
|
tags: Array.isArray(entry.tags) ? entry.tags : [],
|
||||||
|
recognition_status: "confirmed",
|
||||||
|
metadata: {
|
||||||
|
...entry.metadata,
|
||||||
|
material_type: kind,
|
||||||
|
advanced_material: kind === "advanced",
|
||||||
|
catalog_priority: priority,
|
||||||
|
source_image_uri: entry.image_uri ?? null,
|
||||||
|
},
|
||||||
|
created_at: String(entry.created_at || now),
|
||||||
|
updated_at: String(entry.updated_at || entry.created_at || now),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function catalogEntryKind(entry: MaterialCatalogEntry) {
|
||||||
|
return String(entry.library_kind || entry.material_type || entry.metadata?.library_kind || "standard")
|
||||||
|
}
|
||||||
|
|
||||||
function quickProfileMaterialOptionFromBackend(material: Material, index: number): QuickProfileMaterialOption | null {
|
function quickProfileMaterialOptionFromBackend(material: Material, index: number): QuickProfileMaterialOption | null {
|
||||||
const categoryRecord = materialCategories.value.find((category) => category.category_id === material.category_id)
|
const categoryRecord = materialCategories.value.find((category) => category.category_id === material.category_id)
|
||||||
const parentCategory = categoryRecord?.parent_id
|
const parentCategory = categoryRecord?.parent_id
|
||||||
|
|
@ -5196,6 +5333,8 @@ function quickProfileMaterialOptionFromBackend(material: Material, index: number
|
||||||
displayMediaUrl(material.thumbnail_url) ||
|
displayMediaUrl(material.thumbnail_url) ||
|
||||||
displayMediaUrl(material.image_url),
|
displayMediaUrl(material.image_url),
|
||||||
source: "backend",
|
source: "backend",
|
||||||
|
advanced: material.metadata?.advanced_material === true || material.metadata?.material_type === "advanced",
|
||||||
|
priority: Number(material.metadata?.catalog_priority || 0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -10078,7 +10217,7 @@ async function executeQueueAction(actionId: string, taskId?: string) {
|
||||||
bootstrap.value?.permissions.can_write && bootstrap.value?.permissions.can_retry_tasks,
|
bootstrap.value?.permissions.can_write && bootstrap.value?.permissions.can_retry_tasks,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (["delete", "clear-failed", "clear-completed", "clear-terminal"].includes(actionId) && !canManageQueue) {
|
if (["delete", "retry-all-failed", "clear-failed", "clear-completed", "clear-terminal"].includes(actionId) && !canManageQueue) {
|
||||||
jobsError.value = "当前账号缺少任务清理权限,请刷新页面后重试。"
|
jobsError.value = "当前账号缺少任务清理权限,请刷新页面后重试。"
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -10089,6 +10228,10 @@ async function executeQueueAction(actionId: string, taskId?: string) {
|
||||||
jobsError.value = "目标任务已不存在或状态已经变化,只有失败、取消、死信和已完成记录可以删除。"
|
jobsError.value = "目标任务已不存在或状态已经变化,只有失败、取消、死信和已完成记录可以删除。"
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (actionId === "retry-all-failed" && failedJobs.value.length === 0) {
|
||||||
|
jobsError.value = "当前已经没有可重试的失败、取消或死信记录。"
|
||||||
|
return
|
||||||
|
}
|
||||||
if (actionId === "clear-failed" && failedJobs.value.length === 0) {
|
if (actionId === "clear-failed" && failedJobs.value.length === 0) {
|
||||||
jobsError.value = "当前已经没有可清理的异常记录。"
|
jobsError.value = "当前已经没有可清理的异常记录。"
|
||||||
return
|
return
|
||||||
|
|
@ -10109,6 +10252,9 @@ async function executeQueueAction(actionId: string, taskId?: string) {
|
||||||
const retried = await postJson<GenerationJob>(endpoints.jobRetry(job.task_id), {})
|
const retried = await postJson<GenerationJob>(endpoints.jobRetry(job.task_id), {})
|
||||||
selectedQueueTaskId.value = retried.task_id
|
selectedQueueTaskId.value = retried.task_id
|
||||||
queueActionMessage.value = `替代任务 ${shortId(retried.task_id)} 已执行,状态:${statusLabel(retried.status)}。`
|
queueActionMessage.value = `替代任务 ${shortId(retried.task_id)} 已执行,状态:${statusLabel(retried.status)}。`
|
||||||
|
} else if (actionId === "retry-all-failed") {
|
||||||
|
const result = await postJson<Record<string, unknown>>(endpoints.jobRetryFailed, { limit: 100 })
|
||||||
|
queueActionMessage.value = queueBatchActionMessage(result, "失败任务已批量重试")
|
||||||
} else if (actionId === "cancel") {
|
} else if (actionId === "cancel") {
|
||||||
if (!job) return
|
if (!job) return
|
||||||
const cancelled = await postJson<GenerationJob>(endpoints.jobCancel(job.task_id), {})
|
const cancelled = await postJson<GenerationJob>(endpoints.jobCancel(job.task_id), {})
|
||||||
|
|
@ -10717,7 +10863,7 @@ function displayMediaUrl(rawUrl?: string | null): string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// AstrBot's sandbox bridge carries the dashboard login state. A direct
|
// AstrBot's sandbox bridge carries the dashboard login state. A direct
|
||||||
// <img> request cannot add that credential and is rejected with HTTP 401,
|
// Direct image requests cannot add the bridge credential and are rejected.
|
||||||
// so avoid rendering the known-broken URL while its Blob is being loaded.
|
// so avoid rendering the known-broken URL while its Blob is being loaded.
|
||||||
return getApiTransport() === "plugin-bridge" ? "" : value
|
return getApiTransport() === "plugin-bridge" ? "" : value
|
||||||
}
|
}
|
||||||
|
|
@ -10887,6 +11033,7 @@ function errorMessage(err: unknown) {
|
||||||
<template>
|
<template>
|
||||||
<main
|
<main
|
||||||
class="navigation-shell"
|
class="navigation-shell"
|
||||||
|
aria-label="ImageStudio workbench"
|
||||||
:class="{ 'rail-collapsed': !navigationRailExpanded }"
|
:class="{ 'rail-collapsed': !navigationRailExpanded }"
|
||||||
:data-theme="themeMode"
|
:data-theme="themeMode"
|
||||||
:style="shellStyle"
|
:style="shellStyle"
|
||||||
|
|
@ -10903,7 +11050,7 @@ function errorMessage(err: unknown) {
|
||||||
@togglePinned="toggleNavigationRailPinned"
|
@togglePinned="toggleNavigationRailPinned"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<section class="workbench">
|
<section class="workbench" aria-label="ImageStudio workspace">
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
<div class="active-heading">
|
<div class="active-heading">
|
||||||
<span>{{ activeItem.label }}</span>
|
<span>{{ activeItem.label }}</span>
|
||||||
|
|
@ -10914,6 +11061,7 @@ function errorMessage(err: unknown) {
|
||||||
<span aria-hidden="true">⌕</span>
|
<span aria-hidden="true">⌕</span>
|
||||||
<input
|
<input
|
||||||
ref="searchInputRef"
|
ref="searchInputRef"
|
||||||
|
aria-label="Search ImageStudio"
|
||||||
v-model="searchQuery"
|
v-model="searchQuery"
|
||||||
type="search"
|
type="search"
|
||||||
role="combobox"
|
role="combobox"
|
||||||
|
|
@ -11064,6 +11212,7 @@ function errorMessage(err: unknown) {
|
||||||
v-if="showBackendConnectionBanner"
|
v-if="showBackendConnectionBanner"
|
||||||
:class="['backend-connection-banner', backendConnectionClass]"
|
:class="['backend-connection-banner', backendConnectionClass]"
|
||||||
role="status"
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<strong>{{ backendConnection.title }}</strong>
|
<strong>{{ backendConnection.title }}</strong>
|
||||||
|
|
@ -11297,7 +11446,8 @@ function errorMessage(err: unknown) {
|
||||||
</option>
|
</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<span v-if="imageGenerationSubmitting" class="model-state" role="status">生成中</span>
|
<span v-if="imageGenerationSubmitting" class="model-state" role="status"
|
||||||
|
aria-live="polite">生成中</span>
|
||||||
<span v-else-if="imageGenerationError" class="model-state model-state-error" role="alert">
|
<span v-else-if="imageGenerationError" class="model-state model-state-error" role="alert">
|
||||||
{{ imageGenerationError }}
|
{{ imageGenerationError }}
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -11687,7 +11837,8 @@ function errorMessage(err: unknown) {
|
||||||
<span v-else class="feature-action">{{ quickProfileActionButtonLabel(card) }}</span>
|
<span v-else class="feature-action">{{ quickProfileActionButtonLabel(card) }}</span>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="quickCharacterGenerationNotice" class="generation-notice" role="status">
|
<p v-if="quickCharacterGenerationNotice" class="generation-notice" role="status"
|
||||||
|
aria-live="polite">
|
||||||
{{ quickCharacterGenerationNotice }}
|
{{ quickCharacterGenerationNotice }}
|
||||||
</p>
|
</p>
|
||||||
<p v-if="quickCharacterGenerationError" class="generation-error" role="alert">
|
<p v-if="quickCharacterGenerationError" class="generation-error" role="alert">
|
||||||
|
|
@ -12247,7 +12398,8 @@ function errorMessage(err: unknown) {
|
||||||
<span v-else class="quick-profile-empty-media-mark">无缩略图</span>
|
<span v-else class="quick-profile-empty-media-mark">无缩略图</span>
|
||||||
</span>
|
</span>
|
||||||
<span class="quick-profile-material-picker-copy">
|
<span class="quick-profile-material-picker-copy">
|
||||||
<small v-if="activeQuickProfileMaterialPickerCategory === QUICK_PROFILE_ACCESSORY_CATEGORY">
|
<small v-if="reference.advanced">进阶素材 · 高优先级</small>
|
||||||
|
<small v-else-if="activeQuickProfileMaterialPickerCategory === QUICK_PROFILE_ACCESSORY_CATEGORY">
|
||||||
{{ quickProfileMaterialGroupLabel(reference) }}
|
{{ quickProfileMaterialGroupLabel(reference) }}
|
||||||
</small>
|
</small>
|
||||||
<strong>{{ reference.label }}</strong>
|
<strong>{{ reference.label }}</strong>
|
||||||
|
|
@ -12916,18 +13068,53 @@ function errorMessage(err: unknown) {
|
||||||
<header class="materials-hero">
|
<header class="materials-hero">
|
||||||
<div>
|
<div>
|
||||||
<span>素材库</span>
|
<span>素材库</span>
|
||||||
<h2>角色参考素材工作台</h2>
|
<h2>{{ materialHeroTitle }}</h2>
|
||||||
<p>集中管理参考图、识别结果、分类、素材包导入和角色衣橱绑定,后续角色工作流会从这里读取可确认素材。</p>
|
<p>{{ materialHeroDetail }}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="materials-hero-actions">
|
<div v-if="materialLibraryView === 'standard'" class="materials-hero-actions">
|
||||||
<button type="button" :disabled="loadingMaterials" @click="handleMaterialAction(materialActionCards[0])">
|
<button type="button" :disabled="loadingMaterials" @click="handleMaterialAction(materialActionCards[0])">
|
||||||
{{ loadingMaterials ? "同步中" : "刷新素材" }}
|
{{ loadingMaterials ? "同步中" : "刷新素材" }}
|
||||||
</button>
|
</button>
|
||||||
<button type="button" @click="openMaterialWorkflowBinding">进入素材绑定</button>
|
<button type="button" @click="openMaterialWorkflowBinding">进入素材绑定</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-else class="materials-hero-actions">
|
||||||
|
<button type="button" @click="setMaterialLibraryView('advanced')">查看进阶素材</button>
|
||||||
|
<button type="button" @click="setMaterialLibraryView('advanced-import')">新建进阶导入</button>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<MetricCardGrid :cards="materialStatusCards" section-class="materials-status-grid" />
|
<nav class="materials-view-tabs" aria-label="素材库视图">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
:class="{ active: materialLibraryView === 'standard' }"
|
||||||
|
:aria-pressed="materialLibraryView === 'standard'"
|
||||||
|
@click="setMaterialLibraryView('standard')"
|
||||||
|
>
|
||||||
|
<strong>普通素材库</strong>
|
||||||
|
<small>快速识别与直接确认</small>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
:class="{ active: materialLibraryView === 'advanced' }"
|
||||||
|
:aria-pressed="materialLibraryView === 'advanced'"
|
||||||
|
@click="setMaterialLibraryView('advanced')"
|
||||||
|
>
|
||||||
|
<strong>进阶素材库</strong>
|
||||||
|
<small>验证通过的高优先级素材</small>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
:class="{ active: materialLibraryView === 'advanced-import' }"
|
||||||
|
:aria-pressed="materialLibraryView === 'advanced-import'"
|
||||||
|
@click="setMaterialLibraryView('advanced-import')"
|
||||||
|
>
|
||||||
|
<strong>进阶导入</strong>
|
||||||
|
<small>识别、验证生图与多轮调整</small>
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<template v-if="materialLibraryView === 'standard'">
|
||||||
|
<MetricCardGrid :cards="materialStatusCards" section-class="materials-status-grid" />
|
||||||
|
|
||||||
<StateCard
|
<StateCard
|
||||||
v-if="materialsError || materialActionMessage"
|
v-if="materialsError || materialActionMessage"
|
||||||
|
|
@ -13117,6 +13304,16 @@ function errorMessage(err: unknown) {
|
||||||
@save-profile="saveSelectedMaterialProfile"
|
@save-profile="saveSelectedMaterialProfile"
|
||||||
@close="closeOverlay('materialDetail')"
|
@close="closeOverlay('materialDetail')"
|
||||||
/>
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<AdvancedMaterialImportPage
|
||||||
|
v-else
|
||||||
|
:mode="materialLibraryView"
|
||||||
|
:categories="materialCategories"
|
||||||
|
:can-manage="Boolean(bootstrap?.permissions.can_manage_materials)"
|
||||||
|
@navigate="setMaterialLibraryView"
|
||||||
|
@changed="handleAdvancedMaterialChanged"
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
@ -13369,7 +13566,7 @@ function errorMessage(err: unknown) {
|
||||||
<li v-for="job in overviewQueueItems" :key="job.task_id">
|
<li v-for="job in overviewQueueItems" :key="job.task_id">
|
||||||
<div class="queue-main">
|
<div class="queue-main">
|
||||||
<strong>{{ jobTitle(job) }}</strong>
|
<strong>{{ jobTitle(job) }}</strong>
|
||||||
<small>{{ job.model_route || "未指定模型" }} / 等待 {{ waitTime(job) }}</small>
|
<small>{{ job.model_route || "未指定模型" }} / 耗时 {{ waitTime(job) }}</small>
|
||||||
<div class="progress-track">
|
<div class="progress-track">
|
||||||
<span :style="{ width: `${progressValue(job)}%` }" />
|
<span :style="{ width: `${progressValue(job)}%` }" />
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -15006,7 +15203,8 @@ body {
|
||||||
}
|
}
|
||||||
|
|
||||||
.queue-task-list {
|
.queue-task-list {
|
||||||
display: grid;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
max-height: min(70vh, 760px);
|
max-height: min(70vh, 760px);
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
|
|
@ -15019,8 +15217,12 @@ body {
|
||||||
grid-template-columns: 88px minmax(0, 1fr) 70px;
|
grid-template-columns: 88px minmax(0, 1fr) 70px;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
flex: 0 0 auto;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
min-height: 88px;
|
min-height: 88px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
overflow: hidden;
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
|
|
@ -15038,6 +15240,7 @@ body {
|
||||||
.queue-task-status {
|
.queue-task-status {
|
||||||
display: inline-grid;
|
display: inline-grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
|
align-self: center;
|
||||||
min-height: 32px;
|
min-height: 32px;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
padding: 0 10px;
|
padding: 0 10px;
|
||||||
|
|
@ -15117,6 +15320,7 @@ body {
|
||||||
.queue-task-meta {
|
.queue-task-meta {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
|
align-self: center;
|
||||||
justify-items: end;
|
justify-items: end;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
@ -15230,6 +15434,48 @@ body {
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.materials-view-tabs {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 7px;
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.materials-view-tabs button {
|
||||||
|
display: grid;
|
||||||
|
gap: 3px;
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 54px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px 11px;
|
||||||
|
color: var(--text);
|
||||||
|
text-align: left;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.materials-view-tabs button:hover,
|
||||||
|
.materials-view-tabs button.active {
|
||||||
|
border-color: var(--primary);
|
||||||
|
background: var(--primary-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.materials-view-tabs strong,
|
||||||
|
.materials-view-tabs small {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.materials-view-tabs small {
|
||||||
|
color: var(--text-soft);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
.materials-hero {
|
.materials-hero {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|
@ -17298,7 +17544,7 @@ body {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
border-radius: inherit;
|
border-radius: inherit;
|
||||||
background: linear-gradient(90deg, var(--primary), var(--accent));
|
background: linear-gradient(90deg, var(--primary), var(--accent));
|
||||||
transition: width 220ms ease;
|
transition: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-node-card.done .workflow-node-progress i {
|
.workflow-node-card.done .workflow-node-progress i {
|
||||||
|
|
@ -18177,8 +18423,8 @@ body {
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-draft-grid > article.final {
|
.workflow-draft-grid > article.final {
|
||||||
border-color: var(--accent);
|
border-color: color-mix(in srgb, var(--accent) 58%, var(--border));
|
||||||
box-shadow: inset 0 3px 0 var(--accent);
|
background: color-mix(in srgb, var(--accent) 10%, var(--panel-muted));
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-draft-select {
|
.workflow-draft-select {
|
||||||
|
|
@ -18396,15 +18642,15 @@ body {
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-action-card.accent {
|
.workflow-action-card.accent {
|
||||||
border-top-color: var(--accent);
|
border-color: color-mix(in srgb, var(--accent) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-action-card.warn {
|
.workflow-action-card.warn {
|
||||||
border-top-color: var(--warn);
|
border-color: color-mix(in srgb, var(--warn) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-action-card.neutral {
|
.workflow-action-card.neutral {
|
||||||
border-top-color: var(--neutral);
|
border-color: color-mix(in srgb, var(--neutral) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-action-card.disabled {
|
.workflow-action-card.disabled {
|
||||||
|
|
@ -19719,7 +19965,7 @@ body {
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overscroll-behavior: contain;
|
overscroll-behavior: contain;
|
||||||
padding-right: 4px;
|
padding-right: 4px;
|
||||||
transition: max-height 240ms var(--rail-ease);
|
transition: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.quick-profile-material-picker-list.accessory {
|
.quick-profile-material-picker-list.accessory {
|
||||||
|
|
@ -19887,7 +20133,6 @@ body {
|
||||||
min-height: 134px;
|
min-height: 134px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-top: 3px solid var(--primary);
|
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
background: var(--panel-muted);
|
background: var(--panel-muted);
|
||||||
|
|
@ -19895,15 +20140,15 @@ body {
|
||||||
}
|
}
|
||||||
|
|
||||||
.quick-profile-command-card.accent {
|
.quick-profile-command-card.accent {
|
||||||
border-top-color: var(--accent);
|
border-color: color-mix(in srgb, var(--accent) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.quick-profile-command-card.warn {
|
.quick-profile-command-card.warn {
|
||||||
border-top-color: var(--warn);
|
border-color: color-mix(in srgb, var(--warn) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.quick-profile-command-card.neutral {
|
.quick-profile-command-card.neutral {
|
||||||
border-top-color: var(--neutral);
|
border-color: color-mix(in srgb, var(--neutral) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.quick-profile-command-card.disabled {
|
.quick-profile-command-card.disabled {
|
||||||
|
|
@ -21196,6 +21441,10 @@ body {
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 900px) {
|
@media (max-width: 900px) {
|
||||||
|
.materials-view-tabs {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
.navigation-shell {
|
.navigation-shell {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
padding-bottom: 88px;
|
padding-bottom: 88px;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue"
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
|
||||||
|
|
||||||
import { createSafeBackdropClose } from "../safe-backdrop-close"
|
import { createSafeBackdropClose } from "../safe-backdrop-close"
|
||||||
|
|
||||||
|
|
@ -23,6 +23,8 @@ const scale = ref(1)
|
||||||
const offset = ref({ x: 0, y: 0 })
|
const offset = ref({ x: 0, y: 0 })
|
||||||
const dragging = ref(false)
|
const dragging = ref(false)
|
||||||
const dragStart = ref({ pointerId: -1, x: 0, y: 0, offsetX: 0, offsetY: 0 })
|
const dragStart = ref({ pointerId: -1, x: 0, y: 0, offsetX: 0, offsetY: 0 })
|
||||||
|
const dialogRef = ref<HTMLElement | null>(null)
|
||||||
|
let previousFocus: HTMLElement | null = null
|
||||||
|
|
||||||
const scaleLabel = computed(() => `${Math.round(scale.value * 100)}%`)
|
const scaleLabel = computed(() => `${Math.round(scale.value * 100)}%`)
|
||||||
const imageTransform = computed(
|
const imageTransform = computed(
|
||||||
|
|
@ -31,7 +33,16 @@ const imageTransform = computed(
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => [props.open, props.src] as const,
|
() => [props.open, props.src] as const,
|
||||||
() => reset(),
|
([open]) => {
|
||||||
|
reset()
|
||||||
|
if (open) {
|
||||||
|
previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||||
|
void nextTick(() => focusableElements()[0]?.focus())
|
||||||
|
} else {
|
||||||
|
void nextTick(restoreFocus)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
)
|
)
|
||||||
|
|
||||||
onMounted(() => window.addEventListener("keydown", handleEscape))
|
onMounted(() => window.addEventListener("keydown", handleEscape))
|
||||||
|
|
@ -102,6 +113,39 @@ function endDrag(event: PointerEvent) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function focusableElements() {
|
||||||
|
return Array.from(
|
||||||
|
dialogRef.value?.querySelectorAll<HTMLElement>(
|
||||||
|
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
|
||||||
|
) ?? [],
|
||||||
|
).filter((element) => !element.hasAttribute("hidden"))
|
||||||
|
}
|
||||||
|
|
||||||
|
function trapFocus(event: KeyboardEvent) {
|
||||||
|
if (event.key !== "Tab") return
|
||||||
|
const elements = focusableElements()
|
||||||
|
if (!elements.length) {
|
||||||
|
event.preventDefault()
|
||||||
|
dialogRef.value?.focus()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const first = elements[0]
|
||||||
|
const last = elements[elements.length - 1]
|
||||||
|
if (event.shiftKey && document.activeElement === first) {
|
||||||
|
event.preventDefault()
|
||||||
|
last.focus()
|
||||||
|
} else if (!event.shiftKey && document.activeElement === last) {
|
||||||
|
event.preventDefault()
|
||||||
|
first.focus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function restoreFocus() {
|
||||||
|
const target = previousFocus
|
||||||
|
previousFocus = null
|
||||||
|
if (target?.isConnected) target.focus()
|
||||||
|
}
|
||||||
|
|
||||||
function handleEscape(event: KeyboardEvent) {
|
function handleEscape(event: KeyboardEvent) {
|
||||||
if (props.open && event.key === "Escape") close()
|
if (props.open && event.key === "Escape") close()
|
||||||
}
|
}
|
||||||
|
|
@ -125,7 +169,7 @@ function clamp(value: number, min: number, max: number) {
|
||||||
@pointercancel="backdropClose.pointerCancel"
|
@pointercancel="backdropClose.pointerCancel"
|
||||||
@wheel.prevent="zoomFromWheel"
|
@wheel.prevent="zoomFromWheel"
|
||||||
>
|
>
|
||||||
<section class="image-viewer-card" data-overlay-root="imageViewer">
|
<section ref="dialogRef" class="image-viewer-card" data-overlay-root="imageViewer" tabindex="-1" @keydown="trapFocus">
|
||||||
<header>
|
<header>
|
||||||
<div>
|
<div>
|
||||||
<span>图片预览</span>
|
<span>图片预览</span>
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import type {
|
||||||
} from "../../../shared/types/material-operations"
|
} from "../../../shared/types/material-operations"
|
||||||
import { formatBytes } from "../../../shared/utils/presentation"
|
import { formatBytes } from "../../../shared/utils/presentation"
|
||||||
import { isStorageUri, isSupportedImageStorageUri, storageFilename } from "../../../shared/utils/storage-uri"
|
import { isStorageUri, isSupportedImageStorageUri, storageFilename } from "../../../shared/utils/storage-uri"
|
||||||
import { MATERIAL_BODY_SLOT_OPTIONS } from "../material-labels"
|
import { MATERIAL_BODY_SLOT_OPTIONS, materialCategoryLabel } from "../material-labels"
|
||||||
import { createSafeBackdropClose } from "../safe-backdrop-close"
|
import { createSafeBackdropClose } from "../safe-backdrop-close"
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
|
|
@ -60,8 +60,8 @@ const categoryOptions = computed(() => {
|
||||||
.map((category) => ({
|
.map((category) => ({
|
||||||
value: category.category_id,
|
value: category.category_id,
|
||||||
label: category.parent_id
|
label: category.parent_id
|
||||||
? `${categoriesById.get(category.parent_id)?.name ?? "未分类"} / ${category.name}`
|
? `${materialCategoryLabel(categoriesById.get(category.parent_id)?.name ?? "未分类")} / ${materialCategoryLabel(category.name)}`
|
||||||
: category.name,
|
: materialCategoryLabel(category.name),
|
||||||
}))
|
}))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -173,7 +173,7 @@ async function runBatch(action:"select"|"unselect"|"archive"|"delete"|"permanent
|
||||||
<section class="gallery-toolbar" aria-label="图库筛选">
|
<section class="gallery-toolbar" aria-label="图库筛选">
|
||||||
<label class="gallery-search">
|
<label class="gallery-search">
|
||||||
<span aria-hidden="true">⌕</span>
|
<span aria-hidden="true">⌕</span>
|
||||||
<input v-model="query" type="search" placeholder="搜索标题、提示词、模型或来源" />
|
<input id="gallery-search" v-model="query" type="search" aria-label="Search gallery" placeholder="搜索标题、提示词、模型或来源" />
|
||||||
</label>
|
</label>
|
||||||
<div class="gallery-filter-tabs" role="group" aria-label="图片状态">
|
<div class="gallery-filter-tabs" role="group" aria-label="图片状态">
|
||||||
<button
|
<button
|
||||||
|
|
@ -211,7 +211,7 @@ async function runBatch(action:"select"|"unselect"|"archive"|"delete"|"permanent
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="gallery-batchbar"><label><input type="checkbox" :checked="filteredImages.length>0&&filteredImages.filter(image=>!isSample(image)).every(image=>checkedIds.includes(image.image_id))" @change="toggleAllVisible"><span>已选 {{checkedIds.length}} 张</span></label><div><span v-if="actionMessage">{{actionMessage}}</span><button :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('select')">标记选中</button><button :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('unselect')">取消选中</button><button :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('archive')">归档</button><button class="danger" :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('delete')">安全删除</button><button class="danger" :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('permanent')">永久删除</button></div></section>
|
<section class="gallery-batchbar" aria-label="Gallery batch actions"><label><input type="checkbox" aria-label="Select all visible images" :checked="filteredImages.length>0&&filteredImages.filter(image=>!isSample(image)).every(image=>checkedIds.includes(image.image_id))" @change="toggleAllVisible"><span>已选 {{checkedIds.length}} 张</span></label><div class="gallery-batch-actions"><span v-if="actionMessage" aria-live="polite">{{actionMessage}}</span><button :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('select')">标记选中</button><button :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('unselect')">取消选中</button><button :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('archive')">归档</button><button class="danger" :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('delete')">安全删除</button><button class="danger" :disabled="!checkedIds.length||actionBusy||!backendConnected" @click="runBatch('permanent')">永久删除</button></div></section>
|
||||||
|
|
||||||
<section class="gallery-workspace">
|
<section class="gallery-workspace">
|
||||||
<div class="gallery-results">
|
<div class="gallery-results">
|
||||||
|
|
@ -237,7 +237,7 @@ async function runBatch(action:"select"|"unselect"|"archive"|"delete"|"permanent
|
||||||
:key="image.image_id"
|
:key="image.image_id"
|
||||||
:class="['gallery-card', { active: selectedImage?.image_id === image.image_id, archived: isArchived(image) }]"
|
:class="['gallery-card', { active: selectedImage?.image_id === image.image_id, archived: isArchived(image) }]"
|
||||||
>
|
>
|
||||||
<label v-if="!isSample(image)" class="gallery-card-check"><input type="checkbox" :checked="checkedIds.includes(image.image_id)" @change="toggleChecked(image.image_id)"><span></span></label>
|
<label v-if="!isSample(image)" class="gallery-card-check"><input type="checkbox" :aria-label="`Select ${image.title}`" :checked="checkedIds.includes(image.image_id)" @change="toggleChecked(image.image_id)"><span></span></label>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="gallery-card-media"
|
class="gallery-card-media"
|
||||||
|
|
@ -964,4 +964,280 @@ async function runBatch(action:"select"|"unselect"|"archive"|"delete"|"permanent
|
||||||
min-height: 30px;
|
min-height: 30px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.gallery-page {
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero,
|
||||||
|
.gallery-toolbar,
|
||||||
|
.gallery-results,
|
||||||
|
.gallery-inspector,
|
||||||
|
.gallery-load-notice,
|
||||||
|
.gallery-metrics article {
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: 0 8px 24px color-mix(in srgb, var(--bg) 18%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero {
|
||||||
|
align-items: flex-start;
|
||||||
|
padding: 24px;
|
||||||
|
background:
|
||||||
|
linear-gradient(120deg, color-mix(in srgb, var(--primary-soft) 72%, var(--panel)), var(--panel) 62%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero h2 {
|
||||||
|
font-size: clamp(24px, 2.2vw, 30px);
|
||||||
|
letter-spacing: -0.025em;
|
||||||
|
text-wrap: balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero p {
|
||||||
|
max-width: 62ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-toolbar {
|
||||||
|
gap: 14px;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-search,
|
||||||
|
.gallery-filter-tabs button,
|
||||||
|
.gallery-view-switch button,
|
||||||
|
.gallery-hero-actions button,
|
||||||
|
.gallery-card-actions button,
|
||||||
|
.gallery-inspector-actions button,
|
||||||
|
.gallery-empty button {
|
||||||
|
min-height: 38px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-search input:focus-visible,
|
||||||
|
.gallery-filter-tabs button:focus-visible,
|
||||||
|
.gallery-view-switch button:focus-visible,
|
||||||
|
.gallery-hero-actions button:focus-visible,
|
||||||
|
.gallery-card-actions button:focus-visible,
|
||||||
|
.gallery-inspector-actions button:focus-visible,
|
||||||
|
.gallery-empty button:focus-visible,
|
||||||
|
.gallery-batchbar button:focus-visible,
|
||||||
|
.gallery-card:focus-visible,
|
||||||
|
.gallery-inspector-media:focus-visible {
|
||||||
|
outline: 3px solid color-mix(in srgb, var(--primary) 55%, transparent);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-metrics {
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-metrics article {
|
||||||
|
gap: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-metrics strong {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-results {
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-results-header {
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-results-header h3,
|
||||||
|
.gallery-inspector h3 {
|
||||||
|
font-size: 18px;
|
||||||
|
letter-spacing: -0.015em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-grid {
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-card {
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--panel-muted);
|
||||||
|
transition: border-color 160ms ease, background-color 160ms ease, transform 160ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-card:hover,
|
||||||
|
.gallery-card:focus-within {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 44%, var(--border));
|
||||||
|
background: color-mix(in srgb, var(--primary-soft) 22%, var(--panel-muted));
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-card-media {
|
||||||
|
border-radius: 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-empty {
|
||||||
|
min-height: 300px;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-skeleton-grid span {
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.gallery-card,
|
||||||
|
.gallery-skeleton-grid span {
|
||||||
|
animation: none;
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-page {
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero,
|
||||||
|
.gallery-toolbar,
|
||||||
|
.gallery-results,
|
||||||
|
.gallery-inspector,
|
||||||
|
.gallery-load-notice,
|
||||||
|
.gallery-metrics article,
|
||||||
|
.gallery-batchbar {
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero {
|
||||||
|
align-items: flex-start;
|
||||||
|
padding: 22px 24px;
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero h2 {
|
||||||
|
font-size: clamp(24px, 2.2vw, 30px);
|
||||||
|
letter-spacing: -0.025em;
|
||||||
|
text-wrap: balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-hero p {
|
||||||
|
max-width: 62ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-toolbar {
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-search,
|
||||||
|
.gallery-filter-tabs button,
|
||||||
|
.gallery-view-switch button,
|
||||||
|
.gallery-hero-actions button,
|
||||||
|
.gallery-card-actions button,
|
||||||
|
.gallery-inspector-actions button,
|
||||||
|
.gallery-empty button,
|
||||||
|
.gallery-batchbar button {
|
||||||
|
min-height: 38px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-search input:focus-visible,
|
||||||
|
.gallery-filter-tabs button:focus-visible,
|
||||||
|
.gallery-view-switch button:focus-visible,
|
||||||
|
.gallery-hero-actions button:focus-visible,
|
||||||
|
.gallery-card-actions button:focus-visible,
|
||||||
|
.gallery-inspector-actions button:focus-visible,
|
||||||
|
.gallery-empty button:focus-visible,
|
||||||
|
.gallery-batchbar button:focus-visible,
|
||||||
|
.gallery-card-check input:focus-visible,
|
||||||
|
.gallery-card-media:focus-visible,
|
||||||
|
.gallery-card-copy:focus-visible,
|
||||||
|
.gallery-inspector-media:focus-visible {
|
||||||
|
outline: 2px solid var(--primary);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-metrics {
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-metrics article {
|
||||||
|
gap: 8px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-metrics strong {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-batchbar {
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-batch-actions {
|
||||||
|
min-width: 0;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-batch-actions span {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-results {
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-results-header {
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-results-header h3,
|
||||||
|
.gallery-inspector h3 {
|
||||||
|
font-size: 18px;
|
||||||
|
letter-spacing: -0.015em;
|
||||||
|
text-wrap: balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-grid {
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-card {
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--panel-muted);
|
||||||
|
transition: border-color 160ms ease, background-color 160ms ease, transform 160ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-card:hover,
|
||||||
|
.gallery-card:focus-within {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 44%, var(--border));
|
||||||
|
background: color-mix(in srgb, var(--primary-soft) 22%, var(--panel-muted));
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-card-media {
|
||||||
|
border-radius: 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-empty {
|
||||||
|
min-height: 300px;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-skeleton-grid span {
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.gallery-batch-actions {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.gallery-card,
|
||||||
|
.gallery-skeleton-grid span {
|
||||||
|
animation: none;
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
文件差异内容过多而无法显示
加载差异
|
|
@ -0,0 +1,148 @@
|
||||||
|
import type {
|
||||||
|
AdvancedMaterial,
|
||||||
|
AdvancedMaterialImport,
|
||||||
|
AdvancedMaterialValidationAttempt,
|
||||||
|
} from "../../../../shared/types/advanced-material"
|
||||||
|
|
||||||
|
export type MaterialLibraryView = "standard" | "advanced" | "advanced-import"
|
||||||
|
|
||||||
|
export interface AdvancedMaterialStatusMeta {
|
||||||
|
label: string
|
||||||
|
detail: string
|
||||||
|
tone: "idle" | "good" | "warn" | "bad" | "active"
|
||||||
|
busy: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const MATERIAL_VIEWS = new Set<MaterialLibraryView>(["standard", "advanced", "advanced-import"])
|
||||||
|
|
||||||
|
export function parseMaterialLibraryView(value: string | null | undefined): MaterialLibraryView {
|
||||||
|
return value && MATERIAL_VIEWS.has(value as MaterialLibraryView)
|
||||||
|
? (value as MaterialLibraryView)
|
||||||
|
: "standard"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function advancedImportStatusMeta(status: string): AdvancedMaterialStatusMeta {
|
||||||
|
switch (normalize(status)) {
|
||||||
|
case "pending_recognition":
|
||||||
|
case "recognition_queued":
|
||||||
|
case "style_source_recognition_queued":
|
||||||
|
return { label: "等待识别", detail: "源图已保存,等待视觉模型提取特征。", tone: "idle", busy: true }
|
||||||
|
case "recognizing":
|
||||||
|
case "recognizing_style_sources":
|
||||||
|
return { label: "正在识别", detail: "正在提取关键词、提示词和视觉特征。", tone: "active", busy: true }
|
||||||
|
case "style_source_review_required":
|
||||||
|
return { label: "待处理样本", detail: "部分样本识别未完成;可单独重试失败项或排除后继续。", tone: "warn", busy: false }
|
||||||
|
case "style_consensus_queued":
|
||||||
|
case "style_consensus_running":
|
||||||
|
return { label: "正在交叉归纳", detail: "正在对全部有效样本和逐图报告进行共性与差异分析。", tone: "active", busy: true }
|
||||||
|
case "style_consensus_failed":
|
||||||
|
return { label: "交叉归纳失败", detail: "逐图结果仍已保留,可重新发起交叉归纳。", tone: "bad", busy: false }
|
||||||
|
case "pending_validation":
|
||||||
|
case "ready_for_validation":
|
||||||
|
return { label: "等待验证", detail: "识别完成,可以生成第一张还原度验证图。", tone: "warn", busy: false }
|
||||||
|
case "validating":
|
||||||
|
case "validation_queued":
|
||||||
|
return { label: "正在验证", detail: "验证图已入队,完成后可对照源图审核。", tone: "active", busy: true }
|
||||||
|
case "validation_partial_failed":
|
||||||
|
return { label: "部分验证失败", detail: "已完成的验证图会保留,只需单独重试失败场景。", tone: "warn", busy: false }
|
||||||
|
case "pending_review":
|
||||||
|
case "awaiting_review":
|
||||||
|
return { label: "等待审核", detail: "请比较源图与验证图,决定封存或继续调整。", tone: "warn", busy: false }
|
||||||
|
case "accepted":
|
||||||
|
return { label: "已封存", detail: "已作为高优先级进阶素材入库。", tone: "good", busy: false }
|
||||||
|
case "rejected":
|
||||||
|
case "adjustment_required":
|
||||||
|
return { label: "待调整", detail: "上一轮未通过,可补充描述重新验证。", tone: "warn", busy: false }
|
||||||
|
case "failed":
|
||||||
|
case "validation_failed":
|
||||||
|
case "recognition_failed":
|
||||||
|
return { label: "处理失败", detail: "可以查看失败原因并重试当前阶段。", tone: "bad", busy: false }
|
||||||
|
case "cancelled":
|
||||||
|
return { label: "已取消", detail: "当前导入任务已取消。", tone: "idle", busy: false }
|
||||||
|
case "archived":
|
||||||
|
return { label: "已归档", detail: "当前导入记录已归档。", tone: "idle", busy: false }
|
||||||
|
default:
|
||||||
|
return { label: status || "未知状态", detail: "后端返回了尚未识别的状态。", tone: "idle", busy: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function advancedAttemptStatusMeta(status: string): AdvancedMaterialStatusMeta {
|
||||||
|
switch (normalize(status)) {
|
||||||
|
case "queued":
|
||||||
|
return { label: "已入队", detail: "验证任务正在等待执行。", tone: "idle", busy: true }
|
||||||
|
case "running":
|
||||||
|
return { label: "生成中", detail: "正在生成本轮还原度验证图。", tone: "active", busy: true }
|
||||||
|
case "succeeded":
|
||||||
|
case "completed":
|
||||||
|
case "awaiting_review":
|
||||||
|
return { label: "待审核", detail: "验证图已生成,请判断还原度。", tone: "warn", busy: false }
|
||||||
|
case "accepted":
|
||||||
|
return { label: "已采纳", detail: "本轮验证图已经封存入库。", tone: "good", busy: false }
|
||||||
|
case "rejected":
|
||||||
|
return { label: "未采纳", detail: "本轮已保留,可基于反馈继续调整。", tone: "warn", busy: false }
|
||||||
|
case "failed":
|
||||||
|
return { label: "生成失败", detail: "检查错误后可再次发起验证。", tone: "bad", busy: false }
|
||||||
|
case "cancelled":
|
||||||
|
return { label: "已取消", detail: "本轮验证任务已取消。", tone: "idle", busy: false }
|
||||||
|
default:
|
||||||
|
return { label: status || "未知状态", detail: "后端返回了尚未识别的状态。", tone: "idle", busy: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortAdvancedMaterials(items: AdvancedMaterial[]): AdvancedMaterial[] {
|
||||||
|
return [...items].sort((left, right) => {
|
||||||
|
const activeDelta = Number(normalize(right.status) === "active") - Number(normalize(left.status) === "active")
|
||||||
|
if (activeDelta) return activeDelta
|
||||||
|
const priorityDelta = Number(right.priority || 0) - Number(left.priority || 0)
|
||||||
|
if (priorityDelta) return priorityDelta
|
||||||
|
return timestamp(right.accepted_at || right.updated_at) - timestamp(left.accepted_at || left.updated_at)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortAdvancedImports(items: AdvancedMaterialImport[]): AdvancedMaterialImport[] {
|
||||||
|
return [...items].sort((left, right) => timestamp(right.updated_at) - timestamp(left.updated_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortValidationAttempts(items: AdvancedMaterialValidationAttempt[]): AdvancedMaterialValidationAttempt[] {
|
||||||
|
return [...items].sort((left, right) => {
|
||||||
|
const attemptDelta = Number(right.attempt_number || 0) - Number(left.attempt_number || 0)
|
||||||
|
return attemptDelta || timestamp(right.created_at) - timestamp(left.created_at)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function advancedMaterialErrorMessage(value: unknown): string {
|
||||||
|
if (!value || typeof value !== "object") return ""
|
||||||
|
const record = value as Record<string, unknown>
|
||||||
|
const message = String(record.message || record.detail || record.reason || "").trim()
|
||||||
|
if (message) return message
|
||||||
|
const code = String(record.code || record.error_code || "").trim()
|
||||||
|
return code ? `错误代码:${code}` : ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export function firstRecord<T>(payload: unknown, keys: string[]): T | null {
|
||||||
|
if (!payload || typeof payload !== "object") return null
|
||||||
|
const record = payload as Record<string, unknown>
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = record[key]
|
||||||
|
if (value && typeof value === "object" && !Array.isArray(value)) return value as T
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listItems<T>(payload: unknown): T[] {
|
||||||
|
if (Array.isArray(payload)) return payload as T[]
|
||||||
|
if (!payload || typeof payload !== "object") return []
|
||||||
|
const record = payload as Record<string, unknown>
|
||||||
|
if (Array.isArray(record.items)) return record.items as T[]
|
||||||
|
if (record.data && typeof record.data === "object") return listItems<T>(record.data)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalize(status: string) {
|
||||||
|
return String(status || "").trim().toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
function timestamp(value: string | null | undefined) {
|
||||||
|
const parsed = Date.parse(String(value || ""))
|
||||||
|
return Number.isFinite(parsed) ? parsed : 0
|
||||||
|
}
|
||||||
|
|
@ -391,7 +391,7 @@ function forwardWardrobeAdd(materialId: string, wardrobeCategory: string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-detail.sealed {
|
.profile-detail.sealed {
|
||||||
box-shadow: inset 0 3px 0 var(--accent);
|
border-color: color-mix(in srgb, var(--accent) 58%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.detail-heading,
|
.detail-heading,
|
||||||
|
|
@ -813,7 +813,7 @@ button.danger-button {
|
||||||
}
|
}
|
||||||
|
|
||||||
.target-selector button.active {
|
.target-selector button.active {
|
||||||
box-shadow: inset 3px 0 0 var(--accent);
|
border-color: color-mix(in srgb, var(--accent) 48%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.target-thumb {
|
.target-thumb {
|
||||||
|
|
|
||||||
|
|
@ -272,19 +272,19 @@ watch(
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
box-shadow: inset 3px 0 0 var(--border);
|
border-color: var(--border);
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-list-item.kind-ungenerated {
|
.profile-list-item.kind-ungenerated {
|
||||||
box-shadow: inset 3px 0 0 var(--neutral, #7b8494);
|
border-color: color-mix(in srgb, var(--neutral, #7b8494) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-list-item.kind-quick {
|
.profile-list-item.kind-quick {
|
||||||
box-shadow: inset 3px 0 0 var(--warn, #d5963d);
|
border-color: color-mix(in srgb, var(--warn, #d5963d) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-list-item.kind-profile_card {
|
.profile-list-item.kind-profile_card {
|
||||||
box-shadow: inset 3px 0 0 var(--accent);
|
border-color: color-mix(in srgb, var(--accent) 52%, var(--border));
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-list-item:hover {
|
.profile-list-item:hover {
|
||||||
|
|
|
||||||
|
|
@ -44,5 +44,5 @@ const adultUserCount = computed(() => ids("adult_user_allowlist").length)
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.chat-access{display:grid;gap:14px}.intro{display:grid;gap:5px;border:1px solid var(--border);border-radius:10px;padding:15px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.intro span{color:var(--text-soft);font-size:11px;font-weight:800}.intro p,.rules p{margin:0;color:var(--text-soft);line-height:1.5}.rules,.lists{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.rules article{display:grid;gap:6px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.rules b{color:var(--text-soft);font-size:11px}.rules strong{color:var(--primary)}.lists label{display:grid;gap:7px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.lists label>span{display:flex;justify-content:space-between;font-weight:750}.lists em{border-radius:5px;padding:2px 6px;color:var(--primary);background:var(--primary-soft);font-size:11px;font-style:normal}.lists textarea{width:100%;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:10px;color:var(--text);background:var(--panel);font:inherit;line-height:1.55;resize:vertical}.lists small{color:var(--text-soft)}.adult-intro{display:flex;align-items:center;justify-content:space-between;gap:18px;border-left:3px solid #d39b35;border-radius:7px;padding:12px;background:color-mix(in srgb,#e1a53a 10%,var(--panel))}.adult-intro>div{display:grid;gap:3px}.adult-intro span{color:#9a6818;font-size:11px;font-weight:800}.adult-intro p{max-width:58%;margin:0;color:var(--text-soft);font-size:12px;line-height:1.5}.adult-lists label{border-color:color-mix(in srgb,#e1a53a 35%,var(--border))}.limits{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.limits label{display:grid;gap:6px}.limits input[type=number]{min-height:40px;border:1px solid var(--border);border-radius:7px;padding:0 10px;color:var(--text);background:var(--panel);font:inherit}.limits .check{display:flex;align-items:center;gap:8px}@media(max-width:760px){.rules,.lists,.limits{grid-template-columns:1fr}.adult-intro{align-items:flex-start;flex-direction:column}.adult-intro p{max-width:none}}
|
.chat-access{display:grid;gap:14px}.intro{display:grid;gap:5px;border:1px solid var(--border);border-radius:10px;padding:15px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.intro span{color:var(--text-soft);font-size:11px;font-weight:800}.intro p,.rules p{margin:0;color:var(--text-soft);line-height:1.5}.rules,.lists{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.rules article{display:grid;gap:6px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.rules b{color:var(--text-soft);font-size:11px}.rules strong{color:var(--primary)}.lists label{display:grid;gap:7px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.lists label>span{display:flex;justify-content:space-between;font-weight:750}.lists em{border-radius:5px;padding:2px 6px;color:var(--primary);background:var(--primary-soft);font-size:11px;font-style:normal}.lists textarea{width:100%;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:10px;color:var(--text);background:var(--panel);font:inherit;line-height:1.55;resize:vertical}.lists small{color:var(--text-soft)}.adult-intro{display:flex;align-items:center;justify-content:space-between;gap:18px;border:1px solid color-mix(in srgb,#d39b35 48%,var(--border));border-radius:7px;padding:12px;background:color-mix(in srgb,#e1a53a 10%,var(--panel))}.adult-intro>div{display:grid;gap:3px}.adult-intro span{color:#9a6818;font-size:11px;font-weight:800}.adult-intro p{max-width:58%;margin:0;color:var(--text-soft);font-size:12px;line-height:1.5}.adult-lists label{border-color:color-mix(in srgb,#e1a53a 35%,var(--border))}.limits{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.limits label{display:grid;gap:6px}.limits input[type=number]{min-height:40px;border:1px solid var(--border);border-radius:7px;padding:0 10px;color:var(--text);background:var(--panel);font:inherit}.limits .check{display:flex;align-items:center;gap:8px}@media(max-width:760px){.rules,.lists,.limits{grid-template-columns:1fr}.adult-intro{align-items:flex-start;flex-direction:column}.adult-intro p{max-width:none}}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
import { computed, onMounted, ref } from "vue"
|
import { computed, onMounted, ref } from "vue"
|
||||||
import { getJson } from "../../../../shared/api/client"
|
import { getJson } from "../../../../shared/api/client"
|
||||||
import { endpoints } from "../../../../shared/api/endpoints"
|
import { endpoints } from "../../../../shared/api/endpoints"
|
||||||
|
import { encodeModelRouteChain, parseModelRouteChain, type ModelRouteChain } from "./model-route-chain"
|
||||||
|
|
||||||
type Assignment = {
|
type Assignment = {
|
||||||
key: string
|
key: string
|
||||||
|
|
@ -12,7 +13,7 @@ type Assignment = {
|
||||||
runtime: "active" | "rules"
|
runtime: "active" | "rules"
|
||||||
}
|
}
|
||||||
type AdapterOption = { id: string; name: string; route: string; model: string; enabled: boolean }
|
type AdapterOption = { id: string; name: string; route: string; model: string; enabled: boolean }
|
||||||
type RuntimeModel = { route: string; provider_id: string; name: string; model: string; modality: string; source: string }
|
type RuntimeModel = { route: string; provider_id: string; name: string; model: string; modality: string; source: "plugin" | "astrbot" | string }
|
||||||
type ReviewGroup = {
|
type ReviewGroup = {
|
||||||
key: string
|
key: string
|
||||||
primaryKey: string
|
primaryKey: string
|
||||||
|
|
@ -34,6 +35,9 @@ const runtimeModels = ref<RuntimeModel[]>([])
|
||||||
|
|
||||||
const cards: Assignment[] = [
|
const cards: Assignment[] = [
|
||||||
{ key: "material_recognition", title: "素材导入解析", description: "识别素材类别、描述、标签和生成提示词。", recommendation: "建议选择支持图片理解与结构化 JSON 输出的视觉模型;优先稳定和低成本,通常不需要最强推理模型。", kind: "vision", runtime: "active" },
|
{ key: "material_recognition", title: "素材导入解析", description: "识别素材类别、描述、标签和生成提示词。", recommendation: "建议选择支持图片理解与结构化 JSON 输出的视觉模型;优先稳定和低成本,通常不需要最强推理模型。", kind: "vision", runtime: "active" },
|
||||||
|
{ key: "advanced_material_recognition", title: "进阶素材高保真识别", description: "尽可能完整提取颜色、材质、纹理、轮廓、结构和装饰细节,作为还原验证的文字基线。", recommendation: "建议选择视觉细节提取稳定、结构化 JSON 输出可靠的模型;这里应优先识别完整度,而不是创意改写能力。", kind: "vision", runtime: "active" },
|
||||||
|
{ key: "advanced_style_consensus", title: "进阶画风交叉归纳", description: "对多张已识别样本进行共性、差异和画师签名归纳。", recommendation: "建议选择支持多图输入、长上下文和稳定 JSON 输出的视觉模型;可与单图识别模型分开,降低大请求超时风险。", kind: "vision", runtime: "active" },
|
||||||
|
{ key: "advanced_material_validation_generation", title: "进阶素材验证生图", description: "仅根据识别提示词生成一张验证图,用于判断文字描述能否还原原素材。", recommendation: "建议选择提示词遵循和材质、结构还原能力稳定的生图模型;验证阶段不会把原图作为参考图传入。", kind: "image", runtime: "active" },
|
||||||
{ key: "profile_parse", title: "外部角色导入解析", description: "将外部角色文本拆成结构化角色字段。", recommendation: "建议选择指令遵循稳定、长文本处理好且支持 JSON 输出的文本模型;角色资料很长时关注上下文长度。", kind: "text", runtime: "rules" },
|
{ key: "profile_parse", title: "外部角色导入解析", description: "将外部角色文本拆成结构化角色字段。", recommendation: "建议选择指令遵循稳定、长文本处理好且支持 JSON 输出的文本模型;角色资料很长时关注上下文长度。", kind: "text", runtime: "rules" },
|
||||||
{ key: "persona_split", title: "角色设定拆解", description: "拆解身份、外观、服装、关系和世界观。", recommendation: "建议使用语义理解和信息抽取能力较强的文本模型,重点避免遗漏设定或把推测内容当成事实。", kind: "text", runtime: "rules" },
|
{ key: "persona_split", title: "角色设定拆解", description: "拆解身份、外观、服装、关系和世界观。", recommendation: "建议使用语义理解和信息抽取能力较强的文本模型,重点避免遗漏设定或把推测内容当成事实。", kind: "text", runtime: "rules" },
|
||||||
{ key: "prompt_planning", title: "提示词规划与扩写", description: "生成阶段提示词矩阵和负面提示词。", recommendation: "建议选择熟悉生图提示词、风格词和负面词的文本模型;创意能力优先于纯推理速度。", kind: "text", runtime: "rules" },
|
{ key: "prompt_planning", title: "提示词规划与扩写", description: "生成阶段提示词矩阵和负面提示词。", recommendation: "建议选择熟悉生图提示词、风格词和负面词的文本模型;创意能力优先于纯推理速度。", kind: "text", runtime: "rules" },
|
||||||
|
|
@ -45,9 +49,8 @@ const cards: Assignment[] = [
|
||||||
{ key: "hires_fix", title: "高清修复", description: "最终放大、细节修复和风格统一。", recommendation: "建议选择支持高分辨率、图生图或重绘的模型,重点保留原角色身份与构图,避免放大时改变面部和服装。", kind: "image", runtime: "active" },
|
{ key: "hires_fix", title: "高清修复", description: "最终放大、细节修复和风格统一。", recommendation: "建议选择支持高分辨率、图生图或重绘的模型,重点保留原角色身份与构图,避免放大时改变面部和服装。", kind: "image", runtime: "active" },
|
||||||
]
|
]
|
||||||
|
|
||||||
const textRoutes = computed(() => runtimeModels.value.filter(item => item.modality === "text_generation"))
|
const pluginModels = computed(() => runtimeModels.value.filter(item => item.source === "plugin" && item.route))
|
||||||
const visionRoutes = computed(() => runtimeModels.value.filter(item => item.modality === "vision_recognition"))
|
const astrbotModels = computed(() => runtimeModels.value.filter(item => item.source === "astrbot" && item.route))
|
||||||
const imageRoutes = computed(() => runtimeModels.value.filter(item => item.modality === "image_generation"))
|
|
||||||
const reviewGroups: ReviewGroup[] = [
|
const reviewGroups: ReviewGroup[] = [
|
||||||
{
|
{
|
||||||
key: "visual_review_routes",
|
key: "visual_review_routes",
|
||||||
|
|
@ -68,13 +71,20 @@ const reviewGroups: ReviewGroup[] = [
|
||||||
kind: "image",
|
kind: "image",
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
function value(key: string) { return String(props.modelValue[key] || "") }
|
function chainValue(key: string) { return parseModelRouteChain(props.modelValue[key]) }
|
||||||
function options(card: Assignment) {
|
function sourceValue(key: string, source: keyof ModelRouteChain) { return chainValue(key)[source] }
|
||||||
const adapterRoutes = props.adapters.filter(item => item.enabled && item.route).map(item => item.route)
|
function pluginOptions(card: Pick<Assignment, "kind">) {
|
||||||
if (card.kind === "image") return Array.from(new Set([...adapterRoutes, ...imageRoutes.value.map(item => item.route)].filter(Boolean)))
|
const routes = pluginModels.value
|
||||||
const astrbotRoutes = textRoutes.value.map(item => item.route)
|
.filter(item => card.kind === "text" || item.modality === `${card.kind}_generation` || (card.kind === "vision" && item.modality === "vision_recognition"))
|
||||||
if (card.kind === "vision") return Array.from(new Set([props.visionRoute, ...visionRoutes.value.map(item => item.route)].filter(Boolean)))
|
.map(item => item.route)
|
||||||
return Array.from(new Set(astrbotRoutes.filter(Boolean)))
|
if (card.kind === "image") {
|
||||||
|
routes.push(...props.adapters.filter(item => item.enabled && item.route).map(item => item.route))
|
||||||
|
}
|
||||||
|
return Array.from(new Set(routes.filter(Boolean)))
|
||||||
|
}
|
||||||
|
function astrbotOptions(card: Pick<Assignment, "kind">) {
|
||||||
|
if (card.kind === "image") return []
|
||||||
|
return Array.from(new Set(astrbotModels.value.map(item => item.route).filter(Boolean)))
|
||||||
}
|
}
|
||||||
function optionLabel(route: string) {
|
function optionLabel(route: string) {
|
||||||
const adapter = props.adapters.find(item => item.route === route)
|
const adapter = props.adapters.find(item => item.route === route)
|
||||||
|
|
@ -83,7 +93,21 @@ function optionLabel(route: string) {
|
||||||
if (!adapter) return route
|
if (!adapter) return route
|
||||||
return `${adapter.name}${adapter.model ? ` · ${adapter.model}` : ""} (${route})`
|
return `${adapter.name}${adapter.model ? ` · ${adapter.model}` : ""} (${route})`
|
||||||
}
|
}
|
||||||
function update(key: string, next: string) { emit("update:modelValue", { ...props.modelValue, [key]: next }) }
|
function updateSource(key: string, source: keyof ModelRouteChain, next: string) {
|
||||||
|
const chain = chainValue(key)
|
||||||
|
emit("update:modelValue", {
|
||||||
|
...props.modelValue,
|
||||||
|
[key]: encodeModelRouteChain({ ...chain, [source]: next }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
function unavailablePluginRoute(card: Pick<Assignment, "key" | "kind">) {
|
||||||
|
const current = sourceValue(card.key, "plugin")
|
||||||
|
return current && !pluginOptions(card).includes(current) ? current : ""
|
||||||
|
}
|
||||||
|
function unavailableAstrbotRoute(card: Pick<Assignment, "key" | "kind">) {
|
||||||
|
const current = sourceValue(card.key, "astrbot")
|
||||||
|
return current && !astrbotOptions(card).includes(current) ? current : ""
|
||||||
|
}
|
||||||
function reviewRoutes(group: ReviewGroup) {
|
function reviewRoutes(group: ReviewGroup) {
|
||||||
const configured = props.modelValue[group.key]
|
const configured = props.modelValue[group.key]
|
||||||
const routes = Array.isArray(configured) && configured.length
|
const routes = Array.isArray(configured) && configured.length
|
||||||
|
|
@ -97,6 +121,11 @@ function updateReview(group: ReviewGroup, index: number, route: string) {
|
||||||
next[index] = route
|
next[index] = route
|
||||||
emit("update:modelValue", { ...props.modelValue, [group.key]: next, [group.primaryKey]: next[0] || "", [group.secondaryKey]: next[1] || "" })
|
emit("update:modelValue", { ...props.modelValue, [group.key]: next, [group.primaryKey]: next[0] || "", [group.secondaryKey]: next[1] || "" })
|
||||||
}
|
}
|
||||||
|
function updateReviewSource(group: ReviewGroup, index: number, source: keyof ModelRouteChain, route: string) {
|
||||||
|
const current = reviewRoutes(group)
|
||||||
|
const chain = parseModelRouteChain(current[index])
|
||||||
|
updateReview(group, index, encodeModelRouteChain({ ...chain, [source]: route }))
|
||||||
|
}
|
||||||
function addReviewRoute(group: ReviewGroup) {
|
function addReviewRoute(group: ReviewGroup) {
|
||||||
emit("update:modelValue", { ...props.modelValue, [group.key]: [...reviewRoutes(group), ""] })
|
emit("update:modelValue", { ...props.modelValue, [group.key]: [...reviewRoutes(group), ""] })
|
||||||
}
|
}
|
||||||
|
|
@ -106,11 +135,18 @@ function removeReviewRoute(group: ReviewGroup, index: number) {
|
||||||
const next = current.filter((_, itemIndex) => itemIndex !== index)
|
const next = current.filter((_, itemIndex) => itemIndex !== index)
|
||||||
emit("update:modelValue", { ...props.modelValue, [group.key]: next, [group.primaryKey]: next[0] || "", [group.secondaryKey]: next[1] || "" })
|
emit("update:modelValue", { ...props.modelValue, [group.key]: next, [group.primaryKey]: next[0] || "", [group.secondaryKey]: next[1] || "" })
|
||||||
}
|
}
|
||||||
function reviewOptions(group: ReviewGroup, index: number) {
|
function reviewOptions(group: ReviewGroup, index: number, source: keyof ModelRouteChain) {
|
||||||
const current = reviewRoutes(group)
|
const current = reviewRoutes(group)
|
||||||
const selected = new Set(current.filter((route, itemIndex) => itemIndex !== index && route))
|
const selected = new Set(
|
||||||
|
current
|
||||||
|
.filter((_, itemIndex) => itemIndex !== index)
|
||||||
|
.map(route => parseModelRouteChain(route)[source])
|
||||||
|
.filter(Boolean),
|
||||||
|
)
|
||||||
const reviewCard: Assignment = { key: "review", title: "", description: "", recommendation: "", kind: group.kind, runtime: "active" }
|
const reviewCard: Assignment = { key: "review", title: "", description: "", recommendation: "", kind: group.kind, runtime: "active" }
|
||||||
return options(reviewCard).filter(route => !selected.has(route) || route === current[index])
|
const value = parseModelRouteChain(current[index])[source]
|
||||||
|
const options = source === "plugin" ? pluginOptions(reviewCard) : astrbotOptions(reviewCard)
|
||||||
|
return options.filter(route => !selected.has(route) || route === value)
|
||||||
}
|
}
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
try { runtimeModels.value = (await getJson<{items:RuntimeModel[]}>(endpoints.runtimeModels)).items }
|
try { runtimeModels.value = (await getJson<{items:RuntimeModel[]}>(endpoints.runtimeModels)).items }
|
||||||
|
|
@ -120,14 +156,32 @@ onMounted(async () => {
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="assignments">
|
<section class="assignments">
|
||||||
<header><div><span>模型分工</span><strong>按功能节点选择模型路由</strong><p>生图与素材识别配置会立即进入运行链;标记为“规则引擎”的节点当前保留模型路由,启用远程 LLM 后无需重新调整界面。</p></div></header>
|
<header><div><span>模型分工</span><strong>插件优先,AstrBot 备用</strong><p>每个节点分别保存插件适配器和 AstrBot 提供商。运行时优先调用插件路由;插件未配置、不可用或调用失败时,自动尝试 AstrBot 备用路由。</p></div></header>
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
<article v-for="card in cards" :key="card.key">
|
<article v-for="card in cards" :key="card.key">
|
||||||
<div class="card-head"><span :class="card.kind">{{ card.kind === 'image' ? '生图' : card.kind === 'vision' ? '视觉' : '文本' }}</span><em :class="card.runtime">{{ card.runtime === 'active' ? '已接入运行时' : '当前规则引擎' }}</em></div>
|
<div class="card-head"><span :class="card.kind">{{ card.kind === 'image' ? '生图' : card.kind === 'vision' ? '视觉' : '文本' }}</span><em :class="card.runtime">{{ card.runtime === 'active' ? '已接入运行时' : '当前规则引擎' }}</em></div>
|
||||||
<strong>{{ card.title }}</strong>
|
<strong>{{ card.title }}</strong>
|
||||||
<p>{{ card.description }}</p>
|
<p>{{ card.description }}</p>
|
||||||
<div class="recommendation"><b>选型建议</b><span>{{ card.recommendation }}</span></div>
|
<div class="recommendation"><b>选型建议</b><span>{{ card.recommendation }}</span></div>
|
||||||
<label><span>模型路由</span><select :value="value(card.key)" :disabled="disabled" @change="update(card.key, ($event.target as HTMLSelectElement).value)"><option value="">自动选择默认路由</option><option v-for="route in options(card)" :key="route" :value="route">{{ optionLabel(route) }}</option></select></label>
|
<div class="route-pair">
|
||||||
|
<label>
|
||||||
|
<span><b>1</b> 插件适配器(优先)</span>
|
||||||
|
<select :value="sourceValue(card.key, 'plugin')" :disabled="disabled" @change="updateSource(card.key, 'plugin', ($event.target as HTMLSelectElement).value)">
|
||||||
|
<option value="">不使用插件路由</option>
|
||||||
|
<option v-if="unavailablePluginRoute(card)" :value="unavailablePluginRoute(card)" disabled>当前不可用:{{ unavailablePluginRoute(card) }}</option>
|
||||||
|
<option v-for="route in pluginOptions(card)" :key="route" :value="route">{{ optionLabel(route) }}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span><b>2</b> AstrBot 适配器(备用)</span>
|
||||||
|
<select :value="sourceValue(card.key, 'astrbot')" :disabled="disabled || card.kind === 'image'" @change="updateSource(card.key, 'astrbot', ($event.target as HTMLSelectElement).value)">
|
||||||
|
<option value="">{{ card.kind === 'image' ? 'AstrBot 4.25 暂无生图桥接' : '不使用 AstrBot 备用路由' }}</option>
|
||||||
|
<option v-if="unavailableAstrbotRoute(card)" :value="unavailableAstrbotRoute(card)" disabled>当前不可用:{{ unavailableAstrbotRoute(card) }}</option>
|
||||||
|
<option v-for="route in astrbotOptions(card)" :key="route" :value="route">{{ optionLabel(route) }}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p v-if="card.kind === 'vision'" class="route-note">AstrBot 视觉路由仍需所选模型真实支持图片输入;运行时会通过 image_urls 调用。</p>
|
||||||
<small>{{ card.key }}</small>
|
<small>{{ card.key }}</small>
|
||||||
</article>
|
</article>
|
||||||
<article v-for="group in reviewGroups" :key="group.key" class="review-group">
|
<article v-for="group in reviewGroups" :key="group.key" class="review-group">
|
||||||
|
|
@ -135,9 +189,13 @@ onMounted(async () => {
|
||||||
<div><strong>{{ group.title }}</strong><p>{{ group.description }}</p></div>
|
<div><strong>{{ group.title }}</strong><p>{{ group.description }}</p></div>
|
||||||
<div class="recommendation"><b>选型建议</b><span>{{ group.recommendation }}</span></div>
|
<div class="recommendation"><b>选型建议</b><span>{{ group.recommendation }}</span></div>
|
||||||
<div class="review-routes">
|
<div class="review-routes">
|
||||||
<label v-for="(route, index) in reviewRoutes(group)" :key="index">
|
<label v-for="(route, index) in reviewRoutes(group)" :key="index" class="review-route-row">
|
||||||
<span>{{ index === 0 ? '主审核模型' : index === 1 ? '复核模型' : `附加审核模型 ${index}` }}</span>
|
<span>{{ index === 0 ? '主审核模型' : index === 1 ? '复核模型' : `附加审核模型 ${index}` }}</span>
|
||||||
<div class="review-select"><select :value="route" :disabled="disabled" @change="updateReview(group, index, ($event.target as HTMLSelectElement).value)"><option value="">请选择不同的模型路由</option><option v-for="option in reviewOptions(group, index)" :key="option" :value="option">{{ optionLabel(option) }}</option></select><button v-if="index > 1" type="button" :disabled="disabled" title="移除此审核路由" @click="removeReviewRoute(group, index)">×</button></div>
|
<div class="review-select">
|
||||||
|
<select :value="parseModelRouteChain(route).plugin" :disabled="disabled" @change="updateReviewSource(group, index, 'plugin', ($event.target as HTMLSelectElement).value)"><option value="">插件路由(优先)</option><option v-for="option in reviewOptions(group, index, 'plugin')" :key="option" :value="option">{{ optionLabel(option) }}</option></select>
|
||||||
|
<select :value="parseModelRouteChain(route).astrbot" :disabled="disabled || group.kind === 'image'" @change="updateReviewSource(group, index, 'astrbot', ($event.target as HTMLSelectElement).value)"><option value="">{{ group.kind === 'image' ? 'AstrBot 暂无生图桥接' : 'AstrBot 路由(备用)' }}</option><option v-for="option in reviewOptions(group, index, 'astrbot')" :key="option" :value="option">{{ optionLabel(option) }}</option></select>
|
||||||
|
<button v-if="index > 1" type="button" :disabled="disabled" title="移除此审核路由" @click="removeReviewRoute(group, index)">×</button>
|
||||||
|
</div>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<button class="add-review" type="button" :disabled="disabled" @click="addReviewRoute(group)">+ 添加审核路由</button>
|
<button class="add-review" type="button" :disabled="disabled" @click="addReviewRoute(group)">+ 添加审核路由</button>
|
||||||
|
|
@ -148,5 +206,5 @@ onMounted(async () => {
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.assignments{display:grid;gap:14px}.assignments>header{border:1px solid var(--border);border-radius:10px;padding:15px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.assignments header>div{display:grid;gap:4px}.assignments header span{color:var(--text-soft);font-size:11px;font-weight:800}.assignments header p,.grid p{margin:0;color:var(--text-soft);line-height:1.5}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.grid article{display:grid;gap:9px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.card-head{display:flex;justify-content:space-between}.card-head span,.card-head em{border-radius:5px;padding:3px 7px;font-size:10px;font-style:normal}.card-head span.image{color:#7757e8;background:var(--primary-soft)}.card-head span.vision{color:#25845a;background:color-mix(in srgb,#39aa72 13%,var(--panel))}.card-head span.text{color:#a06a12;background:color-mix(in srgb,#e1a53a 15%,var(--panel))}.card-head em{color:var(--text-soft);background:var(--panel)}.card-head em.active{color:#25845a}.recommendation{display:grid;grid-template-columns:auto 1fr;align-items:start;gap:8px;border-left:3px solid var(--primary);border-radius:4px;padding:8px 10px;background:color-mix(in srgb,var(--primary-soft) 55%,var(--panel))}.recommendation b{white-space:nowrap;color:var(--primary);font-size:11px}.recommendation span{color:var(--text-soft);font-size:12px;line-height:1.55}.grid label{display:grid;gap:5px}.grid label>span,.grid article>small{color:var(--text-soft);font-size:11px}.grid select{width:100%;min-height:39px;border:1px solid var(--border);border-radius:7px;padding:0 34px 0 10px;color:var(--text);background:var(--panel);font:inherit;cursor:pointer}.grid select:disabled{cursor:not-allowed;opacity:.65}.review-group{grid-column:1/-1}.review-routes{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.review-select{display:flex;gap:7px}.review-select button{flex:0 0 39px;border:1px solid var(--border);border-radius:7px;color:#c45151;background:var(--panel);font-size:20px}.add-review{justify-self:start;border:1px dashed var(--primary);border-radius:7px;padding:8px 13px;color:var(--primary);background:var(--panel);cursor:pointer}@media(max-width:760px){.grid,.review-routes{grid-template-columns:1fr}.recommendation{grid-template-columns:1fr}}
|
.assignments{display:grid;gap:14px}.assignments>header{border:1px solid var(--border);border-radius:10px;padding:15px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.assignments header>div{display:grid;gap:4px}.assignments header span{color:var(--text-soft);font-size:11px;font-weight:800}.assignments header p,.grid p{margin:0;color:var(--text-soft);line-height:1.5}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.grid article{display:grid;gap:9px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.card-head{display:flex;justify-content:space-between}.card-head span,.card-head em{border-radius:5px;padding:3px 7px;font-size:10px;font-style:normal}.card-head span.image{color:#7757e8;background:var(--primary-soft)}.card-head span.vision{color:#25845a;background:color-mix(in srgb,#39aa72 13%,var(--panel))}.card-head span.text{color:#a06a12;background:color-mix(in srgb,#e1a53a 15%,var(--panel))}.card-head em{color:var(--text-soft);background:var(--panel)}.card-head em.active{color:#25845a}.recommendation{display:grid;grid-template-columns:auto 1fr;align-items:start;gap:8px;border:1px solid color-mix(in srgb,var(--primary) 48%,var(--border));border-radius:4px;padding:8px 10px;background:color-mix(in srgb,var(--primary-soft) 55%,var(--panel))}.recommendation b{white-space:nowrap;color:var(--primary);font-size:11px}.recommendation span{color:var(--text-soft);font-size:12px;line-height:1.55}.route-pair{display:grid;grid-template-columns:1fr 1fr;gap:8px}.grid label{display:grid;gap:5px;min-width:0}.grid label>span,.grid article>small{color:var(--text-soft);font-size:11px}.grid label>span b{display:inline-grid;place-items:center;width:17px;height:17px;margin-right:4px;border-radius:50%;color:#fff;background:var(--primary);font-size:9px}.grid select{width:100%;min-height:39px;border:1px solid var(--border);border-radius:7px;padding:0 34px 0 10px;color:var(--text);background:var(--panel);font:inherit;cursor:pointer}.grid select:disabled{cursor:not-allowed;opacity:.65}.route-note{font-size:11px!important}.review-group{grid-column:1/-1}.review-routes{display:grid;gap:10px}.review-route-row{border:1px solid var(--border);border-radius:8px;padding:10px;background:var(--panel)}.review-select{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:7px}.review-select button{width:39px;border:1px solid var(--border);border-radius:7px;color:#c45151;background:var(--panel);font-size:20px}.add-review{justify-self:start;border:1px dashed var(--primary);border-radius:7px;padding:8px 13px;color:var(--primary);background:var(--panel);cursor:pointer}@media(max-width:900px){.route-pair,.review-select{grid-template-columns:1fr}.review-select button{width:100%}}@media(max-width:760px){.grid{grid-template-columns:1fr}.recommendation{grid-template-columns:1fr}}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -2,22 +2,35 @@
|
||||||
import { computed, onMounted, ref } from "vue"
|
import { computed, onMounted, ref } from "vue"
|
||||||
import { getJson, postJson } from "../../../../shared/api/client"
|
import { getJson, postJson } from "../../../../shared/api/client"
|
||||||
import { endpoints } from "../../../../shared/api/endpoints"
|
import { endpoints } from "../../../../shared/api/endpoints"
|
||||||
|
import { encodeModelRouteChain, parseModelRouteChain, type ModelRouteChain } from "./model-route-chain"
|
||||||
|
|
||||||
type AdapterOption = { id:string; name:string; route:string; model:string; enabled:boolean }
|
type AdapterOption = { id:string; name:string; route:string; model:string; enabled:boolean }
|
||||||
type RuntimeModel = { route:string;provider_id:string;name:string;model:string;modality:string;source:string }
|
type RuntimeModel = { route:string;provider_id:string;name:string;model:string;modality:string;source:string }
|
||||||
|
type RouteKind = "text" | "vision"
|
||||||
|
type RouteOption = { label:string;value:string }
|
||||||
const props = defineProps<{modelValue:Record<string,unknown>;adapters:AdapterOption[];disabled:boolean}>()
|
const props = defineProps<{modelValue:Record<string,unknown>;adapters:AdapterOption[];disabled:boolean}>()
|
||||||
const emit = defineEmits<{"update:modelValue":[value:Record<string,unknown>]}>()
|
const emit = defineEmits<{"update:modelValue":[value:Record<string,unknown>]}>()
|
||||||
|
|
||||||
const value = computed(()=>clone(props.modelValue))
|
const value = computed(()=>clone(props.modelValue))
|
||||||
const runtimeModels=ref<RuntimeModel[]>([])
|
const runtimeModels=ref<RuntimeModel[]>([])
|
||||||
const imageRoutes = computed(()=>props.adapters.filter(item=>item.enabled&&item.route).map(item=>({label:`${item.name}${item.model?` / ${item.model}`:""}`,value:item.route})))
|
const imageRoutes = computed(()=>props.adapters.filter(item=>item.enabled&&item.route).map(item=>({label:`${item.name}${item.model?` / ${item.model}`:""}`,value:item.route})))
|
||||||
const textRoutes = computed(()=>runtimeModels.value.filter(item=>item.modality==="text_generation").map(item=>({label:`${item.name} / ${item.model||item.provider_id}`,value:item.route})))
|
|
||||||
const routes = imageRoutes
|
const routes = imageRoutes
|
||||||
const previewPrompt=ref(""),previewSelection=ref("translated"),manualPrompt=ref(""),previewBusy=ref(false),previewError=ref(""),previewResult=ref<Record<string,unknown>|null>(null)
|
const previewPrompt=ref(""),previewSelection=ref("translated"),manualPrompt=ref(""),previewBusy=ref(false),previewError=ref(""),previewResult=ref<Record<string,unknown>|null>(null)
|
||||||
function clone<T>(input:T):T{return JSON.parse(JSON.stringify(input??{})) as T}
|
function clone<T>(input:T):T{return JSON.parse(JSON.stringify(input??{})) as T}
|
||||||
function get(path:string,fallback:unknown=""){let current:unknown=value.value;for(const key of path.split(".")){if(!current||typeof current!=="object"||Array.isArray(current))return fallback;current=(current as Record<string,unknown>)[key]}return current??fallback}
|
function get(path:string,fallback:unknown=""){let current:unknown=value.value;for(const key of path.split(".")){if(!current||typeof current!=="object"||Array.isArray(current))return fallback;current=(current as Record<string,unknown>)[key]}return current??fallback}
|
||||||
function set(path:string,nextValue:unknown){const next=clone(value.value);const keys=path.split(".");let current=next;for(const key of keys.slice(0,-1)){if(!current[key]||typeof current[key]!=="object"||Array.isArray(current[key]))current[key]={};current=current[key] as Record<string,unknown>}current[keys.at(-1)!]=nextValue;emit("update:modelValue",next)}
|
function set(path:string,nextValue:unknown){const next=clone(value.value);const keys=path.split(".");let current=next;for(const key of keys.slice(0,-1)){if(!current[key]||typeof current[key]!=="object"||Array.isArray(current[key]))current[key]={};current=current[key] as Record<string,unknown>}current[keys.at(-1)!]=nextValue;emit("update:modelValue",next)}
|
||||||
function checked(path:string){return get(path,false)===true}
|
function checked(path:string){return get(path,false)===true}
|
||||||
|
function routeChain(path:string){return parseModelRouteChain(get(path,""))}
|
||||||
|
function routeSource(path:string,source:keyof ModelRouteChain){return routeChain(path)[source]}
|
||||||
|
function setRouteSource(path:string,source:keyof ModelRouteChain,route:string){set(path,encodeModelRouteChain({...routeChain(path),[source]:route}))}
|
||||||
|
function routeOptions(kind:RouteKind,source:keyof ModelRouteChain):RouteOption[]{
|
||||||
|
const models=runtimeModels.value.filter(item=>item.route&&item.source===(source==="plugin"?"plugin":"astrbot"))
|
||||||
|
const filtered=source==="astrbot"||kind==="text"?models:models.filter(item=>item.modality==="vision_recognition")
|
||||||
|
const result=new Map<string,string>()
|
||||||
|
for(const item of filtered)result.set(item.route,`${item.name} / ${item.model||item.provider_id}`)
|
||||||
|
return Array.from(result,([value,label])=>({value,label}))
|
||||||
|
}
|
||||||
|
function unavailableRoute(path:string,kind:RouteKind,source:keyof ModelRouteChain){const current=routeSource(path,source);return current&&!routeOptions(kind,source).some(item=>item.value===current)?current:""}
|
||||||
const entrypoints=[{key:"web",label:"Web"},{key:"qq",label:"QQ"},{key:"telegram",label:"Telegram"},{key:"discord",label:"Discord"},{key:"api",label:"API"}]
|
const entrypoints=[{key:"web",label:"Web"},{key:"qq",label:"QQ"},{key:"telegram",label:"Telegram"},{key:"discord",label:"Discord"},{key:"api",label:"API"}]
|
||||||
async function runPreview(){if(!previewPrompt.value.trim())return;previewBusy.value=true;previewError.value="";try{previewResult.value=await postJson(endpoints.promptGovernancePreview,{prompt:previewPrompt.value,entrypoint:"web",translation_consent:true,selection:previewSelection.value,manual_prompt:manualPrompt.value,model_route:String(get('routing.safe_route')||'image_low'),content_permissions:{adult_user_allowed:true,adult_group_allowed:true,quota_allowed:true}})}catch(e){previewError.value=e instanceof Error?e.message:String(e)}finally{previewBusy.value=false}}
|
async function runPreview(){if(!previewPrompt.value.trim())return;previewBusy.value=true;previewError.value="";try{previewResult.value=await postJson(endpoints.promptGovernancePreview,{prompt:previewPrompt.value,entrypoint:"web",translation_consent:true,selection:previewSelection.value,manual_prompt:manualPrompt.value,model_route:String(get('routing.safe_route')||'image_low'),content_permissions:{adult_user_allowed:true,adult_group_allowed:true,quota_allowed:true}})}catch(e){previewError.value=e instanceof Error?e.message:String(e)}finally{previewBusy.value=false}}
|
||||||
onMounted(async()=>{try{runtimeModels.value=(await getJson<{items:RuntimeModel[]}>(endpoints.runtimeModels)).items}catch{runtimeModels.value=[]}})
|
onMounted(async()=>{try{runtimeModels.value=(await getJson<{items:RuntimeModel[]}>(endpoints.runtimeModels)).items}catch{runtimeModels.value=[]}})
|
||||||
|
|
@ -29,17 +42,17 @@ onMounted(async()=>{try{runtimeModels.value=(await getJson<{items:RuntimeModel[]
|
||||||
|
|
||||||
<article class="preview-card"><header><div><span>链路预览</span><strong>发送前检查最终提示词与路由</strong></div><button :disabled="previewBusy||!previewPrompt.trim()" @click="runPreview">{{previewBusy?'处理中…':'运行预览'}}</button></header><textarea v-model="previewPrompt" rows="3" placeholder="输入中文或英文生图需求"></textarea><div class="preview-choice"><label><input v-model="previewSelection" type="radio" value="original">直接使用原文</label><label><input v-model="previewSelection" type="radio" value="translated">使用转译</label><label><input v-model="previewSelection" type="radio" value="manual">手动编辑后使用</label></div><textarea v-if="previewSelection==='manual'" v-model="manualPrompt" rows="2" placeholder="输入手动调整后的提示词"></textarea><p v-if="previewError" class="preview-error">{{previewError}}</p><div v-if="previewResult" class="preview-result"><span><b>转译</b>{{String((previewResult.translation as any)?.status||'—')}}</span><span><b>审核</b>{{String((previewResult.moderation as any)?.level||'—')}}</span><span><b>路由</b>{{String((previewResult.route_decision as any)?.selected_route||(previewResult.route_decision as any)?.reason||'—')}}</span><p>{{String((previewResult.normalization as any)?.normalized_text||previewResult.selected_prompt||'')}}</p><details><summary>查看完整决策摘要</summary><pre>{{JSON.stringify(previewResult,null,2)}}</pre></details></div></article>
|
<article class="preview-card"><header><div><span>链路预览</span><strong>发送前检查最终提示词与路由</strong></div><button :disabled="previewBusy||!previewPrompt.trim()" @click="runPreview">{{previewBusy?'处理中…':'运行预览'}}</button></header><textarea v-model="previewPrompt" rows="3" placeholder="输入中文或英文生图需求"></textarea><div class="preview-choice"><label><input v-model="previewSelection" type="radio" value="original">直接使用原文</label><label><input v-model="previewSelection" type="radio" value="translated">使用转译</label><label><input v-model="previewSelection" type="radio" value="manual">手动编辑后使用</label></div><textarea v-if="previewSelection==='manual'" v-model="manualPrompt" rows="2" placeholder="输入手动调整后的提示词"></textarea><p v-if="previewError" class="preview-error">{{previewError}}</p><div v-if="previewResult" class="preview-result"><span><b>转译</b>{{String((previewResult.translation as any)?.status||'—')}}</span><span><b>审核</b>{{String((previewResult.moderation as any)?.level||'—')}}</span><span><b>路由</b>{{String((previewResult.route_decision as any)?.selected_route||(previewResult.route_decision as any)?.reason||'—')}}</span><p>{{String((previewResult.normalization as any)?.normalized_text||previewResult.selected_prompt||'')}}</p><details><summary>查看完整决策摘要</summary><pre>{{JSON.stringify(previewResult,null,2)}}</pre></details></div></article>
|
||||||
|
|
||||||
<article class="card"><header><div><span>01 · Prompt Translation</span><strong>LLM 提示词转译</strong><p>用户明确允许后,将中文需求结构化为英文生图提示词;失败时安全回退原文。</p></div><label class="switch"><input type="checkbox" :checked="checked('translation.enabled')" :disabled="disabled" @change="set('translation.enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="grid"><label><span>转译模型路由</span><select :value="String(get('translation.model_route'))" :disabled="disabled" @change="set('translation.model_route',($event.target as HTMLSelectElement).value)"><option value="">未配置(使用原文)</option><option v-for="route in textRoutes" :key="route.value" :value="route.value">{{route.label}}</option></select><small>直接读取 AstrBot 已添加的文本 LLM;建议选择指令遵循稳定、支持结构化 JSON 的模型。</small></label><label><span>模板版本</span><input :value="String(get('translation.template_version','1.0'))" :disabled="disabled" @input="set('translation.template_version',($event.target as HTMLInputElement).value)"><small>便于追踪提示词差异和回滚。</small></label></div><div class="entries"><span>允许自动转译的入口</span><label v-for="item in entrypoints" :key="item.key"><input type="checkbox" :checked="checked(`translation.entrypoints.${item.key}`)" :disabled="disabled" @change="set(`translation.entrypoints.${item.key}`,($event.target as HTMLInputElement).checked)">{{item.label}}</label></div></article>
|
<article class="card"><header><div><span>01 · Prompt Translation</span><strong>LLM 提示词转译</strong><p>用户明确允许后,将中文需求结构化为英文生图提示词;插件路由失败时自动尝试 AstrBot 备用路由,全部失败才安全回退原文。</p></div><label class="switch"><input type="checkbox" :checked="checked('translation.enabled')" :disabled="disabled" @change="set('translation.enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="route-pair source-pair"><label><span><b>1</b> ImageStudio 插件适配器(优先)</span><select :value="routeSource('translation.model_route','plugin')" :disabled="disabled" @change="setRouteSource('translation.model_route','plugin',($event.target as HTMLSelectElement).value)"><option value="">不使用插件路由</option><option v-if="unavailableRoute('translation.model_route','text','plugin')" :value="unavailableRoute('translation.model_route','text','plugin')" disabled>当前不可用:{{unavailableRoute('translation.model_route','text','plugin')}}</option><option v-for="route in routeOptions('text','plugin')" :key="route.value" :value="route.value">{{route.label}}</option></select></label><label><span><b>2</b> AstrBot 模型提供商(备用)</span><select :value="routeSource('translation.model_route','astrbot')" :disabled="disabled" @change="setRouteSource('translation.model_route','astrbot',($event.target as HTMLSelectElement).value)"><option value="">不使用 AstrBot 备用</option><option v-if="unavailableRoute('translation.model_route','text','astrbot')" :value="unavailableRoute('translation.model_route','text','astrbot')" disabled>当前不可用:{{unavailableRoute('translation.model_route','text','astrbot')}}</option><option v-for="route in routeOptions('text','astrbot')" :key="route.value" :value="route.value">{{route.label}}</option></select></label></div><div class="grid"><label><span>模板版本</span><input :value="String(get('translation.template_version','1.0'))" :disabled="disabled" @input="set('translation.template_version',($event.target as HTMLInputElement).value)"><small>便于追踪提示词差异和回滚。</small></label></div><div class="entries"><span>允许自动转译的入口</span><label v-for="item in entrypoints" :key="item.key"><input type="checkbox" :checked="checked(`translation.entrypoints.${item.key}`)" :disabled="disabled" @change="set(`translation.entrypoints.${item.key}`,($event.target as HTMLInputElement).checked)">{{item.label}}</label></div></article>
|
||||||
|
|
||||||
<article class="card"><header><div><span>02 · Moderation</span><strong>生成前内容审核</strong><p>规则审核始终执行;可增加一个 LLM 复核模型,冲突时采用更严格结果。</p></div><label class="switch"><input type="checkbox" :checked="checked('moderation.llm_review_enabled')" :disabled="disabled" @change="set('moderation.llm_review_enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="grid"><label><span>审核模型路由</span><select :value="String(get('moderation.model_route'))" :disabled="disabled" @change="set('moderation.model_route',($event.target as HTMLSelectElement).value)"><option value="">仅使用本地规则</option><option v-for="route in textRoutes" :key="route.value" :value="route.value">{{route.label}}</option></select><small>建议使用对中文语义、年龄和风险分类理解稳定的模型。</small></label><label><span>审核服务失败策略</span><select :value="String(get('moderation.failure_policy','fail_closed'))" :disabled="disabled" @change="set('moderation.failure_policy',($event.target as HTMLSelectElement).value)"><option value="fail_closed">保守拒绝</option><option value="confirm">要求人工确认</option></select><small>审核不可用时不会自动进入宽松模型。</small></label></div></article>
|
<article class="card"><header><div><span>02 · Moderation</span><strong>生成前内容审核</strong><p>规则审核始终执行;LLM 复核按插件优先、AstrBot 备用执行,冲突时采用更严格结果。</p></div><label class="switch"><input type="checkbox" :checked="checked('moderation.llm_review_enabled')" :disabled="disabled" @change="set('moderation.llm_review_enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="route-pair source-pair"><label><span><b>1</b> ImageStudio 插件适配器(优先)</span><select :value="routeSource('moderation.model_route','plugin')" :disabled="disabled" @change="setRouteSource('moderation.model_route','plugin',($event.target as HTMLSelectElement).value)"><option value="">不使用插件路由</option><option v-if="unavailableRoute('moderation.model_route','text','plugin')" :value="unavailableRoute('moderation.model_route','text','plugin')" disabled>当前不可用:{{unavailableRoute('moderation.model_route','text','plugin')}}</option><option v-for="route in routeOptions('text','plugin')" :key="route.value" :value="route.value">{{route.label}}</option></select></label><label><span><b>2</b> AstrBot 模型提供商(备用)</span><select :value="routeSource('moderation.model_route','astrbot')" :disabled="disabled" @change="setRouteSource('moderation.model_route','astrbot',($event.target as HTMLSelectElement).value)"><option value="">不使用 AstrBot 备用</option><option v-if="unavailableRoute('moderation.model_route','text','astrbot')" :value="unavailableRoute('moderation.model_route','text','astrbot')" disabled>当前不可用:{{unavailableRoute('moderation.model_route','text','astrbot')}}</option><option v-for="route in routeOptions('text','astrbot')" :key="route.value" :value="route.value">{{route.label}}</option></select></label></div><div class="grid"><label><span>审核服务失败策略</span><select :value="String(get('moderation.failure_policy','fail_closed'))" :disabled="disabled" @change="set('moderation.failure_policy',($event.target as HTMLSelectElement).value)"><option value="fail_closed">保守拒绝</option><option value="confirm">要求人工确认</option></select><small>两条审核路由都不可用时不会自动进入宽松模型。</small></label></div></article>
|
||||||
|
|
||||||
<article class="card routing"><header><div><span>03 · Dynamic Routing</span><strong>普通 / NSFW 动态模型路由</strong><p>普通内容走安全模型;仅通过审核且权限满足的成人内容可自动进入指定 NSFW 模型。</p></div><label class="switch"><input type="checkbox" :checked="checked('routing.adult_auto_route_enabled')" :disabled="disabled" @change="set('routing.adult_auto_route_enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="route-pair"><label><span>普通生图路由</span><select :value="String(get('routing.safe_route'))" :disabled="disabled" @change="set('routing.safe_route',($event.target as HTMLSelectElement).value)"><option value="">跟随当前默认路由</option><option v-for="route in routes" :key="route.value" :value="route.value">{{route.label}}</option></select></label><div class="arrow">→</div><label><span>NSFW 生图路由</span><select :value="String(get('routing.nsfw_route'))" :disabled="disabled" @change="set('routing.nsfw_route',($event.target as HTMLSelectElement).value)"><option value="">未配置</option><option v-for="route in routes" :key="route.value" :value="route.value">{{route.label}}</option></select></label></div><div class="entries"><span>允许成人内容路由的入口</span><label v-for="item in entrypoints" :key="item.key"><input type="checkbox" :checked="checked(`routing.entrypoints.${item.key}`)" :disabled="disabled" @change="set(`routing.entrypoints.${item.key}`,($event.target as HTMLInputElement).checked)">{{item.label}}</label></div><div class="policy"><b>固定安全策略</b><span>允许的成人内容:审核 + 管理员开关 + 入口权限 + 用户/群聊权限全部通过后自动分流。</span><span>恐怖主义、高危暴力、现实伤害威胁和极端血腥:始终禁止并警告,不进入任何生图模型。</span><span>普通模型仅在明确内容安全拒绝、二次审核为 adult_allowed 时单次回退 NSFW;网络、额度、鉴权和参数错误不会触发。</span></div></article>
|
<article class="card routing"><header><div><span>03 · Dynamic Routing</span><strong>普通 / NSFW 动态模型路由</strong><p>普通内容走安全模型;仅通过审核且权限满足的成人内容可自动进入指定 NSFW 模型。</p></div><label class="switch"><input type="checkbox" :checked="checked('routing.adult_auto_route_enabled')" :disabled="disabled" @change="set('routing.adult_auto_route_enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="route-pair"><label><span>普通生图路由</span><select :value="String(get('routing.safe_route'))" :disabled="disabled" @change="set('routing.safe_route',($event.target as HTMLSelectElement).value)"><option value="">跟随当前默认路由</option><option v-for="route in routes" :key="route.value" :value="route.value">{{route.label}}</option></select></label><div class="arrow">→</div><label><span>NSFW 生图路由</span><select :value="String(get('routing.nsfw_route'))" :disabled="disabled" @change="set('routing.nsfw_route',($event.target as HTMLSelectElement).value)"><option value="">未配置</option><option v-for="route in routes" :key="route.value" :value="route.value">{{route.label}}</option></select></label></div><div class="entries"><span>允许成人内容路由的入口</span><label v-for="item in entrypoints" :key="item.key"><input type="checkbox" :checked="checked(`routing.entrypoints.${item.key}`)" :disabled="disabled" @change="set(`routing.entrypoints.${item.key}`,($event.target as HTMLInputElement).checked)">{{item.label}}</label></div><div class="policy"><b>固定安全策略</b><span>允许的成人内容:审核 + 管理员开关 + 入口权限 + 用户/群聊权限全部通过后自动分流。</span><span>恐怖主义、高危暴力、现实伤害威胁和极端血腥:始终禁止并警告,不进入任何生图模型。</span><span>普通模型仅在明确内容安全拒绝、二次审核为 adult_allowed 时单次回退 NSFW;网络、额度、鉴权和参数错误不会触发。</span></div></article>
|
||||||
|
|
||||||
<article class="card"><header><div><span>04 · Output Review</span><strong>生成后图片审核</strong><p>在聊天返回和普通图库展示前检查结果;异常结果进入受限图库并等待复核。</p></div><label class="switch"><input type="checkbox" :checked="checked('image_moderation.enabled')" :disabled="disabled" @change="set('image_moderation.enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="grid"><label><span>图片审核模型路由</span><select :value="String(get('image_moderation.model_route'))" :disabled="disabled" @change="set('image_moderation.model_route',($event.target as HTMLSelectElement).value)"><option value="">未配置</option><option v-for="route in routes" :key="route.value" :value="route.value">{{route.label}}</option></select><small>需要支持图片理解和结构化风险输出。</small></label><label><span>敏感日志脱敏</span><select :value="String(get('retention.redact_sensitive_logs',true))" :disabled="disabled" @change="set('retention.redact_sensitive_logs',($event.target as HTMLSelectElement).value==='true')"><option value="true">开启</option><option value="false">关闭</option></select></label></div><div class="retention"><label><span>原始提示词</span><input type="number" min="0" :value="Number(get('retention.raw_prompt_days',30))" :disabled="disabled" @input="set('retention.raw_prompt_days',Number(($event.target as HTMLInputElement).value))"><small>天</small></label><label><span>转译提示词</span><input type="number" min="0" :value="Number(get('retention.translated_prompt_days',90))" :disabled="disabled" @input="set('retention.translated_prompt_days',Number(($event.target as HTMLInputElement).value))"><small>天</small></label><label><span>审核记录</span><input type="number" min="0" :value="Number(get('retention.moderation_record_days',180))" :disabled="disabled" @input="set('retention.moderation_record_days',Number(($event.target as HTMLInputElement).value))"><small>天</small></label></div></article>
|
<article class="card"><header><div><span>04 · Output Review</span><strong>生成后图片审核</strong><p>在聊天返回和普通图库展示前检查结果;插件视觉模型失败时自动尝试 AstrBot 备用视觉模型。</p></div><label class="switch"><input type="checkbox" :checked="checked('image_moderation.enabled')" :disabled="disabled" @change="set('image_moderation.enabled',($event.target as HTMLInputElement).checked)"><span></span></label></header><div class="route-pair source-pair"><label><span><b>1</b> ImageStudio 视觉适配器(优先)</span><select :value="routeSource('image_moderation.model_route','plugin')" :disabled="disabled" @change="setRouteSource('image_moderation.model_route','plugin',($event.target as HTMLSelectElement).value)"><option value="">不使用插件视觉路由</option><option v-if="unavailableRoute('image_moderation.model_route','vision','plugin')" :value="unavailableRoute('image_moderation.model_route','vision','plugin')" disabled>当前不可用:{{unavailableRoute('image_moderation.model_route','vision','plugin')}}</option><option v-for="route in routeOptions('vision','plugin')" :key="route.value" :value="route.value">{{route.label}}</option></select></label><label><span><b>2</b> AstrBot 视觉提供商(备用)</span><select :value="routeSource('image_moderation.model_route','astrbot')" :disabled="disabled" @change="setRouteSource('image_moderation.model_route','astrbot',($event.target as HTMLSelectElement).value)"><option value="">不使用 AstrBot 备用</option><option v-if="unavailableRoute('image_moderation.model_route','vision','astrbot')" :value="unavailableRoute('image_moderation.model_route','vision','astrbot')" disabled>当前不可用:{{unavailableRoute('image_moderation.model_route','vision','astrbot')}}</option><option v-for="route in routeOptions('vision','astrbot')" :key="route.value" :value="route.value">{{route.label}}</option></select></label></div><small class="vision-note">AstrBot 备用模型必须真实支持图片输入;运行时通过 image_urls 调用。</small><div class="grid"><label><span>敏感日志脱敏</span><select :value="String(get('retention.redact_sensitive_logs',true))" :disabled="disabled" @change="set('retention.redact_sensitive_logs',($event.target as HTMLSelectElement).value==='true')"><option value="true">开启</option><option value="false">关闭</option></select></label></div><div class="retention"><label><span>原始提示词</span><input type="number" min="0" :value="Number(get('retention.raw_prompt_days',30))" :disabled="disabled" @input="set('retention.raw_prompt_days',Number(($event.target as HTMLInputElement).value))"><small>天</small></label><label><span>转译提示词</span><input type="number" min="0" :value="Number(get('retention.translated_prompt_days',90))" :disabled="disabled" @input="set('retention.translated_prompt_days',Number(($event.target as HTMLInputElement).value))"><small>天</small></label><label><span>审核记录</span><input type="number" min="0" :value="Number(get('retention.moderation_record_days',180))" :disabled="disabled" @input="set('retention.moderation_record_days',Number(($event.target as HTMLInputElement).value))"><small>天</small></label></div></article>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.governance{display:grid;gap:13px}.intro,.card{border:1px solid var(--border);border-radius:10px;background:var(--panel-muted)}.intro{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:16px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.intro>div:first-child,.card header>div{display:grid;gap:4px}.intro span,.card header span,.entries>span{color:var(--text-soft);font-size:11px;font-weight:800}.intro p,.card p,.grid small{margin:0;color:var(--text-soft);font-size:12px;line-height:1.5}.flow{display:flex;align-items:center;gap:6px;white-space:nowrap}.flow b{border-radius:6px;padding:6px 8px;color:var(--primary);background:var(--panel)}.flow i{color:var(--text-soft);font-style:normal}.card{display:grid;gap:14px;padding:15px}.card>header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.grid label,.route-pair label{display:grid;gap:6px}.grid label>span,.route-pair label>span,.retention span{font-size:12px;font-weight:750}select,input{width:100%;min-height:40px;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:0 10px;color:var(--text);background:var(--panel)}.switch input{position:absolute;opacity:0;pointer-events:none}.switch span{position:relative;display:block;width:44px;height:25px;border-radius:99px;background:var(--border);cursor:pointer}.switch span:after{position:absolute;top:3px;left:3px;width:19px;height:19px;border-radius:50%;background:#fff;content:"";transition:.18s}.switch input:checked+span{background:var(--primary)}.switch input:checked+span:after{transform:translateX(19px)}.entries{display:flex;align-items:center;flex-wrap:wrap;gap:10px;border-top:1px solid var(--border);padding-top:12px}.entries label{display:flex;align-items:center;gap:5px;font-size:12px}.entries input{width:auto;min-height:auto}.route-pair{display:grid;grid-template-columns:1fr 36px 1fr;align-items:end;gap:8px}.arrow{display:grid;place-items:center;min-height:40px;color:var(--primary);font-size:20px}.routing{border-color:color-mix(in srgb,var(--primary) 35%,var(--border))}.policy{display:grid;gap:6px;border-left:3px solid #d39b35;border-radius:6px;padding:11px 12px;background:color-mix(in srgb,#e1a53a 10%,var(--panel))}.policy b{color:#9a6818}.policy span{color:var(--text-soft);font-size:12px;line-height:1.45}.retention{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.retention label{display:grid;grid-template-columns:1fr 72px auto;align-items:center;gap:7px}.retention small{color:var(--text-soft)}@media(max-width:800px){.intro{align-items:flex-start;flex-direction:column}.flow{flex-wrap:wrap}.grid,.route-pair,.retention{grid-template-columns:1fr}.arrow{transform:rotate(90deg)}}
|
.governance{display:grid;gap:13px}.intro,.card{border:1px solid var(--border);border-radius:10px;background:var(--panel-muted)}.intro{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:16px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.intro>div:first-child,.card header>div{display:grid;gap:4px}.intro span,.card header span,.entries>span{color:var(--text-soft);font-size:11px;font-weight:800}.intro p,.card p,.grid small{margin:0;color:var(--text-soft);font-size:12px;line-height:1.5}.flow{display:flex;align-items:center;gap:6px;white-space:nowrap}.flow b{border-radius:6px;padding:6px 8px;color:var(--primary);background:var(--panel)}.flow i{color:var(--text-soft);font-style:normal}.card{display:grid;gap:14px;padding:15px}.card>header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.grid label,.route-pair label{display:grid;gap:6px}.grid label>span,.route-pair label>span,.retention span{font-size:12px;font-weight:750}.source-pair{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.source-pair label>span b{display:inline-grid;place-items:center;width:18px;height:18px;margin-right:4px;border-radius:50%;color:#fff;background:var(--primary);font-size:10px}.vision-note{color:var(--text-soft);font-size:11px}select,input{width:100%;min-height:40px;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:0 10px;color:var(--text);background:var(--panel)}.switch input{position:absolute;opacity:0;pointer-events:none}.switch span{position:relative;display:block;width:44px;height:25px;border-radius:99px;background:var(--border);cursor:pointer}.switch span:after{position:absolute;top:3px;left:3px;width:19px;height:19px;border-radius:50%;background:#fff;content:"";transition:.18s}.switch input:checked+span{background:var(--primary)}.switch input:checked+span:after{transform:translateX(19px)}.entries{display:flex;align-items:center;flex-wrap:wrap;gap:10px;border-top:1px solid var(--border);padding-top:12px}.entries label{display:flex;align-items:center;gap:5px;font-size:12px}.entries input{width:auto;min-height:auto}.route-pair{display:grid;grid-template-columns:1fr 36px 1fr;align-items:end;gap:8px}.arrow{display:grid;place-items:center;min-height:40px;color:var(--primary);font-size:20px}.routing{border-color:color-mix(in srgb,var(--primary) 35%,var(--border))}.policy{display:grid;gap:6px;border:1px solid color-mix(in srgb,#d39b35 48%,var(--border));border-radius:6px;padding:11px 12px;background:color-mix(in srgb,#e1a53a 10%,var(--panel))}.policy b{color:#9a6818}.policy span{color:var(--text-soft);font-size:12px;line-height:1.45}.retention{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.retention label{display:grid;grid-template-columns:1fr 72px auto;align-items:center;gap:7px}.retention small{color:var(--text-soft)}@media(max-width:800px){.intro{align-items:flex-start;flex-direction:column}.flow{flex-wrap:wrap}.grid,.route-pair,.retention{grid-template-columns:1fr}.arrow{transform:rotate(90deg)}}
|
||||||
.preview-card{display:grid;gap:10px;border:1px solid var(--border);border-radius:10px;padding:15px;background:var(--panel-muted)}.preview-card>header{display:flex;align-items:center;justify-content:space-between;gap:12px}.preview-card>header>div{display:grid;gap:3px}.preview-card>header span{color:var(--text-soft);font-size:11px;font-weight:800}.preview-card button{min-height:36px;border:1px solid var(--primary);border-radius:7px;padding:0 11px;color:#fff;background:var(--primary);cursor:pointer}.preview-card button:disabled{opacity:.5}.preview-card textarea{width:100%;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:9px;color:var(--text);background:var(--panel);font:inherit;resize:vertical}.preview-choice{display:flex;flex-wrap:wrap;gap:10px}.preview-choice label{display:flex;align-items:center;gap:5px;font-size:12px}.preview-result{display:grid;grid-template-columns:repeat(3,1fr);gap:7px;border-top:1px solid var(--border);padding-top:10px}.preview-result>span{display:grid;gap:3px;border-radius:6px;padding:8px;background:var(--panel)}.preview-result>span b{color:var(--text-soft);font-size:10px}.preview-result>p,.preview-result>details{grid-column:1/-1}.preview-result>p{margin:0;border-radius:6px;padding:9px;background:var(--panel);font-size:12px;line-height:1.5}.preview-result pre{max-height:260px;overflow:auto;border-radius:6px;padding:8px;background:var(--panel);font-size:10px;white-space:pre-wrap}.preview-error{color:var(--danger)!important}
|
.preview-card{display:grid;gap:10px;border:1px solid var(--border);border-radius:10px;padding:15px;background:var(--panel-muted)}.preview-card>header{display:flex;align-items:center;justify-content:space-between;gap:12px}.preview-card>header>div{display:grid;gap:3px}.preview-card>header span{color:var(--text-soft);font-size:11px;font-weight:800}.preview-card button{min-height:36px;border:1px solid var(--primary);border-radius:7px;padding:0 11px;color:#fff;background:var(--primary);cursor:pointer}.preview-card button:disabled{opacity:.5}.preview-card textarea{width:100%;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:9px;color:var(--text);background:var(--panel);font:inherit;resize:vertical}.preview-choice{display:flex;flex-wrap:wrap;gap:10px}.preview-choice label{display:flex;align-items:center;gap:5px;font-size:12px}.preview-result{display:grid;grid-template-columns:repeat(3,1fr);gap:7px;border-top:1px solid var(--border);padding-top:10px}.preview-result>span{display:grid;gap:3px;border-radius:6px;padding:8px;background:var(--panel)}.preview-result>span b{color:var(--text-soft);font-size:10px}.preview-result>p,.preview-result>details{grid-column:1/-1}.preview-result>p{margin:0;border-radius:6px;padding:9px;background:var(--panel);font-size:12px;line-height:1.5}.preview-result pre{max-height:260px;overflow:auto;border-radius:6px;padding:8px;background:var(--panel);font-size:10px;white-space:pre-wrap}.preview-error{color:var(--danger)!important}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { computed, onMounted, ref } from "vue"
|
||||||
import { getJson } from "../../../../shared/api/client"
|
import { getJson } from "../../../../shared/api/client"
|
||||||
import { endpoints } from "../../../../shared/api/endpoints"
|
import { endpoints } from "../../../../shared/api/endpoints"
|
||||||
import type { MaterialCategory } from "../../../../shared/types/material"
|
import type { MaterialCategory } from "../../../../shared/types/material"
|
||||||
|
import { materialCategoryLabel } from "../../material-labels"
|
||||||
|
|
||||||
type Requirement = { category: string; requirement: string; enabled: boolean }
|
type Requirement = { category: string; requirement: string; enabled: boolean }
|
||||||
const props = defineProps<{ modelValue: Record<string, unknown>; disabled: boolean }>()
|
const props = defineProps<{ modelValue: Record<string, unknown>; disabled: boolean }>()
|
||||||
|
|
@ -32,7 +33,9 @@ function addRequirement() { emit("update:modelValue", { ...props.modelValue, cat
|
||||||
function removeRequirement(index: number) { emit("update:modelValue", { ...props.modelValue, category_requirements: requirements.value.filter((_, itemIndex) => itemIndex !== index) }) }
|
function removeRequirement(index: number) { emit("update:modelValue", { ...props.modelValue, category_requirements: requirements.value.filter((_, itemIndex) => itemIndex !== index) }) }
|
||||||
function categoryLabel(category: MaterialCategory) {
|
function categoryLabel(category: MaterialCategory) {
|
||||||
const parent = categories.value.find(item => item.category_id === category.parent_id)
|
const parent = categories.value.find(item => item.category_id === category.parent_id)
|
||||||
return parent ? `${parent.name} / ${category.name}` : category.name
|
return parent
|
||||||
|
? `${materialCategoryLabel(parent.name)} / ${materialCategoryLabel(category.name)}`
|
||||||
|
: materialCategoryLabel(category.name)
|
||||||
}
|
}
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
try { categories.value = await getJson<MaterialCategory[]>(endpoints.materialCategories) }
|
try { categories.value = await getJson<MaterialCategory[]>(endpoints.materialCategories) }
|
||||||
|
|
|
||||||
文件差异因一行或多行过长而隐藏
|
|
@ -0,0 +1,39 @@
|
||||||
|
export const MODEL_ROUTE_CHAIN_PREFIX = "route-chain:"
|
||||||
|
|
||||||
|
export type ModelRouteChain = {
|
||||||
|
plugin: string
|
||||||
|
astrbot: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseModelRouteChain(value: unknown): ModelRouteChain {
|
||||||
|
const route = String(value ?? "").trim()
|
||||||
|
if (!route) return { plugin: "", astrbot: "" }
|
||||||
|
if (route.startsWith(MODEL_ROUTE_CHAIN_PREFIX)) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(route.slice(MODEL_ROUTE_CHAIN_PREFIX.length)) as Record<string, unknown>
|
||||||
|
return {
|
||||||
|
plugin: String(parsed.plugin ?? "").trim(),
|
||||||
|
astrbot: astrbotRoute(parsed.astrbot),
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Preserve malformed legacy input visibly in the plugin slot.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return route.startsWith("astrbot:")
|
||||||
|
? { plugin: "", astrbot: route }
|
||||||
|
: { plugin: route, astrbot: "" }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeModelRouteChain(chain: ModelRouteChain): string {
|
||||||
|
const plugin = String(chain.plugin ?? "").trim()
|
||||||
|
const astrbot = astrbotRoute(chain.astrbot)
|
||||||
|
if (plugin && !astrbot) return plugin
|
||||||
|
if (astrbot && !plugin) return astrbot
|
||||||
|
if (!plugin && !astrbot) return ""
|
||||||
|
return `${MODEL_ROUTE_CHAIN_PREFIX}${JSON.stringify({ astrbot, plugin })}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function astrbotRoute(value: unknown): string {
|
||||||
|
const route = String(value ?? "").trim()
|
||||||
|
return !route || route.startsWith("astrbot:") ? route : ""
|
||||||
|
}
|
||||||
|
|
@ -243,7 +243,7 @@ function shortValue(value: string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-branch-strip > button.current {
|
.workflow-branch-strip > button.current {
|
||||||
box-shadow: inset 3px 0 0 var(--primary);
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.workflow-branch-strip > button:disabled:not(.current) {
|
.workflow-branch-strip > button:disabled:not(.current) {
|
||||||
|
|
|
||||||
|
|
@ -78,7 +78,9 @@ const visibleMaterials = computed(() => {
|
||||||
})
|
})
|
||||||
.sort((left, right) => {
|
.sort((left, right) => {
|
||||||
const selectedDifference = Number(selectedSet.value.has(right.material_id)) - Number(selectedSet.value.has(left.material_id))
|
const selectedDifference = Number(selectedSet.value.has(right.material_id)) - Number(selectedSet.value.has(left.material_id))
|
||||||
return selectedDifference || right.updated_at.localeCompare(left.updated_at)
|
const advancedDifference = Number(isAdvancedMaterial(right)) - Number(isAdvancedMaterial(left))
|
||||||
|
const priorityDifference = materialPriority(right) - materialPriority(left)
|
||||||
|
return selectedDifference || advancedDifference || priorityDifference || right.updated_at.localeCompare(left.updated_at)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
const dirty = computed(() => normalizedIds(draftSelectedIds.value).join("|") !== normalizedIds(props.selectedMaterialIds).join("|"))
|
const dirty = computed(() => normalizedIds(draftSelectedIds.value).join("|") !== normalizedIds(props.selectedMaterialIds).join("|"))
|
||||||
|
|
@ -123,6 +125,14 @@ function materialImage(material: Material) {
|
||||||
function categoryLabel(material: Material) {
|
function categoryLabel(material: Material) {
|
||||||
return material.category_id ? categoryNameById.value.get(material.category_id) || "未分类" : "未分类"
|
return material.category_id ? categoryNameById.value.get(material.category_id) || "未分类" : "未分类"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isAdvancedMaterial(material: Material) {
|
||||||
|
return material.metadata?.advanced_material === true || material.metadata?.material_type === "advanced"
|
||||||
|
}
|
||||||
|
|
||||||
|
function materialPriority(material: Material) {
|
||||||
|
return Number(material.metadata?.catalog_priority || 0)
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
@ -210,7 +220,7 @@ function categoryLabel(material: Material) {
|
||||||
<b v-if="selectedSet.has(material.material_id)">已选</b>
|
<b v-if="selectedSet.has(material.material_id)">已选</b>
|
||||||
</span>
|
</span>
|
||||||
<span class="workflow-material-drawer-copy">
|
<span class="workflow-material-drawer-copy">
|
||||||
<small>{{ categoryLabel(material) }}</small>
|
<small>{{ isAdvancedMaterial(material) ? "进阶优先 · " : "" }}{{ categoryLabel(material) }}</small>
|
||||||
<strong>{{ material.display_name }}</strong>
|
<strong>{{ material.display_name }}</strong>
|
||||||
<em>{{ material.prompt || "已确认,可作为图片参考" }}</em>
|
<em>{{ material.prompt || "已确认,可作为图片参考" }}</em>
|
||||||
</span>
|
</span>
|
||||||
|
|
|
||||||
|
|
@ -26,3 +26,20 @@ export function materialBodySlotLabel(value: unknown) {
|
||||||
const key = String(value ?? "").trim()
|
const key = String(value ?? "").trim()
|
||||||
return MATERIAL_BODY_SLOT_LABELS.get(key) ?? key
|
return MATERIAL_BODY_SLOT_LABELS.get(key) ?? key
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MATERIAL_CATEGORY_LABELS = new Map<string, string>([
|
||||||
|
["top", "上装"],
|
||||||
|
["bottom", "下装"],
|
||||||
|
["dress", "连衣裙"],
|
||||||
|
["shoes", "鞋履"],
|
||||||
|
["accessory", "配饰"],
|
||||||
|
["style", "风格"],
|
||||||
|
["composition", "构图"],
|
||||||
|
["outfit", "服装"],
|
||||||
|
])
|
||||||
|
|
||||||
|
/** Keep backend category names stable while presenting built-in labels in Chinese. */
|
||||||
|
export function materialCategoryLabel(value: unknown) {
|
||||||
|
const key = String(value ?? "").trim()
|
||||||
|
return MATERIAL_CATEGORY_LABELS.get(key.toLowerCase()) ?? key
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
:root {
|
||||||
|
--ui-space-1: 4px;
|
||||||
|
--ui-space-2: 8px;
|
||||||
|
--ui-space-3: 12px;
|
||||||
|
--ui-space-4: 16px;
|
||||||
|
--ui-space-5: 20px;
|
||||||
|
--ui-space-6: 24px;
|
||||||
|
--ui-radius-sm: 6px;
|
||||||
|
--ui-radius-md: 8px;
|
||||||
|
--ui-radius-lg: 10px;
|
||||||
|
--ui-border-subtle: color-mix(in srgb, currentColor 14%, transparent);
|
||||||
|
--ui-focus-ring: 0 0 0 3px color-mix(in srgb, var(--primary) 28%, transparent);
|
||||||
|
--ui-shadow-soft: 0 8px 20px color-mix(in srgb, var(--bg) 22%, transparent);
|
||||||
|
--ui-duration-fast: 140ms;
|
||||||
|
--ui-duration-normal: 180ms;
|
||||||
|
--ui-ease-standard: cubic-bezier(0.2, 0, 0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
:root {
|
||||||
|
--ui-duration-fast: 0ms;
|
||||||
|
--ui-duration-normal: 0ms;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,457 @@
|
||||||
|
.navigation-shell {
|
||||||
|
--workbench-pad: 20px;
|
||||||
|
background: var(--bg);
|
||||||
|
background-image: none;
|
||||||
|
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell button,
|
||||||
|
.navigation-shell input,
|
||||||
|
.navigation-shell select,
|
||||||
|
.navigation-shell textarea {
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell button:focus-visible,
|
||||||
|
.navigation-shell input:focus-visible,
|
||||||
|
.navigation-shell select:focus-visible,
|
||||||
|
.navigation-shell textarea:focus-visible,
|
||||||
|
.navigation-shell [tabindex]:focus-visible {
|
||||||
|
outline: none;
|
||||||
|
box-shadow: var(--ui-focus-ring);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell button:hover:not(:disabled),
|
||||||
|
.navigation-shell button:focus-visible:not(:disabled) {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 46%, var(--border));
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail {
|
||||||
|
background: var(--bg-soft);
|
||||||
|
backdrop-filter: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-mark {
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar {
|
||||||
|
background: var(--panel);
|
||||||
|
backdrop-filter: none;
|
||||||
|
border-bottom-color: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell[data-theme="light"] .topbar {
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel,
|
||||||
|
.overview-strip,
|
||||||
|
.detail-hero,
|
||||||
|
.generate-hero,
|
||||||
|
.materials-hero,
|
||||||
|
.signal-card,
|
||||||
|
.metric-card,
|
||||||
|
.queue-board-panel,
|
||||||
|
.queue-detail-panel,
|
||||||
|
.materials-library-panel,
|
||||||
|
.materials-action-card,
|
||||||
|
.materials-category-chip,
|
||||||
|
.state-card,
|
||||||
|
.empty-state,
|
||||||
|
.quick-profile-profile-card,
|
||||||
|
.quick-profile-image-panel,
|
||||||
|
.quick-profile-command-panel,
|
||||||
|
.quick-profile-library,
|
||||||
|
.quick-profile-material-panel,
|
||||||
|
.workflow-panel,
|
||||||
|
.workflow-detail-panel,
|
||||||
|
.workflow-preview-panel,
|
||||||
|
.settings-section,
|
||||||
|
.logs-panel {
|
||||||
|
border-radius: var(--ui-radius-lg);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel,
|
||||||
|
.overview-strip,
|
||||||
|
.detail-hero,
|
||||||
|
.generate-hero,
|
||||||
|
.materials-hero,
|
||||||
|
.queue-board-panel,
|
||||||
|
.queue-detail-panel,
|
||||||
|
.materials-library-panel,
|
||||||
|
.quick-profile-profile-card,
|
||||||
|
.quick-profile-image-panel,
|
||||||
|
.quick-profile-command-panel,
|
||||||
|
.quick-profile-library,
|
||||||
|
.quick-profile-material-panel,
|
||||||
|
.workflow-panel,
|
||||||
|
.workflow-detail-panel,
|
||||||
|
.workflow-preview-panel,
|
||||||
|
.settings-section,
|
||||||
|
.logs-panel {
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.signal-card::before,
|
||||||
|
.metric-card::before,
|
||||||
|
.queue-action-card::before,
|
||||||
|
.workflow-draft-grid > article.final::before {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signal-card.good,
|
||||||
|
.metric-card.good,
|
||||||
|
.signal-card.warn,
|
||||||
|
.metric-card.warn,
|
||||||
|
.signal-card.bad,
|
||||||
|
.metric-card.bad,
|
||||||
|
.signal-card.idle,
|
||||||
|
.metric-card.idle {
|
||||||
|
border-color: var(--border);
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.signal-card.good,
|
||||||
|
.metric-card.good { border-color: color-mix(in srgb, var(--accent) 52%, var(--border)); }
|
||||||
|
.signal-card.warn,
|
||||||
|
.metric-card.warn { border-color: color-mix(in srgb, var(--warn) 52%, var(--border)); }
|
||||||
|
.signal-card.bad,
|
||||||
|
.metric-card.bad { border-color: color-mix(in srgb, var(--danger) 52%, var(--border)); }
|
||||||
|
|
||||||
|
.panel header,
|
||||||
|
.overview-strip > header,
|
||||||
|
.generate-hero > header,
|
||||||
|
.materials-hero > header,
|
||||||
|
.queue-board-panel > header,
|
||||||
|
.materials-library-panel > header {
|
||||||
|
gap: var(--ui-space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell h1,
|
||||||
|
.navigation-shell h2,
|
||||||
|
.navigation-shell h3,
|
||||||
|
.navigation-shell strong {
|
||||||
|
text-wrap: balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell p,
|
||||||
|
.navigation-shell dd,
|
||||||
|
.navigation-shell .panel-copy,
|
||||||
|
.navigation-shell .empty-state span {
|
||||||
|
text-wrap: pretty;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell input,
|
||||||
|
.navigation-shell select,
|
||||||
|
.navigation-shell textarea {
|
||||||
|
min-height: 38px;
|
||||||
|
border-color: var(--border);
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell input::placeholder,
|
||||||
|
.navigation-shell textarea::placeholder {
|
||||||
|
color: var(--text-soft);
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell .primary-button,
|
||||||
|
.navigation-shell button.primary,
|
||||||
|
.navigation-shell .quick-create {
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell .state-card,
|
||||||
|
.navigation-shell .empty-state {
|
||||||
|
border-color: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell .state-card.good,
|
||||||
|
.navigation-shell .state-card.warn,
|
||||||
|
.navigation-shell .state-card.bad,
|
||||||
|
.navigation-shell .state-card.info {
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1180px) {
|
||||||
|
.navigation-shell {
|
||||||
|
--workbench-pad: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar {
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.navigation-shell {
|
||||||
|
--workbench-pad: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar {
|
||||||
|
padding-top: 14px;
|
||||||
|
padding-bottom: 14px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.navigation-shell *,
|
||||||
|
.navigation-shell *::before,
|
||||||
|
.navigation-shell *::after {
|
||||||
|
animation-duration: 0.001ms !important;
|
||||||
|
animation-iteration-count: 1 !important;
|
||||||
|
scroll-behavior: auto !important;
|
||||||
|
transition-duration: 0.001ms !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.generate-page,
|
||||||
|
.profiles-page,
|
||||||
|
.materials-page,
|
||||||
|
.settings-page,
|
||||||
|
.logs-page,
|
||||||
|
.performance-detail-page,
|
||||||
|
.queue-page,
|
||||||
|
.workflow-workspace,
|
||||||
|
.quick-profile-workspace {
|
||||||
|
gap: var(--ui-space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.generate-hero,
|
||||||
|
.queue-hero,
|
||||||
|
.profiles-workspace,
|
||||||
|
.materials-workbench,
|
||||||
|
.settings-page > .hero,
|
||||||
|
.logs-hero,
|
||||||
|
.performance-detail-page > header {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.generate-mode-actions,
|
||||||
|
.materials-view-tabs,
|
||||||
|
.materials-filter-strip,
|
||||||
|
.materials-subfilter-strip,
|
||||||
|
.queue-filter-tabs,
|
||||||
|
.profile-tabs,
|
||||||
|
.detail-tabs,
|
||||||
|
.logs-toolbar,
|
||||||
|
.workflow-section-header,
|
||||||
|
.workflow-round-toolbar {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
background: var(--panel-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.generate-mode-button,
|
||||||
|
.materials-view-tabs button,
|
||||||
|
.queue-filter-tabs button,
|
||||||
|
.profile-tabs button,
|
||||||
|
.detail-tabs button,
|
||||||
|
.workflow-round-toolbar button {
|
||||||
|
border-radius: var(--ui-radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.generate-mode-button.active,
|
||||||
|
.materials-view-tabs button.active,
|
||||||
|
.queue-filter-tabs button.active,
|
||||||
|
.profile-tabs button.active,
|
||||||
|
.detail-tabs button.active {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 48%, var(--border));
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--primary-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-generation-workspace,
|
||||||
|
.performance-detail-grid,
|
||||||
|
.queue-workbench,
|
||||||
|
.materials-workbench,
|
||||||
|
.profiles-workspace,
|
||||||
|
.settings-page .workspace,
|
||||||
|
.logs-workspace,
|
||||||
|
.workflow-layout {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-panel,
|
||||||
|
.image-display-panel,
|
||||||
|
.image-info-card,
|
||||||
|
.performance-summary-panel,
|
||||||
|
.performance-breakdown,
|
||||||
|
.queue-board-panel,
|
||||||
|
.queue-detail-panel,
|
||||||
|
.queue-actions-panel,
|
||||||
|
.materials-library-panel,
|
||||||
|
.materials-actions-panel,
|
||||||
|
.profile-master,
|
||||||
|
.profile-detail,
|
||||||
|
.detail-content,
|
||||||
|
.settings-page section,
|
||||||
|
.logs-stream,
|
||||||
|
.workflow-preview-panel,
|
||||||
|
.workflow-detail-panel,
|
||||||
|
.workflow-candidate-pool,
|
||||||
|
.workflow-dependency-card,
|
||||||
|
.workflow-round-panel,
|
||||||
|
.workflow-material-drawer,
|
||||||
|
.workflow-composer-panel {
|
||||||
|
border-color: var(--border);
|
||||||
|
border-radius: var(--ui-radius-lg);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-panel,
|
||||||
|
.image-display-panel,
|
||||||
|
.image-info-card,
|
||||||
|
.performance-summary-panel,
|
||||||
|
.performance-breakdown,
|
||||||
|
.queue-board-panel,
|
||||||
|
.queue-detail-panel,
|
||||||
|
.queue-actions-panel,
|
||||||
|
.materials-library-panel,
|
||||||
|
.materials-actions-panel,
|
||||||
|
.profile-master,
|
||||||
|
.profile-detail,
|
||||||
|
.detail-content,
|
||||||
|
.settings-page section,
|
||||||
|
.logs-stream,
|
||||||
|
.workflow-preview-panel,
|
||||||
|
.workflow-detail-panel,
|
||||||
|
.workflow-candidate-pool,
|
||||||
|
.workflow-dependency-card,
|
||||||
|
.workflow-round-panel,
|
||||||
|
.workflow-material-drawer,
|
||||||
|
.workflow-composer-panel {
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-card,
|
||||||
|
.queue-task-card,
|
||||||
|
.queue-list li,
|
||||||
|
.materials-library-card,
|
||||||
|
.materials-action-card,
|
||||||
|
.profile-list-item,
|
||||||
|
.workflow-candidate-card,
|
||||||
|
.workflow-round-card,
|
||||||
|
.workflow-group-card,
|
||||||
|
.workflow-material-bind-card,
|
||||||
|
.workflow-prompt-plan-card,
|
||||||
|
.workflow-branch-panel,
|
||||||
|
.workflow-chat-panel {
|
||||||
|
border-color: var(--border);
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
background: var(--panel-muted);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-card:hover,
|
||||||
|
.image-preview-card.active,
|
||||||
|
.queue-task-card:hover,
|
||||||
|
.queue-list li:hover,
|
||||||
|
.materials-library-card:hover,
|
||||||
|
.profile-list-item:hover,
|
||||||
|
.profile-list-item.active,
|
||||||
|
.workflow-candidate-card:hover,
|
||||||
|
.workflow-round-card:hover {
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 44%, var(--border));
|
||||||
|
background: color-mix(in srgb, var(--primary-soft) 20%, var(--panel-muted));
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-stage,
|
||||||
|
.image-stage-empty,
|
||||||
|
.image-preview-empty,
|
||||||
|
.detail-empty,
|
||||||
|
.profile-detail-empty,
|
||||||
|
.logs-empty,
|
||||||
|
.workflow-candidate-empty,
|
||||||
|
.workflow-round-empty,
|
||||||
|
.workflow-dependency-empty {
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
border-color: var(--border);
|
||||||
|
background: var(--panel-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-stage-button,
|
||||||
|
.quick-create,
|
||||||
|
.quick-profile-hero-button,
|
||||||
|
.quick-profile-portrait-button,
|
||||||
|
.materials-primary-add,
|
||||||
|
.workflow-review-trigger,
|
||||||
|
.workflow-compare-trigger {
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-pill,
|
||||||
|
.queue-task-status,
|
||||||
|
.workflow-status-pill,
|
||||||
|
.profile-status-pill,
|
||||||
|
.material-status-pill {
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell table {
|
||||||
|
border-collapse: separate;
|
||||||
|
border-spacing: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--ui-radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell th,
|
||||||
|
.navigation-shell td {
|
||||||
|
border-color: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell :is(.dialog, .drawer, [class*="-dialog"], [class*="-drawer"]) {
|
||||||
|
border-radius: var(--ui-radius-lg);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell :is(.dialog, .drawer, [class*="-dialog"], [class*="-drawer"]) > header,
|
||||||
|
.navigation-shell :is(.dialog, .drawer, [class*="-dialog"], [class*="-drawer"]) > footer {
|
||||||
|
border-color: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1180px) {
|
||||||
|
.image-generation-workspace,
|
||||||
|
.performance-detail-grid,
|
||||||
|
.queue-workbench,
|
||||||
|
.materials-workbench,
|
||||||
|
.profiles-workspace,
|
||||||
|
.workflow-layout {
|
||||||
|
gap: var(--ui-space-3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@media (max-width: 1360px) and (min-width: 901px) {
|
||||||
|
.overview-strip {
|
||||||
|
grid-template-columns: minmax(220px, 1.2fr) repeat(3, minmax(120px, 0.8fr)) minmax(200px, 0.9fr);
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-strip > * {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1360px) and (min-width: 901px) {
|
||||||
|
.navigation-shell .overview-strip {
|
||||||
|
grid-template-columns: minmax(220px, 1.2fr) repeat(3, minmax(120px, 0.8fr)) minmax(200px, 0.9fr);
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navigation-shell .overview-strip > * {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1180px) {
|
||||||
|
.navigation-shell .overview-strip {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,122 @@
|
||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { readFile } from "node:fs/promises"
|
||||||
|
import test from "node:test"
|
||||||
|
|
||||||
|
const pagePath = new URL(
|
||||||
|
"../standalone-web/src/features/materials/AdvancedMaterialImportPage.vue",
|
||||||
|
import.meta.url,
|
||||||
|
)
|
||||||
|
const typesPath = new URL("../shared/types/advanced-material.ts", import.meta.url)
|
||||||
|
const endpointsPath = new URL("../shared/api/endpoints.ts", import.meta.url)
|
||||||
|
const appPath = new URL("../standalone-web/src/App.vue", import.meta.url)
|
||||||
|
|
||||||
|
test("omits an unknown upload MIME type instead of claiming the image is PNG", async () => {
|
||||||
|
const [page, types] = await Promise.all([
|
||||||
|
readFile(pagePath, "utf8"),
|
||||||
|
readFile(typesPath, "utf8"),
|
||||||
|
])
|
||||||
|
|
||||||
|
assert.match(types, /content_type\?: string/)
|
||||||
|
assert.match(types, /fidelity_score\?: number \| null/)
|
||||||
|
assert.match(page, /const declaredContentType = uploadFile\.value\.type\.trim\(\)/)
|
||||||
|
assert.match(
|
||||||
|
page,
|
||||||
|
/\.\.\.\(declaredContentType \? \{ content_type: declaredContentType \} : \{\}\)/,
|
||||||
|
)
|
||||||
|
assert.doesNotMatch(
|
||||||
|
page,
|
||||||
|
/content_type:\s*uploadFile\.value\.type\s*\|\|\s*["']image\/png["']/,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("enables 2-8 image style sets without replacing the legacy single-image upload", async () => {
|
||||||
|
const [page, types, endpoints] = await Promise.all([
|
||||||
|
readFile(pagePath, "utf8"),
|
||||||
|
readFile(typesPath, "utf8"),
|
||||||
|
readFile(endpointsPath, "utf8"),
|
||||||
|
])
|
||||||
|
|
||||||
|
assert.match(page, /const MIN_STYLE_IMAGES = 2/)
|
||||||
|
assert.match(page, /const MAX_STYLE_IMAGES = 8/)
|
||||||
|
assert.match(page, /styleSetUploadEnabled/)
|
||||||
|
assert.match(page, /endpoints\.advancedMaterialStyleSetUpload/)
|
||||||
|
assert.match(page, /endpoints\.advancedMaterialImportUpload/)
|
||||||
|
assert.match(page, /Promise\.all\(accepted\.map/)
|
||||||
|
assert.match(page, /0 张参考图/)
|
||||||
|
assert.match(page, /styleValidationCases\.value\.length === 3/)
|
||||||
|
assert.match(types, /interface AdvancedStyleSource/)
|
||||||
|
assert.match(types, /interface AdvancedStyleConsensus/)
|
||||||
|
assert.match(types, /interface AdvancedStyleValidationCase/)
|
||||||
|
assert.match(types, /images: AdvancedStyleSetUploadImage\[\]/)
|
||||||
|
assert.match(endpoints, /advancedMaterialStyleSetUpload: "advanced-material-imports\/style-set\/upload"/)
|
||||||
|
assert.match(endpoints, /style-validation-cases\/\$\{caseId\}\/retry/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("allows an unsealed import to be deleted after its queue row is removed", async () => {
|
||||||
|
const [page, endpoints] = await Promise.all([
|
||||||
|
readFile(pagePath, "utf8"),
|
||||||
|
readFile(endpointsPath, "utf8"),
|
||||||
|
])
|
||||||
|
|
||||||
|
assert.match(endpoints, /advancedMaterialImportDelete/)
|
||||||
|
assert.match(page, /deleteJson<Record<string, unknown>>/)
|
||||||
|
assert.match(page, /确认删除导入/)
|
||||||
|
assert.match(page, /!selectedImport\.accepted_material_id/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("keeps queue cards at their natural height instead of compressing grid rows", async () => {
|
||||||
|
const app = await readFile(appPath, "utf8")
|
||||||
|
|
||||||
|
assert.match(app, /\.queue-task-list\s*\{[^}]*display:\s*flex;[^}]*flex-direction:\s*column;/s)
|
||||||
|
assert.match(app, /\.queue-task-card\s*\{[^}]*flex:\s*0 0 auto;[^}]*min-height:\s*88px;/s)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("polls only active import state and keeps storage-backed media URLs stable", async () => {
|
||||||
|
const page = await readFile(pagePath, "utf8")
|
||||||
|
|
||||||
|
assert.match(page, /const pollBusy = ref\(false\)/)
|
||||||
|
assert.match(page, /void pollActiveState\(\)/)
|
||||||
|
assert.doesNotMatch(page, /setInterval\([\s\S]{0,500}void refreshAll\(true\)/)
|
||||||
|
assert.match(page, /if \(importId && selectedWasBusy\)/)
|
||||||
|
assert.match(page, /if \(!pairedUri \|\| !pairedUri\.startsWith\("storage:\/\/"\)\) signedUrls\.add\(value\)/)
|
||||||
|
assert.match(page, /mediaUrl\(item\.source_thumbnail_uri, item\.source_image_uri/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("routes style corrections and validation-content instructions separately", async () => {
|
||||||
|
const [page, types] = await Promise.all([
|
||||||
|
readFile(pagePath, "utf8"),
|
||||||
|
readFile(typesPath, "utf8"),
|
||||||
|
])
|
||||||
|
|
||||||
|
assert.match(types, /style_adjustment_text\?: string/)
|
||||||
|
assert.match(types, /validation_instruction\?: string/)
|
||||||
|
assert.match(page, /const validationInstructionText = ref\(""\)/)
|
||||||
|
assert.match(page, /style_adjustment_text: selectedStyleSet\.value \? adjustment/)
|
||||||
|
assert.match(page, /validation_instruction: selectedStyleSet\.value \? validationInstruction/)
|
||||||
|
assert.match(page, /下一轮验证内容(选填)/)
|
||||||
|
assert.match(page, /已应用文字调整/)
|
||||||
|
assert.match(page, /应用文字调整并生成下一轮/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("recognizes canonical advanced style sets and renders all three validation images", async () => {
|
||||||
|
const page = await readFile(pagePath, "utf8")
|
||||||
|
|
||||||
|
assert.match(page, /workflowKind === "style_set" \|\| workflowKind === "advanced_style_set"/)
|
||||||
|
assert.match(page, /attempt\.validation_cases\?\.length/)
|
||||||
|
assert.match(page, /v-for="validationCase in attempt\.validation_cases"/)
|
||||||
|
assert.match(page, /class="advanced-attempt-history-images"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("opens advanced-material thumbnails in the shared safe image preview dialog", async () => {
|
||||||
|
const page = await readFile(pagePath, "utf8")
|
||||||
|
|
||||||
|
assert.match(page, /import ImagePreviewDialog from "\.\.\/\.\.\/components\/ImagePreviewDialog\.vue"/)
|
||||||
|
assert.match(page, /const previewImageSrc = ref\(""\)/)
|
||||||
|
assert.match(page, /function validationCasePreviewUrl/)
|
||||||
|
assert.match(page, /@click="openImagePreview\(validationCasePreviewUrl\(validationCase\)/)
|
||||||
|
assert.match(page, /<ImagePreviewDialog/)
|
||||||
|
assert.match(page, /@close="closeImagePreview"/)
|
||||||
|
assert.match(page, /function styleValidationFidelityPercent/)
|
||||||
|
assert.match(page, /function styleValidationReviewSummary/)
|
||||||
|
assert.match(page, /title="点击查看大图"/)
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,34 @@
|
||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { readFile } from "node:fs/promises"
|
||||||
|
import test from "node:test"
|
||||||
|
|
||||||
|
const presentationPath = new URL("../shared/utils/presentation.ts", import.meta.url)
|
||||||
|
const timeoutsPath = new URL("../shared/config/timeouts.ts", import.meta.url)
|
||||||
|
const clientPath = new URL("../shared/api/client.ts", import.meta.url)
|
||||||
|
const bridgePath = new URL("../shared/api/astrbot-page-bridge.ts", import.meta.url)
|
||||||
|
const appPath = new URL("../standalone-web/src/App.vue", import.meta.url)
|
||||||
|
|
||||||
|
test("uses the backend 900 second task budget throughout the plugin bridge UI", async () => {
|
||||||
|
const [timeouts, client, bridge, app] = await Promise.all([
|
||||||
|
readFile(timeoutsPath, "utf8"),
|
||||||
|
readFile(clientPath, "utf8"),
|
||||||
|
readFile(bridgePath, "utf8"),
|
||||||
|
readFile(appPath, "utf8"),
|
||||||
|
])
|
||||||
|
|
||||||
|
assert.match(timeouts, /LONG_TASK_TIMEOUT_SECONDS = 900/)
|
||||||
|
assert.match(timeouts, /LONG_TASK_TIMEOUT_MS = LONG_TASK_TIMEOUT_SECONDS \* 1000/)
|
||||||
|
assert.match(client, /LONG_TASK_ENDPOINT\.test\(endpoint\)[\s\S]*\? LONG_TASK_TIMEOUT_MS/)
|
||||||
|
assert.match(bridge, /LONG_TASK_ENDPOINT\.test\(endpoint\)[\s\S]*\? LONG_TASK_TIMEOUT_MS/)
|
||||||
|
assert.match(app, /耗时 \/ 后端时限/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("treats naive backend timestamps as UTC and freezes terminal job duration", async () => {
|
||||||
|
const presentation = await readFile(presentationPath, "utf8")
|
||||||
|
|
||||||
|
assert.match(presentation, /BACKEND_NAIVE_UTC_TIMESTAMP/)
|
||||||
|
assert.match(presentation, /`\$\{text\.replace\(" ", "T"\)\}Z`/)
|
||||||
|
assert.match(presentation, /TERMINAL_JOB_STATUSES\.has\(status\)/)
|
||||||
|
assert.match(presentation, /terminal \? timestamp\(job\.updated_at\) : 0/)
|
||||||
|
assert.match(presentation, /job\.request\?\.timeout_seconds/)
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,59 @@
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const repoRoot = path.resolve(__dirname, '..', '..')
|
||||||
|
const frontendRoot = path.join(repoRoot, 'frontend')
|
||||||
|
const standaloneRoot = path.join(frontendRoot, 'standalone-web', 'src')
|
||||||
|
const app = fs.readFileSync(path.join(standaloneRoot, 'App.vue'), 'utf8')
|
||||||
|
const navigation = fs.readFileSync(path.join(standaloneRoot, 'features', 'navigation', 'navigation-config.ts'), 'utf8')
|
||||||
|
const workbenchStyles = fs.readFileSync(path.join(standaloneRoot, 'styles', 'workbench.css'), 'utf8')
|
||||||
|
const bridge = fs.readFileSync(path.join(frontendRoot, 'shared', 'api', 'astrbot-page-bridge.ts'), 'utf8')
|
||||||
|
|
||||||
|
const views = ['overview', 'generate', 'queue', 'performance', 'gallery', 'profiles', 'materials', 'settings', 'logs']
|
||||||
|
|
||||||
|
test('UI shell keeps all supported views and landmarks', () => {
|
||||||
|
for (const view of views) assert.match(navigation, new RegExp('key: \"' + view + '\"'), 'missing nav view: ' + view)
|
||||||
|
assert.match(app, /<main\s+[\s\S]*aria-label=\"ImageStudio workbench\"/)
|
||||||
|
assert.match(app, /<section class=\"workbench\" aria-label=\"ImageStudio workspace\">/)
|
||||||
|
assert.match(app, /role=\"status\"[\s\S]*aria-live=\"polite\"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('UI shell preserves plugin bridge and lazy page loading', () => {
|
||||||
|
assert.match(app, /defineAsyncComponent\(\(\) => import\(\"\.\/features\/gallery\/GalleryPage\.vue\"\)\)/)
|
||||||
|
assert.match(app, /defineAsyncComponent\(\(\) => import\(\"\.\/features\/settings\/SettingsPage\.vue\"\)\)/)
|
||||||
|
assert.match(app, /defineAsyncComponent\(\(\) => import\(\"\.\/features\/workflow\/WorkflowComposer\.vue\"\)\)/)
|
||||||
|
assert.match(bridge, /kind: \"ready\"/)
|
||||||
|
assert.match(bridge, /message.kind === \"context\"/)
|
||||||
|
assert.match(bridge, /apiGet/)
|
||||||
|
assert.match(bridge, /apiPost/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('UI CSS avoids layout-property animation and supports reduced motion', () => {
|
||||||
|
assert.doesNotMatch(workbenchStyles, /transition\s*:\s*[^;]*(?:width|height|max-height|grid-template-columns|padding|margin)/i)
|
||||||
|
assert.match(workbenchStyles, /@media \(max-width: 1180px\)/)
|
||||||
|
assert.match(workbenchStyles, /@media \(max-width: 900px\)/)
|
||||||
|
assert.match(workbenchStyles, /@media \(prefers-reduced-motion: reduce\)/)
|
||||||
|
assert.match(workbenchStyles, /--ui-focus-ring/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('standalone image markup provides alt text', () => {
|
||||||
|
const files = []
|
||||||
|
const visit = (dir) => {
|
||||||
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const fullPath = path.join(dir, entry.name)
|
||||||
|
if (entry.isDirectory()) visit(fullPath)
|
||||||
|
else if (entry.name.endsWith('.vue')) files.push(fullPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visit(standaloneRoot)
|
||||||
|
for (const file of files) {
|
||||||
|
const source = fs.readFileSync(file, 'utf8')
|
||||||
|
for (const tag of source.match(/<img\b[\s\S]*?>/gi) ?? []) {
|
||||||
|
assert.match(tag, /\balt\s*=/i, 'image without alt: ' + path.relative(repoRoot, file))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const repoRoot = path.resolve(__dirname, '..', '..')
|
||||||
|
const tokens = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'styles', 'tokens.css'), 'utf8')
|
||||||
|
const workbench = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'styles', 'workbench.css'), 'utf8')
|
||||||
|
const app = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'App.vue'), 'utf8')
|
||||||
|
|
||||||
|
const requiredTokens = [
|
||||||
|
'--ui-space-1', '--ui-space-2', '--ui-space-3', '--ui-space-4', '--ui-space-5', '--ui-space-6',
|
||||||
|
'--ui-radius-sm', '--ui-radius-md', '--ui-radius-lg', '--ui-focus-ring', '--ui-duration-fast',
|
||||||
|
]
|
||||||
|
|
||||||
|
test('visual tokens remain centralized', () => {
|
||||||
|
for (const token of requiredTokens) assert.match(tokens, new RegExp(`${token}:`), `missing token ${token}`)
|
||||||
|
assert.match(workbench, /var\(--ui-radius-md\)/)
|
||||||
|
assert.match(workbench, /var\(--ui-radius-lg\)/)
|
||||||
|
assert.doesNotMatch(workbench, /#[0-9a-f]{6}\b/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('semantic states retain readable borders', () => {
|
||||||
|
for (const state of ['good', 'warn', 'bad', 'disabled']) {
|
||||||
|
assert.match(`${workbench}\n${app}`, new RegExp(`\\.${state}`), `missing ${state} state styling`)
|
||||||
|
}
|
||||||
|
assert.match(workbench, /color-mix\(in srgb, var\(--danger\)/)
|
||||||
|
assert.match(workbench, /color-mix\(in srgb, var\(--warn\)/)
|
||||||
|
})
|
||||||
|
|
||||||
|
function luminance(hex) {
|
||||||
|
const values = hex.match(/[0-9a-f]{2}/gi).map((value) => Number.parseInt(value, 16) / 255)
|
||||||
|
const linear = values.map((value) => value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
|
||||||
|
return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
|
||||||
|
}
|
||||||
|
|
||||||
|
function contrastRatio(first, second) {
|
||||||
|
const firstLuminance = luminance(first)
|
||||||
|
const secondLuminance = luminance(second)
|
||||||
|
return (Math.max(firstLuminance, secondLuminance) + 0.05) / (Math.min(firstLuminance, secondLuminance) + 0.05)
|
||||||
|
}
|
||||||
|
|
||||||
|
test('dark and light text tokens meet AA contrast targets', () => {
|
||||||
|
assert.ok(contrastRatio('#edf4fb', '#111522') >= 4.5)
|
||||||
|
assert.ok(contrastRatio('#9aa8ba', '#111522') >= 4.5)
|
||||||
|
assert.ok(contrastRatio('#18202b', '#f3f6fb') >= 4.5)
|
||||||
|
assert.ok(contrastRatio('#667085', '#f3f6fb') >= 4.5)
|
||||||
|
})
|
||||||
117
main.py
117
main.py
|
|
@ -125,6 +125,18 @@ _RUNTIME_PATH_TO_ASTRBOT_KEY = {
|
||||||
"vision.provider.timeout_seconds": "vision_provider_timeout_seconds",
|
"vision.provider.timeout_seconds": "vision_provider_timeout_seconds",
|
||||||
"vision.provider.enabled": "vision_provider_enabled",
|
"vision.provider.enabled": "vision_provider_enabled",
|
||||||
"model_assignments.material_recognition": "model_material_recognition",
|
"model_assignments.material_recognition": "model_material_recognition",
|
||||||
|
"model_assignments.advanced_material_recognition": "model_advanced_material_recognition",
|
||||||
|
"model_assignments.advanced_style_consensus": "model_advanced_style_consensus",
|
||||||
|
"model_assignments.advanced_material_validation_generation": "model_advanced_material_validation_generation",
|
||||||
|
"advanced_materials.cost_budget.enabled": "advanced_material_budget_enabled",
|
||||||
|
"advanced_materials.cost_budget.days": "advanced_material_budget_days",
|
||||||
|
"advanced_materials.cost_budget.max_task_count": "advanced_material_budget_max_task_count",
|
||||||
|
"advanced_materials.cost_budget.max_image_count": "advanced_material_budget_max_image_count",
|
||||||
|
"advanced_materials.cost_budget.max_estimated_cost": "advanced_material_budget_max_estimated_cost",
|
||||||
|
"advanced_materials.cost_budget.price_key": "advanced_material_budget_price_key",
|
||||||
|
"advanced_materials.cost_budget.per_request": "advanced_material_budget_per_request",
|
||||||
|
"advanced_materials.cost_budget.per_image": "advanced_material_budget_per_image",
|
||||||
|
"advanced_materials.cost_budget.per_1k_tokens": "advanced_material_budget_per_1k_tokens",
|
||||||
"model_assignments.profile_parse": "model_profile_parse",
|
"model_assignments.profile_parse": "model_profile_parse",
|
||||||
"model_assignments.persona_split": "model_persona_split",
|
"model_assignments.persona_split": "model_persona_split",
|
||||||
"model_assignments.prompt_planning": "model_prompt_planning",
|
"model_assignments.prompt_planning": "model_prompt_planning",
|
||||||
|
|
@ -150,6 +162,7 @@ _RUNTIME_PATH_TO_ASTRBOT_KEY = {
|
||||||
"chat_access.allow_2k": "chat_allow_2k",
|
"chat_access.allow_2k": "chat_allow_2k",
|
||||||
"chat_access.allow_4k": "chat_allow_4k",
|
"chat_access.allow_4k": "chat_allow_4k",
|
||||||
"features.private_companion_integration": "enable_private_companion_integration",
|
"features.private_companion_integration": "enable_private_companion_integration",
|
||||||
|
"storage.advanced_materials_path": "advanced_materials_path",
|
||||||
"database.backend": "database_backend",
|
"database.backend": "database_backend",
|
||||||
"database.sqlite.path": "sqlite_path",
|
"database.sqlite.path": "sqlite_path",
|
||||||
"database.postgresql.enabled": "postgresql_enabled",
|
"database.postgresql.enabled": "postgresql_enabled",
|
||||||
|
|
@ -361,6 +374,8 @@ class Main(AstrBotStar):
|
||||||
self.chat_background_tasks: set[asyncio.Task[Any]] = set()
|
self.chat_background_tasks: set[asyncio.Task[Any]] = set()
|
||||||
self.round_worker_runtime: Any | None = None
|
self.round_worker_runtime: Any | None = None
|
||||||
self.round_worker_result: dict[str, Any] | None = None
|
self.round_worker_result: dict[str, Any] | None = None
|
||||||
|
self.advanced_material_worker_runtime: Any | None = None
|
||||||
|
self.advanced_material_worker_result: dict[str, Any] | None = None
|
||||||
self.runtime_loop: asyncio.AbstractEventLoop | None = None
|
self.runtime_loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
|
||||||
async def initialize(self) -> None:
|
async def initialize(self) -> None:
|
||||||
|
|
@ -393,11 +408,32 @@ class Main(AstrBotStar):
|
||||||
"error_type": type(exc).__name__,
|
"error_type": type(exc).__name__,
|
||||||
"message": " ".join(str(exc).split())[:500],
|
"message": " ".join(str(exc).split())[:500],
|
||||||
}
|
}
|
||||||
|
try:
|
||||||
|
from backend.services.advanced_material_worker_runtime import (
|
||||||
|
create_advanced_material_worker_runtime,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.advanced_material_worker_runtime = create_advanced_material_worker_runtime()
|
||||||
|
self.advanced_material_worker_result = self.advanced_material_worker_runtime.start()
|
||||||
|
except Exception as exc:
|
||||||
|
# Keep the normal material library and recovery UI usable when the
|
||||||
|
# optional advanced-material worker cannot start. Its persisted
|
||||||
|
# imports/tasks remain available for retry after configuration is
|
||||||
|
# corrected or the plugin is reloaded.
|
||||||
|
self.advanced_material_worker_runtime = None
|
||||||
|
self.advanced_material_worker_result = {
|
||||||
|
"running": False,
|
||||||
|
"error_type": type(exc).__name__,
|
||||||
|
"message": " ".join(str(exc).split())[:500],
|
||||||
|
}
|
||||||
if self.context is not None:
|
if self.context is not None:
|
||||||
self.registration_result = register_plugin(self.context)
|
self.registration_result = register_plugin(self.context)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def terminate(self) -> None:
|
async def terminate(self) -> None:
|
||||||
|
if self.advanced_material_worker_runtime is not None:
|
||||||
|
self.advanced_material_worker_result = self.advanced_material_worker_runtime.stop()
|
||||||
|
self.advanced_material_worker_runtime = None
|
||||||
if self.round_worker_runtime is not None:
|
if self.round_worker_runtime is not None:
|
||||||
self.round_worker_result = self.round_worker_runtime.stop()
|
self.round_worker_result = self.round_worker_runtime.stop()
|
||||||
self.round_worker_runtime = None
|
self.round_worker_runtime = None
|
||||||
|
|
@ -1761,6 +1797,18 @@ def _mapping_from_runtime_config(config: Any | None) -> dict[str, Any]:
|
||||||
"vision_provider_timeout_seconds",
|
"vision_provider_timeout_seconds",
|
||||||
"vision_provider_enabled",
|
"vision_provider_enabled",
|
||||||
"model_material_recognition",
|
"model_material_recognition",
|
||||||
|
"model_advanced_material_recognition",
|
||||||
|
"model_advanced_style_consensus",
|
||||||
|
"model_advanced_material_validation_generation",
|
||||||
|
"advanced_material_budget_enabled",
|
||||||
|
"advanced_material_budget_days",
|
||||||
|
"advanced_material_budget_max_task_count",
|
||||||
|
"advanced_material_budget_max_image_count",
|
||||||
|
"advanced_material_budget_max_estimated_cost",
|
||||||
|
"advanced_material_budget_price_key",
|
||||||
|
"advanced_material_budget_per_request",
|
||||||
|
"advanced_material_budget_per_image",
|
||||||
|
"advanced_material_budget_per_1k_tokens",
|
||||||
"model_profile_parse",
|
"model_profile_parse",
|
||||||
"model_persona_split",
|
"model_persona_split",
|
||||||
"model_prompt_planning",
|
"model_prompt_planning",
|
||||||
|
|
@ -1786,6 +1834,7 @@ def _mapping_from_runtime_config(config: Any | None) -> dict[str, Any]:
|
||||||
"chat_allow_2k",
|
"chat_allow_2k",
|
||||||
"chat_allow_4k",
|
"chat_allow_4k",
|
||||||
"enable_private_companion_integration",
|
"enable_private_companion_integration",
|
||||||
|
"advanced_materials_path",
|
||||||
"database_backend",
|
"database_backend",
|
||||||
"sqlite_path",
|
"sqlite_path",
|
||||||
"postgresql_enabled",
|
"postgresql_enabled",
|
||||||
|
|
@ -1885,6 +1934,7 @@ def _runtime_config_patch_from_mapping(mapping: Mapping[str, Any]) -> dict[str,
|
||||||
database = _mapping_from_any(mapping.get("database"))
|
database = _mapping_from_any(mapping.get("database"))
|
||||||
sqlite = _mapping_from_any(database.get("sqlite")) if database else {}
|
sqlite = _mapping_from_any(database.get("sqlite")) if database else {}
|
||||||
postgresql = _mapping_from_any(database.get("postgresql")) if database else {}
|
postgresql = _mapping_from_any(database.get("postgresql")) if database else {}
|
||||||
|
storage = _mapping_from_any(mapping.get("storage"))
|
||||||
features = _mapping_from_any(mapping.get("features"))
|
features = _mapping_from_any(mapping.get("features"))
|
||||||
plugin = _mapping_from_any(mapping.get("plugin"))
|
plugin = _mapping_from_any(mapping.get("plugin"))
|
||||||
vision = _mapping_from_any(mapping.get("vision"))
|
vision = _mapping_from_any(mapping.get("vision"))
|
||||||
|
|
@ -1986,6 +2036,73 @@ def _runtime_config_patch_from_mapping(mapping: Mapping[str, Any]) -> dict[str,
|
||||||
if value:
|
if value:
|
||||||
_set_nested(patch, ("model_assignments", target_key), value)
|
_set_nested(patch, ("model_assignments", target_key), value)
|
||||||
|
|
||||||
|
# Advanced-material assignments deliberately preserve an empty value so
|
||||||
|
# administrators can clear a dedicated route and return to its documented
|
||||||
|
# fallback without a stale AstrBot runtime override restoring it.
|
||||||
|
for target_key, source_key in {
|
||||||
|
"advanced_material_recognition": "model_advanced_material_recognition",
|
||||||
|
"advanced_material_validation_generation": "model_advanced_material_validation_generation",
|
||||||
|
}.items():
|
||||||
|
value = _runtime_value(mapping, source_key)
|
||||||
|
if value is not _MISSING:
|
||||||
|
_set_nested(patch, ("model_assignments", target_key), _runtime_text(value))
|
||||||
|
|
||||||
|
consensus_route = _runtime_text(_runtime_value(mapping, "model_advanced_style_consensus"))
|
||||||
|
if consensus_route:
|
||||||
|
_set_nested(patch, ("model_assignments", "advanced_style_consensus"), consensus_route)
|
||||||
|
|
||||||
|
advanced_materials_path = _runtime_text(
|
||||||
|
_runtime_value(
|
||||||
|
mapping,
|
||||||
|
"advanced_materials_path",
|
||||||
|
fallback=storage.get("advanced_materials_path", _MISSING),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if advanced_materials_path:
|
||||||
|
_set_nested(patch, ("storage", "advanced_materials_path"), advanced_materials_path)
|
||||||
|
|
||||||
|
advanced_materials = mapping.get("advanced_materials") if isinstance(mapping.get("advanced_materials"), Mapping) else {}
|
||||||
|
current_budget = advanced_materials.get("cost_budget") if isinstance(advanced_materials.get("cost_budget"), Mapping) else {}
|
||||||
|
budget_enabled = _runtime_value(
|
||||||
|
mapping,
|
||||||
|
"advanced_material_budget_enabled",
|
||||||
|
fallback=current_budget.get("enabled", _MISSING),
|
||||||
|
)
|
||||||
|
if budget_enabled is not _MISSING:
|
||||||
|
_set_nested(patch, ("advanced_materials", "cost_budget", "enabled"), _runtime_bool(budget_enabled))
|
||||||
|
for target_key, source_key, converter in (
|
||||||
|
("days", "advanced_material_budget_days", int),
|
||||||
|
("max_task_count", "advanced_material_budget_max_task_count", int),
|
||||||
|
("max_image_count", "advanced_material_budget_max_image_count", int),
|
||||||
|
("max_estimated_cost", "advanced_material_budget_max_estimated_cost", float),
|
||||||
|
("per_request", "advanced_material_budget_per_request", float),
|
||||||
|
("per_image", "advanced_material_budget_per_image", float),
|
||||||
|
("per_1k_tokens", "advanced_material_budget_per_1k_tokens", float),
|
||||||
|
):
|
||||||
|
raw_value = _runtime_value(mapping, source_key, fallback=current_budget.get(target_key, _MISSING))
|
||||||
|
if raw_value is _MISSING:
|
||||||
|
continue
|
||||||
|
text_value = _runtime_text(raw_value)
|
||||||
|
if text_value == "" and target_key in {"max_task_count", "max_image_count", "max_estimated_cost"}:
|
||||||
|
_set_nested(patch, ("advanced_materials", "cost_budget", target_key), None)
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
normalized_value = converter(text_value or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
_set_nested(patch, ("advanced_materials", "cost_budget", target_key), normalized_value)
|
||||||
|
budget_price_key = _runtime_value(
|
||||||
|
mapping,
|
||||||
|
"advanced_material_budget_price_key",
|
||||||
|
fallback=current_budget.get("price_key", _MISSING),
|
||||||
|
)
|
||||||
|
if budget_price_key is not _MISSING:
|
||||||
|
_set_nested(
|
||||||
|
patch,
|
||||||
|
("advanced_materials", "cost_budget", "price_key"),
|
||||||
|
_runtime_text(budget_price_key),
|
||||||
|
)
|
||||||
|
|
||||||
# Multi-route assignments are first-class AstrBot plugin settings. Keep
|
# Multi-route assignments are first-class AstrBot plugin settings. Keep
|
||||||
# empty lists as explicit values so clearing a selection in the Web UI is
|
# empty lists as explicit values so clearing a selection in the Web UI is
|
||||||
# persisted back to AstrBot instead of being restored from a stale runtime
|
# persisted back to AstrBot instead of being restored from a stale runtime
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,11 @@
|
||||||
name: astrbot_plugin_imagestudio
|
name: astrbot_plugin_imagestudio
|
||||||
display_name: ImageStudio
|
display_name: ImageStudio
|
||||||
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
|
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
|
||||||
short_desc: AstrBot 内的角色资产、工作流与图片生成管理工作台。
|
short_desc: AstrBot 鍐呯殑瑙掕壊璧勪骇銆佸伐浣滄祦涓庡浘鐗囩敓鎴愮鐞嗗伐浣滃彴銆?
|
||||||
version: 1.0.20
|
version: 1.0.66
|
||||||
author: YokiiroBW
|
author: YokiiroBW
|
||||||
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
|
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
|
||||||
astrbot_version: ">=4.25.0,<5"
|
astrbot_version: ">=4.25.0,<5"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
|
|
@ -4,8 +4,8 @@
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>AstrBot ImageStudio</title>
|
<title>AstrBot ImageStudio</title>
|
||||||
<script type="module" crossorigin src="./assets/index-DLwA6M_k.js"></script>
|
<script type="module" crossorigin src="./assets/index-BZ25rUbw.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="./assets/index-BANum4Rx.css">
|
<link rel="stylesheet" crossorigin href="./assets/index-B8Z-z8zX.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|
|
||||||
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
某些文件未显示,因为此 diff 中更改的文件太多 显示更多
正在加载…
添加表格
在新工单中引用