From 2ef83a746c48366234e81a0ffc1808d9cd5c9bf4 Mon Sep 17 00:00:00 2001 From: tianmeng <702680355@qq.com> Date: Wed, 19 Aug 2026 10:39:58 +0800 Subject: [PATCH 1/2] chore: drop remaining dual-read aliases Keep wallet, catalog, canvas, and prompt-pack on current keys only (credits, apiModel, fill-color, path) and emit resumable instead of can_resume. --- apps/api/app/api/routes/admin/common.py | 2 +- apps/api/app/api/routes/admin/users.py | 4 +- apps/api/app/api/routes/auth.py | 15 +- apps/api/app/crud.py | 14 +- apps/api/app/models.py | 1 - apps/api/app/services/admin/users.py | 7 +- .../api/app/services/agent_memory/episodes.py | 8 +- apps/api/app/services/agent_memory/kg.py | 12 +- apps/api/app/services/agent_memory/schema.py | 6 +- .../app/services/agent_memory/short_term.py | 6 +- .../api/app/services/agent_memory/subgoals.py | 4 +- apps/api/app/services/chat_store.py | 4 +- .../app/services/design/admin/admin_store.py | 299 ++---------------- apps/api/app/services/design/export_render.py | 34 +- .../services/design/intelligence_runtime.py | 4 +- .../services/design/ops/tool_ops_contract.py | 89 +++--- .../services/design/prompts/prompt_build.py | 6 +- .../design/prompts/prompt_pack_store.py | 69 +--- .../design/prompts/skill_store/pack_io.py | 15 +- .../design/prompts/skill_store/runtime.py | 54 +--- .../design/prompts/skill_store/user_skills.py | 9 +- .../services/design/runtime/agent_profile.py | 28 +- .../services/design/runtime/graph/build.py | 13 +- .../services/design/runtime/graph/llm_io.py | 6 +- .../design/runtime/graph/nodes/apply.py | 2 +- .../design/runtime/graph/nodes/bootstrap.py | 2 +- .../runtime/graph/nodes/counterfactual.py | 6 +- .../design/runtime/graph/nodes/decide.py | 19 +- .../design/runtime/graph/nodes/governance.py | 32 +- .../design/runtime/graph/nodes/intent.py | 2 +- .../design/runtime/graph/nodes/observe.py | 23 +- .../design/runtime/graph/nodes/research.py | 5 +- .../design/runtime/graph/nodes/review.py | 50 +-- .../design/runtime/graph/nodes/settle.py | 6 +- .../design/runtime/graph/nodes/tournament.py | 6 +- .../design/runtime/graph/paint_kit.py | 6 +- .../design/runtime/graph/scene_log.py | 12 +- .../services/design/runtime/graph/turns.py | 2 +- .../services/design/runtime/host/placement.py | 57 ++-- .../services/design/runtime/host/prompts.py | 5 +- .../services/design/runtime/host/resources.py | 3 +- .../services/design/runtime/models_route.py | 36 +-- .../design/runtime/pipeline_progress.py | 2 +- .../app/services/design/runtime/subagent.py | 23 +- apps/api/app/services/llm/__init__.py | 49 ++- apps/api/app/services/llm/audio.py | 2 +- apps/api/app/services/llm/byok_presets.py | 4 +- apps/api/app/services/llm/catalog_store.py | 18 +- apps/api/app/services/llm/image.py | 10 +- apps/api/app/services/llm/image_tools.py | 4 +- apps/api/app/services/llm/price_sync.py | 10 +- apps/api/app/services/llm/pricing_registry.py | 23 +- apps/api/app/services/llm/video.py | 2 +- apps/api/app/services/plaza/panel_png.py | 7 +- apps/api/app/services/plaza/store.py | 47 ++- apps/api/app/services/projects.py | 65 +++- apps/api/app/services/vision/crop.py | 6 +- apps/api/app/services/vision/image_edit.py | 4 +- apps/api/app/services/wallet/billing.py | 27 +- apps/api/app/services/wallet/card_keys.py | 45 +-- apps/api/app/services/wallet/db.py | 4 +- apps/api/scripts/gen_card_keys.py | 12 +- .../design_engine/test_design_governance.py | 4 +- .../design_engine/test_language_and_reply.py | 5 +- .../tests/design_engine/test_optimization.py | 4 +- .../unit_tests/test_agent_controller_parse.py | 2 +- .../unit_tests/test_design_run_lifecycle.py | 4 +- .../unit_tests/test_design_sse_progress.py | 2 +- .../api/tests/unit_tests/test_prompt_packs.py | 10 - .../unit_tests/test_task_pricing_capture.py | 6 +- .../unit_tests/test_tool_ops_contract.py | 4 +- .../components/account/AccountProfileTab.tsx | 6 +- .../components/editor/canvas/SvgCanvas.tsx | 11 +- .../editor/canvas/runCanvasCtxAction.ts | 2 +- .../nodes/AudioNode/AudioNodeOverlay.tsx | 4 +- .../nodes/LottieNode/LottieNodeOverlay.tsx | 2 +- .../nodes/ShapeNode/ShapeSelectionToolbar.tsx | 8 +- .../nodes/ShapeNode/ShapeStylePanelHost.tsx | 12 +- .../editor/panels/AgentComposerInput.tsx | 2 +- .../components/editor/panels/AgentDock.tsx | 2 +- .../editor/panels/ExportSelectionPanel.tsx | 2 +- .../editor/panels/agent/agentRoutePrefs.ts | 9 +- .../editor/panels/agent/agentSceneContext.ts | 48 +-- .../editor/panels/agent/customLlmProviders.ts | 16 +- .../editor/panels/agent/designTools.ts | 22 +- .../editor/panels/agent/llmModelMeta.ts | 14 +- .../agent/shared/ImageAspectRatioPicker.tsx | 6 +- .../editor/panels/agent/toolOpsContract.ts | 10 +- .../components/home/SkillsLibraryPanel.tsx | 4 +- .../src/components/layout/RedeemDialog.tsx | 8 +- .../components/layout/UserAccountPanel.tsx | 4 +- .../components/layout/WalletAccountChip.tsx | 6 +- .../components/layout/WalletLedgerPanel.tsx | 18 +- .../components/rcb/core/geometry/baseline.ts | 2 +- .../src/components/rcb/core/spatialIndex.ts | 2 +- .../render/__tests__/sceneRenderer.test.ts | 12 +- .../components/rcb/render/sceneRenderer.ts | 22 +- .../__tests__/canvasFunctionalStress.test.ts | 4 +- .../__tests__/canvasStress.bench.test.ts | 8 - .../document/__tests__/sceneHitBridge.test.ts | 2 +- .../document/__tests__/stackCover.test.ts | 2 +- .../strokeBakedOutlineRadius.test.ts | 1 - .../rcb/scene/document/mediaLifecycle.ts | 4 +- .../rcb/scene/document/nodeCapabilities.ts | 8 +- .../rcb/scene/document/nodeFactories.ts | 8 - .../rcb/scene/document/sceneEffects.ts | 13 +- .../rcb/scene/document/sceneHitBridge.ts | 4 +- .../rcb/scene/document/sceneRadii.ts | 4 +- .../paint/__tests__/nodeEffectsPaint.test.ts | 4 +- .../outlineArrowKeepsPosition.test.ts | 2 - .../__tests__/outlinePathEditPaint.test.ts | 1 - .../__tests__/outlinePenMiterTip.test.ts | 4 - .../outlinePenPencilKeepSilhouette.test.ts | 17 +- .../__tests__/outlineSparsifyZoom.test.ts | 5 +- .../rcb/scene/paint/outlineToPath.ts | 30 +- .../components/rcb/scene/paint/sceneToSvg.ts | 14 +- .../rcb/selection/HostPathChrome.tsx | 2 +- .../rcb/selection/SelectionFeature.tsx | 2 +- .../__tests__/chromeStrokeOutset.test.ts | 2 +- .../postSplitCanvasRegression.test.ts | 4 +- .../chrome/MultiSelectionToolbar.tsx | 2 +- .../rcb/selection/selectionLogic.ts | 2 +- .../components/rcb/selection/shapeBoolean.ts | 7 +- .../components/rcb/shapes/RcbShapeHost.tsx | 5 - .../components/rcb/shapes/RcbShapesLayer.tsx | 2 +- .../shapes/__tests__/lodHostBudget.test.ts | 2 +- .../components/rcb/tools/PenDrawFeature.tsx | 4 +- .../rcb/tools/PenPathEditFeature.tsx | 18 +- apps/web/src/models/wallet.ts | 10 +- apps/web/src/pages/AccountSettingsPage.tsx | 10 +- apps/web/src/service/auth.ts | 4 +- apps/web/src/service/chat.ts | 7 +- apps/web/src/service/wallet.ts | 8 +- apps/web/src/store/modules/editorHistory.ts | 8 - apps/web/src/utils/imageCredits.ts | 6 +- apps/web/src/utils/wallet.ts | 6 +- eval/design-agent/e2e-capture.mjs | 8 +- eval/design-agent/run.mjs | 8 +- packages/contracts/generated/api/zod.gen.ts | 8 +- .../protocol/recombyn_protocol/design_flow.py | 1 - packages/protocol/recombyn_protocol/paint.py | 10 +- .../runtime/recombyn_runtime/intelligence.py | 12 +- scripts/design-agent-stress.mjs | 8 +- 143 files changed, 688 insertions(+), 1255 deletions(-) diff --git a/apps/api/app/api/routes/admin/common.py b/apps/api/app/api/routes/admin/common.py index 34299129..ce555c96 100644 --- a/apps/api/app/api/routes/admin/common.py +++ b/apps/api/app/api/routes/admin/common.py @@ -126,7 +126,7 @@ class GenerateCardKeysIn(BaseModel): """credit = unified 积分 top-up; plan = membership + monthly 积分.""" kind: str = Field(default="credit", max_length=16) # Face value in 积分. - tokens: int = Field(default=0, ge=0, le=50_000_000) + credits: int = Field(default=0, ge=0, le=50_000_000) planId: str | None = Field(default=None, max_length=16) expiresDays: int = Field(default=365, ge=0, le=3650) # Dedicated generate password (CARD_KEY_OPS_PASSWORD), not the login password. diff --git a/apps/api/app/api/routes/admin/users.py b/apps/api/app/api/routes/admin/users.py index 5b4e3338..779726c5 100644 --- a/apps/api/app/api/routes/admin/users.py +++ b/apps/api/app/api/routes/admin/users.py @@ -117,7 +117,7 @@ def admin_generate_card_keys( try: keys = generate_card_keys( count=body.count, - tokens=body.tokens, + credits=body.credits, expires_days=body.expiresDays, kind=body.kind, plan_id=body.planId, @@ -131,7 +131,7 @@ def admin_generate_card_keys( "count": len(keys), "kind": first.get("kind") or body.kind, "planId": first.get("planId") or body.planId, - "tokens": first.get("tokens") if keys else body.tokens, + "credits": first.get("credits") if keys else body.credits, "expiresDays": body.expiresDays, "keys": keys, } diff --git a/apps/api/app/api/routes/auth.py b/apps/api/app/api/routes/auth.py index e80ab631..d1ca8d30 100644 --- a/apps/api/app/api/routes/auth.py +++ b/apps/api/app/api/routes/auth.py @@ -52,7 +52,6 @@ ) from app.services.wallet.db import ( ensure_user_balance, - get_user_tokens, get_wallet, init_wallet_db, list_ledger, @@ -510,10 +509,8 @@ def email_login(body: EmailLoginIn, request: Request) -> dict[str, Any]: @router.get("/me", response_model=AuthMeOut) def auth_me(current_user: CurrentUser) -> dict[str, Any]: - init_wallet_db() return { "user": _user_payload(current_user), - "tokens": get_user_tokens(current_user.id), } @@ -578,10 +575,9 @@ def _wallet_plan_fields(snap: dict[str, Any]) -> dict[str, Any]: def wallet_me(current_user: CurrentUser) -> dict[str, Any]: init_wallet_db() snap = get_wallet(current_user.id) - credits = int(snap.get("credits") or snap.get("tokens") or 0) + credits = int(snap.get("credits") or 0) return { "credits": credits, - "tokens": credits, **_wallet_plan_fields(snap), "ledger": list_ledger(current_user.id), } @@ -600,10 +596,9 @@ def wallet_ledger( """ init_wallet_db() snap = get_wallet(current_user.id) - credits = int(snap.get("credits") or snap.get("tokens") or 0) + credits = int(snap.get("credits") or 0) return { "credits": credits, - "tokens": credits, **_wallet_plan_fields(snap), **list_ledger_page(current_user.id, page=page, page_size=pageSize, kind=kind), } @@ -640,14 +635,12 @@ def wallet_redeem( ) from err clear_redeem_rate_limit(user_id=current_user.id, ip=ip) snap = get_wallet(current_user.id) - credits = int(snap.get("credits") or snap.get("tokens") or 0) - added = int(result.get("creditsAdded") or result.get("tokensAdded") or 0) + credits = int(snap.get("credits") or 0) + added = int(result.get("creditsAdded") or 0) return { "kind": result.get("kind") or "credit", "creditsAdded": added, - "tokensAdded": added, "credits": credits, - "tokens": credits, **_wallet_plan_fields(snap), "ledger": list_ledger(current_user.id), } diff --git a/apps/api/app/crud.py b/apps/api/app/crud.py index e0d455b4..7952aabe 100644 --- a/apps/api/app/crud.py +++ b/apps/api/app/crud.py @@ -2438,8 +2438,7 @@ def _bind(val: Any) -> str: where.append(f"status = {_bind(status.strip())}") if q and q.strip(): like = f"%{q.strip()}%" - b1, b2, b3, b4, b5 = ( - _bind(like), + b1, b2, b3, b4 = ( _bind(like), _bind(like), _bind(like), @@ -2447,8 +2446,7 @@ def _bind(val: Any) -> str: ) where.append( f"(id LIKE {b1} OR user_id LIKE {b2} OR prompt LIKE {b3} OR " - f"coalesce(json_extract(meta_json, '$.trace_id'), '') LIKE {b4} OR " - f"coalesce(json_extract(meta_json, '$.decision_log.trace_id'), '') LIKE {b5})" + f"coalesce(json_extract(meta_json, '$.decision_log.trace_id'), '') LIKE {b4})" ) route_filter = (route or "").strip().lower() if route_filter: @@ -2477,15 +2475,12 @@ def _bind(val: Any) -> str: f""" SELECT id, user_id, scene, status, prompt, error_message, created_at, updated_at, - json_extract(meta_json, '$.trace_id') AS trace_id, json_extract(meta_json, '$.control') AS control, json_extract(meta_json, '$.flow_id') AS flow_id, + json_extract(meta_json, '$.flow_version') AS flow_version, json_extract(meta_json, '$.decision_log.trace_id') AS dl_trace, json_extract(meta_json, '$.decision_log.route') AS dl_route, json_extract(meta_json, '$.decision_log.intent') AS dl_intent, - json_extract(meta_json, '$.execution_log.trace_id') AS el_trace, - json_extract(meta_json, '$.execution_log.intent') AS el_intent, - json_extract(meta_json, '$.execution_log.flow_id') AS el_flow, json_extract(meta_json, '$.execution_log.ops_count') AS ops_count, json_extract(meta_json, '$.execution_log.total_tokens') AS total_tokens, json_extract(meta_json, '$.execution_log.total_duration_ms') AS total_duration_ms, @@ -2493,8 +2488,7 @@ def _bind(val: Any) -> str: json_extract(meta_json, '$.execution_log.task_tier') AS task_tier, json_extract(meta_json, '$.execution_log.vision_used') AS vision_used, json_extract(meta_json, '$.execution_log.model') AS model, - json_extract(meta_json, '$.execution_log.skills_loaded') AS el_skills, - json_extract(meta_json, '$.decision_log.skills_loaded') AS dl_skills + json_extract(meta_json, '$.execution_log.skills_loaded') AS el_skills FROM design_task WHERE {sql_where} ORDER BY created_at DESC diff --git a/apps/api/app/models.py b/apps/api/app/models.py index 58ecd429..3a441b3c 100644 --- a/apps/api/app/models.py +++ b/apps/api/app/models.py @@ -48,7 +48,6 @@ class AuthSessionOut(SQLModel): class AuthMeOut(SQLModel): user: UserPublic - tokens: int | float | None = None class OkOut(SQLModel): diff --git a/apps/api/app/services/admin/users.py b/apps/api/app/services/admin/users.py index f56873d3..63ba3bd7 100644 --- a/apps/api/app/services/admin/users.py +++ b/apps/api/app/services/admin/users.py @@ -12,7 +12,6 @@ from app.services.db import init_schema from app.services.wallet.db import ( credit_tokens, - get_user_tokens, get_wallet, list_ledger_page, normalize_plan, @@ -97,7 +96,7 @@ def adjust_tokens(user_id: str, amount: int, detail: str = "") -> dict[str, Any] else: balance = spend_tokens(uid, abs(amt), detail=note, force=True) - return {"userId": uid, "tokens": balance, "amount": amt} + return {"userId": uid, "credits": balance, "amount": amt} def user_ledger( @@ -110,7 +109,7 @@ def user_ledger( snap = get_wallet(user_id) expires = snap.get("planExpiresAt") return { - "tokens": int(snap.get("tokens") or get_user_tokens(user_id) or 0), + "credits": int(snap.get("credits") or 0), "planId": snap.get("planId") or "free", "planStored": snap.get("planStored") or "free", "planExpiresAt": int(float(expires) * 1000) if expires is not None else None, @@ -149,7 +148,7 @@ def _user_to_out(user: User, bal: UserBalance | None) -> dict[str, Any]: "provider": user.provider or "email", "role": user.role or "user", "status": user.status or "active", - "tokens": int(bal.tokens or 0) if bal else 0, + "credits": int(bal.tokens or 0) if bal else 0, "planId": plan_id, "planStored": stored, "planExpiresAt": int(expires_at * 1000) if expires_at is not None else None, diff --git a/apps/api/app/services/agent_memory/episodes.py b/apps/api/app/services/agent_memory/episodes.py index ff41d2ce..b0a53d96 100644 --- a/apps/api/app/services/agent_memory/episodes.py +++ b/apps/api/app/services/agent_memory/episodes.py @@ -66,10 +66,10 @@ def _summarize_actions(ops: list[Any] | None) -> list[dict[str, Any]]: for item in ops or []: if not isinstance(item, dict): continue - name = str(item.get("op") or item.get("type") or item.get("name") or "").strip() + name = str(item.get("name") or "").strip() if not name: continue - slim: dict[str, Any] = {"op": name[:64]} + slim: dict[str, Any] = {"name": name[:64]} for key in ("id", "frameId", "targetId", "name"): val = item.get(key) if val is not None and str(val).strip(): @@ -280,9 +280,9 @@ def _row_to_hit(r: Any, *, retrieve: str, score: float | None = None) -> dict[st except Exception: actions = [] op_names = [ - str(a.get("op") or "") + str(a.get("name") or "") for a in actions - if isinstance(a, dict) and a.get("op") + if isinstance(a, dict) and a.get("name") ] hit: dict[str, Any] = { "id": str(_col(r, "id") or ""), diff --git a/apps/api/app/services/agent_memory/kg.py b/apps/api/app/services/agent_memory/kg.py index 57854751..46940c6f 100644 --- a/apps/api/app/services/agent_memory/kg.py +++ b/apps/api/app/services/agent_memory/kg.py @@ -206,7 +206,7 @@ def extract_factual_triples_from_episode( op_names: list[str] = [] for a in actions or []: if isinstance(a, dict): - name = str(a.get("op") or a.get("name") or "").strip() + name = str(a.get("name") or "").strip() if name: op_names.append(name) elif isinstance(a, str) and a.strip(): @@ -553,17 +553,15 @@ def _parse_triples_json( raw = None items: list[Any] = [] if isinstance(raw, dict): - items = raw.get("triples") or raw.get("items") or raw.get("edges") or [] - elif isinstance(raw, list): - items = raw + items = raw.get("triples") or [] sc = (scene or "").strip().lower() or "" out: list[tuple[str, str, str]] = [] for it in items: if not isinstance(it, dict): continue - s = str(it.get("s") or it.get("subject") or "").strip() - p = str(it.get("p") or it.get("predicate") or "").strip() - o = str(it.get("o") or it.get("object") or "").strip() + s = str(it.get("s") or "").strip() + p = str(it.get("p") or "").strip() + o = str(it.get("o") or "").strip() if not p or not o: continue if p not in allowed: diff --git a/apps/api/app/services/agent_memory/schema.py b/apps/api/app/services/agent_memory/schema.py index f0e5a668..e3d51339 100644 --- a/apps/api/app/services/agent_memory/schema.py +++ b/apps/api/app/services/agent_memory/schema.py @@ -127,7 +127,7 @@ def slim_review_for_memory(review: dict[str, Any] | None) -> dict[str, Any]: out["overall"] = int(src.get("overall")) except (TypeError, ValueError): pass - action = str(src.get("action") or src.get("review_action") or "").strip() + action = str(src.get("action") or "").strip() if action: out["action"] = action summary = str(src.get("summary") or "").strip() @@ -357,7 +357,7 @@ def trim_short_turn(turn: dict[str, Any]) -> dict[str, Any] | None: role = str(turn.get("role") or "").strip().lower() if role not in ("user", "assistant"): return None - text = str(turn.get("text") or turn.get("content") or "").strip() + text = str(turn.get("text") or "").strip() if not text: return None if re_looks_like_markup(text): @@ -373,4 +373,4 @@ def trim_short_turn(turn: dict[str, Any]) -> dict[str, Any] | None: def re_looks_like_markup(text: str) -> bool: import re - return bool(re.search(r"|\{\s*\"tool_ops\"|\"ops\"\s*:", text, flags=re.I)) + return bool(re.search(r"|\{\s*\"tool_ops\"", text, flags=re.I)) diff --git a/apps/api/app/services/agent_memory/short_term.py b/apps/api/app/services/agent_memory/short_term.py index fd901a3e..cf4282c8 100644 --- a/apps/api/app/services/agent_memory/short_term.py +++ b/apps/api/app/services/agent_memory/short_term.py @@ -82,7 +82,7 @@ def assistant_facing_text(text: str, *, max_chars: int = 800) -> str: def normalize_turn_for_dialogue(turn: dict[str, Any], *, per_turn_chars: int) -> dict[str, Any] | None: role = str(turn.get("role") or "").strip().lower() - raw = str(turn.get("text") or turn.get("content") or "").strip() + raw = str(turn.get("text") or "").strip() if not raw or role not in ("user", "assistant"): return None text = assistant_facing_text(raw, max_chars=per_turn_chars) if role == "assistant" else raw[:per_turn_chars] @@ -278,7 +278,7 @@ def trim_turns_by_chars( lc_msgs: list[BaseMessage] = [] for t in turns: role = str(t.get("role") or "") - text = str(t.get("text") or t.get("content") or "") + text = str(t.get("text") or "") if role == "user": lc_msgs.append(HumanMessage(content=text)) elif role == "assistant": @@ -378,7 +378,7 @@ def update_dialogue_after_run( names: list[str] = [] for op in tool_ops_applied[:6]: if isinstance(op, dict): - n = str(op.get("name") or op.get("op") or "").strip() + n = str(op.get("name") or "").strip() if n: names.append(n) elif isinstance(op, str) and op.strip(): diff --git a/apps/api/app/services/agent_memory/subgoals.py b/apps/api/app/services/agent_memory/subgoals.py index ce1ce5e8..e93cb8dd 100644 --- a/apps/api/app/services/agent_memory/subgoals.py +++ b/apps/api/app/services/agent_memory/subgoals.py @@ -45,7 +45,7 @@ def normalize_item(raw: Any) -> dict[str, Any] | None: } if not isinstance(raw, dict): return None - text = str(raw.get("text") or raw.get("goal") or raw.get("title") or "").strip() + text = str(raw.get("text") or "").strip() if not text: return None status = str(raw.get("status") or "todo").strip().lower() @@ -136,7 +136,7 @@ def parse_subgoals_payload(raw: Any) -> list[str]: if isinstance(item, str) and item.strip(): out.append(item.strip()[:200]) elif isinstance(item, dict): - t = str(item.get("text") or item.get("goal") or "").strip() + t = str(item.get("text") or "").strip() if t: out.append(t[:200]) if len(out) >= 8: diff --git a/apps/api/app/services/chat_store.py b/apps/api/app/services/chat_store.py index 59ba9e1a..eb16e557 100644 --- a/apps/api/app/services/chat_store.py +++ b/apps/api/app/services/chat_store.py @@ -40,7 +40,7 @@ def _pack_message_meta(m: dict[str, Any]) -> str | None: content_marked = m.get("contentMarked") if isinstance(content_marked, str) and content_marked: meta["contentMarked"] = content_marked - # Normalize snake_case aliases once, then copy Ask/resume fields. + # Copy Ask / resume fields from the write payload. aliases = { "designTaskId": m.get("designTaskId"), "canResume": True if m.get("canResume") is True else None, @@ -92,7 +92,7 @@ def _copy_ask_fields(src: dict[str, Any], dest: dict[str, Any]) -> None: def _message_public(m: dict[str, Any], *, sort_fallback: int = 0) -> dict[str, Any]: - meta = _unpack_message_meta(m.get("meta_json") or m.get("metaJson") or m.get("meta")) + meta = _unpack_message_meta(m.get("meta_json")) # Flat fields on write payload also win when listing from in-memory upsert return. if m.get("durationMs") is not None and "durationMs" not in meta: try: diff --git a/apps/api/app/services/design/admin/admin_store.py b/apps/api/app/services/design/admin/admin_store.py index 0967d886..8f6f5ac2 100644 --- a/apps/api/app/services/design/admin/admin_store.py +++ b/apps/api/app/services/design/admin/admin_store.py @@ -919,111 +919,10 @@ def _normalize_agent_flow_graph(graph: dict[str, Any] | None) -> tuple[dict[str, ) changed = True - # Split prompt_bank → independent prompt_* nodes; never merge packs into one bank. - try: - from app.services.design.prompts.prompt_pack_store import ( - seed_prompt_overlay_nodes, - seed_prompt_bank_node, - KIND_LABELS as _PACK_LABELS, - ) - except Exception: - seed_prompt_overlay_nodes = None # type: ignore[assignment] - seed_prompt_bank_node = None # type: ignore[assignment] - _PACK_LABELS = {} - if seed_prompt_overlay_nodes is not None: - packs_from_bank: dict[str, Any] = {} - bank_n = next((n for n in nodes if str(n.get("id") or "") == "prompt_bank"), None) - if bank_n is not None and isinstance(bank_n.get("promptPacks"), dict): - for k, v in bank_n["promptPacks"].items(): - kk = str(k).strip() - if not kk: - continue - if isinstance(v, dict): - packs_from_bank[kk] = dict(v) - else: - packs_from_bank[kk] = {"body": str(v)} - if bank_n is not None: - nodes[:] = [n for n in nodes if str(n.get("id") or "") != "prompt_bank"] - ids.discard("prompt_bank") - edges[:] = [ - e - for e in edges - if str(e.get("source") or "") != "prompt_bank" - and str(e.get("target") or "") != "prompt_bank" - ] - changed = True - - seed_nodes = seed_prompt_overlay_nodes() - seed_by_kind = { - str(n.get("id") or "")[7:]: n - for n in seed_nodes - if str(n.get("id") or "").startswith("prompt_") - } - del packs_from_bank, seed_by_kind - - _KEEP_PROMPT = { - "prompt_react", - "prompt_plan", - "prompt_ask", - } - drop_scene = { - str(n.get("id") or "") - for n in nodes - if str(n.get("kind") or "").lower() == "prompt" - and str(n.get("id") or "").startswith("prompt_") - and str(n.get("id") or "") not in _KEEP_PROMPT - and not str(n.get("promptKey") or "").startswith("agent.prompt.") - } - if drop_scene: - nodes[:] = [n for n in nodes if str(n.get("id") or "") not in drop_scene] - edges[:] = [ - e - for e in edges - if str(e.get("source") or "") not in drop_scene - and str(e.get("target") or "") not in drop_scene - ] - ids -= drop_scene - changed = True - - # LLM/Agent: prompts live on dedicated prompt nodes, not on the model card. - for n in nodes: - kind = str(n.get("kind") or "").lower() - if kind not in {"llm", "agent"}: - continue - pk = str(n.get("promptKey") or "").strip() - pt = str(n.get("promptText") or "").strip() - if not pk and not pt: - continue - # Keep inject.specs reference; clear inline prompt fields on LLM. - if pk or pt: - n["promptKey"] = "" - n["promptText"] = "" - changed = True - - # Remap configRef soft-tags → runtime keys / clear. - _config_ref_aliases: dict[str, str] = {} - for n in nodes: - ref = str(n.get("configRef") or "").strip() - if not ref: - continue - pk = str(n.get("phaseKey") or "").strip() - if ref == "models+routes": - # Soft tag removed; only model_route nodes keep the real runtime key. - n["configRef"] = ( - "precheck.model_threshold" if pk == "model_route" else "" - ) - changed = True - continue - nxt = _config_ref_aliases.get(ref) - if nxt and nxt != ref: - n["configRef"] = nxt - changed = True - - # Expand「资源并行网关」→ 并行 + 工具 + 汇聚(删除 resource_fork 合成节点)。 + # Expand parallel gateway → 并行 + 工具 + 汇聚. edge_ids = {str(e.get("id") or "") for e in edges} if "thought" in ids and ( - "resource_fork" in ids - or "parallel" in ids + "parallel" in ids or "resource_join" in ids or "tool_details" in ids ): @@ -1049,45 +948,12 @@ def _ensure_node(spec: dict[str, Any]) -> None: if str(hit.get("kind") or "") == "resource" and nid == "parallel": hit["kind"] = "parallel" changed = True - if nid == "parallel" and str(hit.get("phaseKey") or "") in ("", "resource_fork"): - # Runtime still gathers via resource_fork handler on this node id→phase map. - hit["phaseKey"] = "resource_fork" + if nid == "parallel" and not str(hit.get("phaseKey") or "").strip(): + hit["phaseKey"] = "parallel" hit["kind"] = "parallel" hit["label"] = hit.get("label") or "并行网关" changed = True - # Retire resource_fork id: rename into parallel when needed. - if "resource_fork" in ids and "parallel" not in ids: - for n in nodes: - if str(n.get("id") or "") != "resource_fork": - continue - n["id"] = "parallel" - n["kind"] = "parallel" - n["capability"] = "control" - n["phaseKey"] = "resource_fork" - lab = str(n.get("label") or "").strip() - n["label"] = "并行网关" if (not lab or "资源" in lab) else lab - n["description"] = "分叉拉取工具详情;运行时 gather 后汇聚" - break - for e in edges: - if str(e.get("source") or "") == "resource_fork": - e["source"] = "parallel" - if str(e.get("target") or "") == "resource_fork": - e["target"] = "parallel" - ids.discard("resource_fork") - ids.add("parallel") - changed = True - elif "resource_fork" in ids and "parallel" in ids: - # Drop duplicate gateway; rewire to parallel. - for e in edges: - if str(e.get("source") or "") == "resource_fork": - e["source"] = "parallel" - if str(e.get("target") or "") == "resource_fork": - e["target"] = "parallel" - nodes[:] = [n for n in nodes if str(n.get("id") or "") != "resource_fork"] - ids.discard("resource_fork") - changed = True - _ensure_node( { "id": "parallel", @@ -1095,7 +961,7 @@ def _ensure_node(spec: dict[str, Any]) -> None: "description": "分叉拉取工具详情;运行时 gather 后汇聚", "kind": "parallel", "capability": "control", - "phaseKey": "resource_fork", + "phaseKey": "parallel", "x": tx + 280, "y": ty, } @@ -1270,17 +1136,6 @@ def _ensure_edge( is_default=False, ) - # Drop obsolete need_resources → resource_fork single edge if still present. - edges[:] = [ - e - for e in edges - if not ( - str(e.get("source") or "") == "thought" - and str(e.get("condition") or "") == "need_resources" - ) - ] - edge_ids = {str(e.get("id") or "") for e in edges} - # Also wire orphan prompt nodes when parallel/join already exist (draft without re-expand). if "parallel" in ids and "resource_join" in ids: edge_ids = {str(e.get("id") or "") for e in edges} @@ -1905,21 +1760,6 @@ def _fix_mode_fork_edge( ): e["condition"] = "intent=ask&no_ops" changed = True - # 合并历史拆出的 confirm_* → clarify(同 phaseKey,功能重复) - _dup_confirm = {"confirm_resources", "confirm_hydrate", "confirm_retry"} - if ids & _dup_confirm: - for e in edges: - tgt = str(e.get("target") or "") - if tgt in _dup_confirm: - e["target"] = "clarify" - changed = True - src = str(e.get("source") or "") - if src in _dup_confirm: - e["source"] = "clarify" - changed = True - nodes[:] = [n for n in nodes if str(n.get("id")) not in _dup_confirm] - ids -= _dup_confirm - changed = True _add_edge( "e_ask_chat", "ask_thought", @@ -1951,65 +1791,15 @@ def _fix_mode_fork_edge( priority=43, ) if "action" in ids: - for e in edges: - if str(e.get("source") or "") != "ask_thought": - continue - cond = str(e.get("condition") or "") - tgt = str(e.get("target") or "") - # Legacy Ask: has_ops → propose. Clear edits paint immediately. - if cond in ("mode=ask&has_ops", "mode=ask&ops_valid") or ( - tgt == "propose" and "ask" in cond and "ops" in cond - ): - if tgt != "action" or cond != "mode=ask&ops_valid": - e["target"] = "action" - e["condition"] = "mode=ask&ops_valid" - e["label"] = e.get("label") or "明确需求直接改" - e["isDefault"] = False - try: - pri = int(e.get("priority", 100)) - except (TypeError, ValueError): - pri = 100 - if pri >= 20: - e["priority"] = 9 - changed = True - break - else: - _add_edge( - "e_ask_propose", - "ask_thought", - "action", - condition="mode=ask&ops_valid", - priority=9, - ) - - # Collapse leaf model nodes (simple/medium/complex/vision/multimodal) - # back into model_route → thought. Tier/vision models live in routeConfig. - _LEAF_MODEL_IDS = { - "model_simple", - "model_medium", - "model_complex", - "model_vision", - "model_multimodal", - } - - def _is_leaf_model(n: dict[str, Any]) -> bool: - nid = str(n.get("id") or "") - pk = str(n.get("phaseKey") or "") - return nid in _LEAF_MODEL_IDS or pk in _LEAF_MODEL_IDS + _add_edge( + "e_ask_propose", + "ask_thought", + "action", + condition="mode=ask&ops_valid", + priority=9, + ) ids = {str(n.get("id")) for n in nodes} - leaf_nodes = [n for n in nodes if _is_leaf_model(n)] - if leaf_nodes: - leaf_ids = {str(n.get("id")) for n in leaf_nodes} - nodes[:] = [n for n in nodes if str(n.get("id")) not in leaf_ids] - edges[:] = [ - e - for e in edges - if str(e.get("source") or "") not in leaf_ids - and str(e.get("target") or "") not in leaf_ids - ] - ids = {str(n.get("id")) for n in nodes} - changed = True if "model_route" in ids and "ask_thought" in ids: has_ask_lane = any( @@ -2837,8 +2627,8 @@ def _parse_task_meta(raw: Any) -> dict[str, Any]: return {} -def _skills_from_meta(decision: dict[str, Any], exec_log: dict[str, Any]) -> list[str]: - raw = exec_log.get("skills_loaded") or decision.get("skills_loaded") or [] +def _skills_from_meta(exec_log: dict[str, Any]) -> list[str]: + raw = exec_log.get("skills_loaded") or [] if isinstance(raw, str) and raw.strip(): try: raw = json.loads(raw) @@ -2991,16 +2781,14 @@ def skill_metrics_summary() -> dict[str, Any]: ) route_m = re.match(r"^(agent_graph(?:_ask|_chat)?)(?::v\d+)?$", route_raw) route = route_m.group(1) if route_m else route_raw - intent = str( - decision.get("intent") or exec_log.get("intent") or "" - ).strip().lower() or "unknown" + intent = str(decision.get("intent") or "").strip().lower() or "unknown" _bucket_inc(route_stats, route, failed=failed_b, ok=ok_b, tokens=tok) _bucket_inc(intent_stats, intent, failed=failed_b, ok=ok_b, tokens=tok) - painted = bool(exec_log.get("painted") or decision.get("tool_ops_applied")) + painted = bool(exec_log.get("painted")) ops_count = int(exec_log.get("ops_count") or 0) round_i = int(exec_log.get("round") or 0) - skills_used = _skills_from_meta(decision, exec_log) + skills_used = _skills_from_meta(exec_log) if meta: with_meta_n += 1 if painted: @@ -3082,19 +2870,13 @@ def skill_metrics_summary() -> dict[str, Any]: } -def _parse_flow_version(*, route: Any, control: Any, exec_log: dict[str, Any], meta: dict[str, Any]) -> int | None: - for raw in (meta.get("flow_version"), exec_log.get("flow_version")): - try: - n = int(raw) - if n > 0: - return n - except (TypeError, ValueError): - pass - for raw in (route, control): - s = str(raw or "") - m = re.search(r":v(\d+)\s*$", s, re.I) - if m: - return int(m.group(1)) +def _parse_flow_version(raw: Any) -> int | None: + try: + n = int(raw) + if n > 0: + return n + except (TypeError, ValueError): + pass return None @@ -3140,10 +2922,8 @@ def _cell(r: Any, name: str) -> Any: for r in rows: route_v = _json_scalar(_cell(r, "dl_route")) control_v = _json_scalar(_cell(r, "control")) - exec_flow = _json_scalar(_cell(r, "el_flow")) meta_flow = _json_scalar(_cell(r, "flow_id")) skills = _skills_from_meta( - {"skills_loaded": _json_scalar(_cell(r, "dl_skills"))}, {"skills_loaded": _json_scalar(_cell(r, "el_skills"))}, ) created_at = _cell(r, "created_at") @@ -3151,26 +2931,18 @@ def _cell(r: Any, name: str) -> Any: items.append( { "taskId": _cell(r, "id"), - "traceId": _json_scalar(_cell(r, "trace_id")) - or _json_scalar(_cell(r, "dl_trace")) - or _json_scalar(_cell(r, "el_trace")), + "traceId": _json_scalar(_cell(r, "dl_trace")), "userId": _cell(r, "user_id"), "scene": _cell(r, "scene"), "status": _cell(r, "status"), "route": route_v, - "intent": _json_scalar(_cell(r, "dl_intent")) - or _json_scalar(_cell(r, "el_intent")), + "intent": _json_scalar(_cell(r, "dl_intent")), "prompt": _cell(r, "prompt"), "decisionLog": None, "executionLog": None, "control": control_v, - "flowId": meta_flow or exec_flow, - "flowVersion": _parse_flow_version( - route=route_v, - control=control_v, - exec_log={"flow_id": exec_flow} if exec_flow else {}, - meta={"flow_id": meta_flow} if meta_flow else {}, - ), + "flowId": meta_flow, + "flowVersion": _parse_flow_version(_cell(r, "flow_version")), "opsCount": _json_int(_cell(r, "ops_count")), "totalTokens": _json_int(_cell(r, "total_tokens")), "durationMs": _json_int(_cell(r, "total_duration_ms")), @@ -3276,24 +3048,19 @@ def get_decision_log(task_id: str) -> dict[str, Any] | None: ] return { "taskId": r.id, - "traceId": meta.get("trace_id") or decision.get("trace_id") or exec_log.get("trace_id"), + "traceId": decision.get("trace_id"), "userId": r.user_id, "scene": r.scene, "status": r.status, "route": decision.get("route"), - "intent": decision.get("intent") or exec_log.get("intent"), + "intent": decision.get("intent"), "prompt": r.prompt, "decisionLog": decision, "executionLog": exec_log or None, "langfuse": langfuse or None, "control": meta.get("control"), - "flowId": meta.get("flow_id") or exec_log.get("flow_id"), - "flowVersion": _parse_flow_version( - route=decision.get("route"), - control=meta.get("control"), - exec_log=exec_log, - meta=meta, - ), + "flowId": meta.get("flow_id"), + "flowVersion": _parse_flow_version(meta.get("flow_version")), "opsCount": exec_log.get("ops_count"), "totalTokens": exec_log.get("total_tokens"), "durationMs": duration_ms, @@ -3303,7 +3070,7 @@ def get_decision_log(task_id: str) -> dict[str, Any] | None: "taskTier": exec_log.get("task_tier"), "visionUsed": exec_log.get("vision_used"), "model": exec_log.get("model"), - "skills": _skills_from_meta(decision, exec_log), + "skills": _skills_from_meta(exec_log), "error": r.error_message, "createdAt": int(float(r.created_at) * 1000) if r.created_at else None, "updatedAt": int(float(r.updated_at) * 1000) if r.updated_at else None, diff --git a/apps/api/app/services/design/export_render.py b/apps/api/app/services/design/export_render.py index 9cd9b528..9a677e8b 100644 --- a/apps/api/app/services/design/export_render.py +++ b/apps/api/app/services/design/export_render.py @@ -98,11 +98,10 @@ def _attrs(node: dict[str, Any]) -> dict[str, Any]: def _node_box(node: dict[str, Any]) -> tuple[float, float, float, float]: - attrs = _attrs(node) - x = _num(node.get("x"), _num(attrs.get("x"))) - y = _num(node.get("y"), _num(attrs.get("y"))) - w = max(1.0, _num(node.get("width"), _num(attrs.get("width"), 1.0))) - h = max(1.0, _num(node.get("height"), _num(attrs.get("height"), 1.0))) + x = _num(node.get("x")) + y = _num(node.get("y")) + w = max(1.0, _num(node.get("width"), 1.0)) + h = max(1.0, _num(node.get("height"), 1.0)) return x, y, w, h @@ -117,17 +116,15 @@ def _inside_frame(node: dict[str, Any], frame: dict[str, Any]) -> bool: def _image_src(node: dict[str, Any]) -> str: - attrs = _attrs(node) - for key in ("src", "url", "href", "xlink:href"): - raw = str(attrs.get(key) or node.get(key) or "").strip() - if raw.startswith(("http://", "https://", "data:image/")): - return raw + raw = str(_attrs(node).get("src") or "").strip() + if raw.startswith(("http://", "https://", "data:image/")): + return raw return "" def _fill_color(node: dict[str, Any]) -> tuple[int, int, int, int] | None: attrs = _attrs(node) - raw = attrs.get("fill") or node.get("fill") or attrs.get("backgroundColor") + raw = attrs.get("fill-color") if raw is None: return None s = str(raw).strip().lower() @@ -137,13 +134,7 @@ def _fill_color(node: dict[str, Any]) -> tuple[int, int, int, int] | None: def _node_z(node: dict[str, Any]) -> int: - attrs = _attrs(node) - return int( - _num( - node.get("z"), - _num(node.get("zIndex"), _num(attrs.get("z"), _num(attrs.get("zIndex")))), - ) - ) + return int(_num(node.get("z"))) def _json_list(raw: Any) -> list[Any]: @@ -187,10 +178,9 @@ def _text_plain(attrs: dict[str, Any]) -> str: if data: return data - for key in ("markdown", "text", "content"): - raw = attrs.get(key) - if isinstance(raw, str) and raw.strip(): - return raw + md = attrs.get("markdown") + if isinstance(md, str) and md.strip(): + return md.strip() return "" diff --git a/apps/api/app/services/design/intelligence_runtime.py b/apps/api/app/services/design/intelligence_runtime.py index 58dd9849..444da6ff 100644 --- a/apps/api/app/services/design/intelligence_runtime.py +++ b/apps/api/app/services/design/intelligence_runtime.py @@ -51,9 +51,7 @@ def apply_intelligence_result( else: apply_reference_intelligence( rt, - compile_reference_intelligence( - data, data.get("visual_dna") or data.get("dna") - ), + compile_reference_intelligence(data, data.get("visual_dna")), ) return data diff --git a/apps/api/app/services/design/ops/tool_ops_contract.py b/apps/api/app/services/design/ops/tool_ops_contract.py index 4557b393..95308305 100644 --- a/apps/api/app/services/design/ops/tool_ops_contract.py +++ b/apps/api/app/services/design/ops/tool_ops_contract.py @@ -48,11 +48,8 @@ def _looks_like_css_gradient(raw: object) -> bool: def _validate_shape_fill_args(name: str, args: dict[str, Any]) -> str | None: """Reject CSS gradient strings; require native fillType + fill/fillEnd.""" - fill_keys = ("fill", "fillColor", "backgroundColor", "color") - for key in fill_keys: - if key not in args or args.get(key) is None: - continue - val = args.get(key) + if "fill" in args and args.get("fill") is not None: + val = args.get("fill") if _looks_like_css_gradient(val): return format_op_error( f"{name}_css_gradient_fill", @@ -61,7 +58,7 @@ def _validate_shape_fill_args(name: str, args: dict[str, Any]) -> str | None: "use fillType=linear|radial|angular|diffuse with fill + fillEnd " "(+ gradientAngle?)" ), - detail=f"{key}={str(val)[:96]}", + detail=f"fill={str(val)[:96]}", ) fill_type_raw = args.get("fillType") if fill_type_raw is not None and str(fill_type_raw).strip(): @@ -156,19 +153,6 @@ def allowed_canvas_tool_keys() -> frozenset[str]: ) -# Models often invent singular / snake variants; map to registry keys. -_OP_NAME_ALIASES: dict[str, str] = { - "delete_node": "delete_nodes", - "remove_node": "delete_nodes", - "remove_nodes": "delete_nodes", -} - - -def _canonicalize_op_name(name: str) -> str: - key = str(name or "").strip() - return _OP_NAME_ALIASES.get(key, key) - - def format_canvas_tools_for_model(rules: dict[str, str] | None = None) -> str: """Capability block for LLM prompts — Action registry (+ schema + hint).""" del rules # allowlist = design_canvas_tool.enabled only @@ -335,18 +319,20 @@ def _max_ops_per_step(rules: dict[str, str] | None) -> int: def _coerce_op_args(item: dict[str, Any]) -> dict[str, Any]: - """Normalize one tool_op to an ``args`` dict.""" + """Canvas args only — ``op_id`` lives on the op envelope.""" nested = item.get("args") - if isinstance(nested, dict): - args = dict(nested) - else: - args = {} - op_id = item.get("op_id") - if op_id is not None and str(op_id).strip(): - args["op_id"] = str(op_id).strip()[:64] + args = dict(nested) if isinstance(nested, dict) else {} + args.pop("op_id", None) return args +def _envelope_op_id(item: dict[str, Any]) -> str: + raw = item.get("op_id") + if raw is None: + return "" + return str(raw).strip()[:64] + + def _parse_raw_ops(content: str | dict[str, Any] | list[Any] | None) -> list[dict[str, Any]]: """Parse model JSON into raw op dicts (before allowlist / validation).""" if isinstance(content, (dict, list)): @@ -364,15 +350,18 @@ def _parse_raw_ops(content: str | dict[str, Any] | list[Any] | None) -> list[dic for item in ops_raw: if not isinstance(item, dict): continue - name = _canonicalize_op_name(item.get("name") or "") + name = str(item.get("name") or "").strip() if not name: continue - out.append({"name": name, "args": _coerce_op_args(item)}) + row = {"name": name, "args": _coerce_op_args(item)} + oid = _envelope_op_id(item) + if oid: + row["op_id"] = oid + out.append(row) return out -def _stable_op_id(name: str, args: dict[str, Any], index: int) -> str: - existing = args.get("op_id") +def _stable_op_id(name: str, args: dict[str, Any], index: int, existing: str = "") -> str: if existing: return str(existing).strip()[:64] try: @@ -819,7 +808,7 @@ def normalize_agent_tool_ops( classified_intent: str | None = None, ) -> tuple[list[dict[str, Any]], list[str]]: """ - Allowlist + alias normalize + per-op validation + op_id + dedupe. + Allowlist + per-op validation + op_id + dedupe. Semantic mistakes are rejected with errors for the model to re-emit — never silently rewritten (no create→update morph, no inventing nodeId). @@ -877,7 +866,11 @@ def normalize_agent_tool_ops( ) ) continue - working.append({"name": name, "args": args}) + row = {"name": name, "args": args} + oid = _envelope_op_id(item) + if oid: + row["op_id"] = oid + working.append(row) # Validate intent — reject, do not rewrite into a "fixed" op. working, morph_errs = _reject_shape_morph_ops(working) @@ -901,8 +894,7 @@ def normalize_agent_tool_ops( if err: errors.append(err) continue - op_id = _stable_op_id(name, args, idx) - args["op_id"] = op_id + op_id = _stable_op_id(name, args, idx, _envelope_op_id(item)) normalized.append({"name": name, "args": args, "op_id": op_id}) # Dedupe by op_id (SSE replay / model duplicates). @@ -1199,9 +1191,8 @@ def tool_ops_for_sse(ops: list[dict[str, Any]]) -> list[dict[str, Any]]: for op in ops: name = op.get("name") args = dict(op.get("args") or {}) - oid = op.get("op_id") or args.get("op_id") - if oid: - args["op_id"] = oid + args.pop("op_id", None) + oid = op.get("op_id") if name == "create_shape" and args.get("path") is not None: path = str(args.get("path") or "") logger.info( @@ -1278,18 +1269,18 @@ def tidy_tool_ops_scene( nid = str(row.get("id") or "").strip() if not nid: continue - ntype = str(row.get("type") or row.get("nodeType") or "").lower() - text = str(row.get("text") or row.get("content") or "").strip() + text = str(row.get("text") or "").strip() + ntype = str(row.get("type") or "").lower() # Drop empty text nodes. - if ntype in ("text", "textbox") and not text: + if ntype == "text" and not text: delete_ids.append(nid) notes.append(f"drop_empty_text:{nid[:8]}") continue x = _num(row.get("x")) y = _num(row.get("y")) - nw = max(1.0, _num(row.get("width") or row.get("w"), 1.0)) - nh = max(1.0, _num(row.get("height") or row.get("h"), 1.0)) + nw = max(1.0, _num(row.get("w"), 1.0)) + nh = max(1.0, _num(row.get("h"), 1.0)) if clamp_geometry: # Clamp into artboard (create path with frame-local coords only). cx = min(max(0.0, x), float(w - 1)) @@ -1307,23 +1298,23 @@ def tidy_tool_ops_scene( or abs(ch - nh) > 0.5 ) if clamped: - row["x"], row["y"], row["width"], row["height"] = cx, cy, cw, ch + row["x"], row["y"], row["w"], row["h"] = cx, cy, cw, ch + oid = f"tidy-clamp-{nid}" args = { "nodeId": nid, "x": round(cx, 2), "y": round(cy, 2), "width": round(cw, 2), "height": round(ch, 2), - "op_id": f"tidy-clamp-{nid}", } - ops.append({"name": "update_node", "args": args, "op_id": args["op_id"]}) + ops.append({"name": "update_node", "args": args, "op_id": oid}) notes.append(f"clamp:{nid[:8]}") fill = str(row.get("fill") or "").strip().lower() fp = ( f"{ntype}|{fill}|{int(round(_num(row.get('x'))))}|" - f"{int(round(_num(row.get('y'))))}|{int(round(_num(row.get('width') or row.get('w'), 1)))}|" - f"{int(round(_num(row.get('height') or row.get('h'), 1)))}|{text[:24]}" + f"{int(round(_num(row.get('y'))))}|{int(round(_num(row.get('w'), 1)))}|" + f"{int(round(_num(row.get('h'), 1)))}|{text[:24]}" ) if fp in seen_fp and ntype not in ("frame", "artboard", "group"): delete_ids.append(nid) @@ -1337,7 +1328,7 @@ def tidy_tool_ops_scene( ops.append( { "name": "delete_nodes", - "args": {"nodeIds": delete_ids, "op_id": oid}, + "args": {"nodeIds": delete_ids}, "op_id": oid, } ) diff --git a/apps/api/app/services/design/prompts/prompt_build.py b/apps/api/app/services/design/prompts/prompt_build.py index f5109a1d..4ce0ecc2 100644 --- a/apps/api/app/services/design/prompts/prompt_build.py +++ b/apps/api/app/services/design/prompts/prompt_build.py @@ -18,14 +18,14 @@ def _bg_candidate_from_nodes(nodes: list[dict[str, Any]]) -> dict[str, Any] | No if not isinstance(n, dict) or not n.get("id"): continue try: - w = float(n.get("w") or n.get("width") or 0) - h = float(n.get("h") or n.get("height") or 0) + w = float(n.get("w") or 0) + h = float(n.get("h") or 0) except (TypeError, ValueError): continue area = w * h if area <= best_area: continue - fill = n.get("fill") or n.get("backgroundColor") + fill = n.get("fill") if not fill: continue best = n diff --git a/apps/api/app/services/design/prompts/prompt_pack_store.py b/apps/api/app/services/design/prompts/prompt_pack_store.py index 47829f6d..fcc309ea 100644 --- a/apps/api/app/services/design/prompts/prompt_pack_store.py +++ b/apps/api/app/services/design/prompts/prompt_pack_store.py @@ -300,7 +300,7 @@ def is_need_prompt_kind(kind: str) -> bool: def is_need_pack(row: dict[str, Any]) -> bool: """Need pack is determined by pack ``type`` code.""" - t = str(row.get("type") or row.get("pack_type") or "").strip().lower() + t = str(row.get("pack_type") or "").strip().lower() return t == PACK_TYPE_NEED @@ -334,71 +334,6 @@ def _get(key: str, default: Any = None) -> Any: } -def seed_prompt_overlay_nodes(*, x0: float = 2280, y0: float = 80, dy: float = 140) -> list[dict[str, Any]]: - """Seed need_* prompt overlay nodes (if any remain in seed).""" - out: list[dict[str, Any]] = [] - i = 0 - for item in _SEED: - kind = str(item.get("kind") or "").strip() - pack_type = normalize_pack_type(item.get("type"), kind=kind) - if pack_type != PACK_TYPE_NEED: - continue - title = str(item.get("title") or KIND_LABELS.get(kind, kind)) - when = str(item.get("when_to_use") or "") - scenes = str(item.get("scenes") or "") - body = str(item.get("body") or "") - out.append( - { - "id": f"prompt_{kind}", - "label": title, - "description": when, - "kind": "prompt", - "capability": "prompt", - "phaseKey": f"prompt_{kind}", - "configRef": f"pack.{kind}", - "promptText": body, - "inject": { - "mode": "details", - "source": "prompt", - "scenes": scenes, - }, - "x": x0, - "y": y0 + i * dy, - } - ) - i += 1 - return out - - -def seed_prompt_bank_node(*, x: float = 2280, y: float = 400) -> dict[str, Any]: - """Deprecated helper: packs dict only (for splitting old prompt_bank graphs).""" - packs: dict[str, Any] = {} - for item in _SEED: - kind = str(item.get("kind") or "").strip() - if normalize_pack_type(item.get("type"), kind=kind) != PACK_TYPE_NEED: - continue - packs[kind] = { - "title": str(item.get("title") or KIND_LABELS.get(kind, kind)), - "whenToUse": str(item.get("when_to_use") or ""), - "scenes": str(item.get("scenes") or ""), - "body": str(item.get("body") or ""), - } - return { - "id": "prompt_bank", - "label": "场景提示词", - "description": "已废弃:请拆成独立 prompt_* 节点", - "kind": "prompt", - "capability": "prompt", - "phaseKey": "prompt_bank", - "configRef": "prompt_bank", - "promptPacks": packs, - "promptText": "", - "inject": {"mode": "details", "source": "prompt"}, - "x": x, - "y": y, - } - - def _prune_prompt_packs_to_seed(session: Session, *, now: float) -> None: """Drop obsolete scene packs; leave system keys alone.""" del now @@ -514,7 +449,7 @@ def _apply_seed_fields_to_row(row: Any, seed_item: dict[str, Any], *, kind: str, if str(row.scenes or "").strip() != want_scenes: row.scenes = want_scenes changed = True - want_used = used_by_csv(seed_item.get("usedBy") or seed_item.get("used_by")) + want_used = used_by_csv(seed_item.get("usedBy")) if str(row.used_by or "").strip() != want_used: row.used_by = want_used changed = True diff --git a/apps/api/app/services/design/prompts/skill_store/pack_io.py b/apps/api/app/services/design/prompts/skill_store/pack_io.py index 3106abda..f2a39df6 100644 --- a/apps/api/app/services/design/prompts/skill_store/pack_io.py +++ b/apps/api/app/services/design/prompts/skill_store/pack_io.py @@ -357,13 +357,8 @@ def _skill_item_from_parts( or meta.get("displayName") or key ).strip() or key - description = str( - loc.get("description") - or meta.get("description") - or meta.get("when_to_use") - or "" - ).strip() - when = str(meta.get("when_to_use") or description).strip() + description = str(loc.get("description") or meta.get("description") or "").strip() + when = str(meta.get("when_to_use") or "").strip() pos = body.strip() if not pos: return None @@ -586,7 +581,7 @@ def _eval_task_issues(row: dict[str, Any]) -> list[str]: out: list[str] = [] for item in raw: if isinstance(item, dict): - text = str(item.get("issue") or item.get("text") or "").strip() + text = str(item.get("issue") or "").strip() else: text = str(item or "").strip() if text: @@ -853,8 +848,8 @@ def build_skill_ab_experiment( a_in = variant_a if isinstance(variant_a, dict) else {} b_in = variant_b if isinstance(variant_b, dict) else {} # Spec default: poster_craft V12-A Hero 60–80% vs V12-B Hero 55–75%. - a_band = str(a_in.get("hero_band") or a_in.get("band") or "60–80%").strip() - b_band = str(b_in.get("hero_band") or b_in.get("band") or "55–75%").strip() + a_band = str(a_in.get("hero_band") or "60–80%").strip() + b_band = str(b_in.get("hero_band") or "55–75%").strip() a_id = str(a_in.get("id") or f"V{base_v}-A").strip() b_id = str(b_in.get("id") or f"V{base_v}-B").strip() a_md = str(a_in.get("md") or "").strip() or _replace_or_insert_hero_band( diff --git a/apps/api/app/services/design/prompts/skill_store/runtime.py b/apps/api/app/services/design/prompts/skill_store/runtime.py index e57ff079..496a2052 100644 --- a/apps/api/app/services/design/prompts/skill_store/runtime.py +++ b/apps/api/app/services/design/prompts/skill_store/runtime.py @@ -48,27 +48,14 @@ def runtime_skill_keys() -> frozenset[str]: if _c._RUNTIME_SKILL_KEYS is not None: return _c._RUNTIME_SKILL_KEYS keys = {str(k).strip() for k in _SEED_BY_KEY if str(k).strip()} - # Qualified aliases for core. - for k in list(keys): - keys.add(f"{NS_CORE}.{k}") try: with Session(core_db.engine) as session: rows = crud.list_design_skill_keys_enabled(session=session) - for k, ns_raw in rows: + for k, _ns_raw in rows: k = str(k or "").strip() if not k: continue keys.add(k) - ns = _normalize_namespace(ns_raw, source=None) - # If row has bare key, also accept qualified form. - ns_prefix, local = split_namespace_key(k) - if not ns_prefix: - keys.add(f"{ns}.{k}") - if ns == NS_CORE: - keys.add(k) - else: - keys.add(local) - keys.add(k) except Exception: pass _c._RUNTIME_SKILL_KEYS = frozenset(keys) @@ -303,10 +290,6 @@ def resolve_storage_skill_key(raw: str, *, scene: str = "") -> str | None: s = base.strip().lower() if not s: return None - if s.startswith("skill."): - s = s[6:] - if s.startswith("skill_"): - s = s[6:] ns, local = split_namespace_key(s) rows = list_runtime_skills(scene=scene, enabled_only=True) by_key = {str(r.get("skillKey") or "").strip().lower(): r for r in rows} @@ -376,11 +359,7 @@ def format_skills_catalog( ver = int(r.get("version") or 1) ns = str(r.get("namespace") or NS_USER) kind = str(r.get("skillKind") or skill_kind_for_namespace(ns)) - q = str(r.get("qualifiedKey") or key) - line = f"- `{key}` [{ns}/{kind}] v{ver}" - if q != key: - line += f" alias:`{q}`" - line += f" — {name}" + line = f"- `{key}` [{ns}/{kind}] v{ver} — {name}" if when: line += f"({when[:80]})" lines.append(line) @@ -565,7 +544,7 @@ def _skill_body_for_context(row: dict[str, Any], *, role: str = "paint") -> str: key = str(row.get("skillKey") or "").strip().lower() graph = _SKILL_GRAPH.get(key) or {} category = str(row.get("category") or graph.get("category") or "agent").lower() - mode = str(row.get("contextMode") or graph.get("context_mode") or "full").lower() + mode = str(row.get("contextMode") or "full").lower() body = str(row.get("promptPositive") or "").strip() rules = str(graph.get("rules_excerpt") or "").strip() review_docs = str(graph.get("review_docs") or "").strip() @@ -587,9 +566,7 @@ def _skill_body_for_context(row: dict[str, Any], *, role: str = "paint") -> str: def _skill_available_for_context(row: dict[str, Any], *, role: str) -> bool: """Do not inject review-only curricula into the action stage.""" - key = str(row.get("skillKey") or "").strip().lower() - graph = _SKILL_GRAPH.get(key) or {} - mode = str(row.get("contextMode") or graph.get("context_mode") or "full").lower() + mode = str(row.get("contextMode") or "full").lower() if role == "paint" and mode == "review": return False return True @@ -745,7 +722,7 @@ def row_sort_key(r: dict[str, Any]) -> tuple[int, int, str]: def _normalize_loaded_skill_keys( skill_keys: list[str], *, scene: str = "" ) -> set[str]: - """Map need_skills refs (bare / namespaced / aliases) → storage skill_keys.""" + """Map need_skills refs (bare / namespaced) → storage skill_keys.""" raw = {str(k).strip().lower() for k in skill_keys if str(k).strip()} if not raw: return set() @@ -1011,19 +988,10 @@ def parse_need_skills_with_pins( continue if key in ("all", "*"): return ["*"], {}, {}, errs - if key.startswith("skill."): - key = key[6:] - if key.startswith("skill_"): - key = key[6:] storage = resolve_storage_skill_key(key, scene=scene) or key - if known and storage not in known and key not in known and f"core.{key}" not in known: - # Also accept qualified forms already in known - ns, local = split_namespace_key(key) - alt = f"{ns}.{local}" if ns else f"core.{key}" - if alt not in known and storage not in known: - errs.append(f"skill_unknown:{key_raw}") - continue - storage = resolve_storage_skill_key(key, scene=scene) or storage + if known and storage not in known: + errs.append(f"skill_unknown:{key_raw}") + continue if storage in seen: continue seen.add(storage) @@ -1108,7 +1076,7 @@ def _rule_matches( if int(prompt_chars or 0) < need: return False - raw_intents = rule.get("intent_in") or rule.get("intents") + raw_intents = rule.get("intent_in") if raw_intents is not None: if isinstance(raw_intents, str): want = {p.strip().lower() for p in raw_intents.split(",") if p.strip()} @@ -1121,7 +1089,7 @@ def _rule_matches( if want and not intent_l: return False - raw_includes = rule.get("prompt_includes_any") or rule.get("promptIncludesAny") + raw_includes = rule.get("prompt_includes_any") if raw_includes is not None: if isinstance(raw_includes, str): needles = [p.strip().lower() for p in raw_includes.split(",") if p.strip()] @@ -1139,10 +1107,8 @@ def _rule_matches( "empty_canvas", "has_images", "intent_in", - "intents", "min_prompt_chars", "prompt_includes_any", - "promptIncludesAny", } return bool(keys) diff --git a/apps/api/app/services/design/prompts/skill_store/user_skills.py b/apps/api/app/services/design/prompts/skill_store/user_skills.py index 3d4fca9d..33f038c1 100644 --- a/apps/api/app/services/design/prompts/skill_store/user_skills.py +++ b/apps/api/app/services/design/prompts/skill_store/user_skills.py @@ -561,13 +561,8 @@ def _pack_display_fields(meta: dict[str, Any], *, local: str) -> tuple[str, str, or meta.get("displayName") or local ).strip() or local - description = str( - loc.get("description") - or meta.get("description") - or meta.get("when_to_use") - or "" - ).strip() - when = str(meta.get("when_to_use") or description).strip() + description = str(loc.get("description") or meta.get("description") or "").strip() + when = str(meta.get("when_to_use") or "").strip() return display, description, when def _pack_logo_url(meta: dict[str, Any]) -> str | None: diff --git a/apps/api/app/services/design/runtime/agent_profile.py b/apps/api/app/services/design/runtime/agent_profile.py index 09d4b201..eca95ac8 100644 --- a/apps/api/app/services/design/runtime/agent_profile.py +++ b/apps/api/app/services/design/runtime/agent_profile.py @@ -235,7 +235,7 @@ def _parse_stage_spec(raw: Any, *, default_mode_overlay: bool) -> StagePromptSpe return StagePromptSpec(protocol=protocol, mode_overlay=default_mode_overlay) if not isinstance(raw, dict): return None - protocol = _as_text(raw.get("protocol") or raw.get("pack") or "") + protocol = _as_text(raw.get("protocol") or "") if not protocol: return None mode = raw.get("mode_overlay") @@ -514,7 +514,7 @@ def _add(kind: str, body: Any, *, default_id: str) -> None: f"{source}: roles {rid!r} isolation {isolation!r} not live " f"(supported: {', '.join(sorted(_LIVE_ROLE_ISOLATIONS))})" ) - subagent_id = _as_text(body.get("subagent") or body.get("subagent_id")) or None + subagent_id = _as_text(body.get("subagent")) or None if isolation == "forked_context" and not subagent_id: subagent_id = rid roles.append( @@ -598,20 +598,8 @@ def _parse_subagents(raw: dict[str, Any], *, source: str) -> tuple[SubAgentDef, f"(supported: {', '.join(sorted(_LIVE_SUBAGENT_ISOLATIONS))})" ) stage = _as_text(body.get("stage"), sid).lower() or sid - system_key = _as_text( - body.get("system") or body.get("system_key") or body.get("protocol"), - "", - ) - contract = _as_text( - body.get("contract") - or (body.get("schema") if isinstance(body.get("schema"), str) else "") - or "", - ) - if isinstance(body.get("contract"), dict): - contract = _as_text( - body["contract"].get("schema") or body["contract"].get("id"), - contract, - ) + system_key = _as_text(body.get("system"), "") + contract = _as_text(body.get("contract"), "") model_ref = _as_text(body.get("model"), "") tools: list[str] = [] tools_raw = body.get("tools") @@ -625,8 +613,6 @@ def _parse_subagents(raw: dict[str, Any], *, source: str) -> tuple[SubAgentDef, except (TypeError, ValueError): max_turns = 1 parallel_b = _boolish(body.get("parallel")) - if parallel_b is None: - parallel_b = _boolish(body.get("parallel_ok")) parallel_ok = True if parallel_b is None else parallel_b out.append( SubAgentDef( @@ -655,7 +641,7 @@ def _parse_contracts(raw: dict[str, Any]) -> dict[str, str]: if isinstance(body, str): sid = body.strip() elif isinstance(body, dict): - sid = _as_text(body.get("schema") or body.get("id") or "") + sid = _as_text(body.get("schema") or "") else: sid = "" if sid: @@ -756,9 +742,7 @@ def _profile_from_dict(raw: dict[str, Any], *, source: str) -> AgentProfile: if isinstance(intent_raw, str): intent_prompt = intent_raw.strip() elif isinstance(intent_raw, dict): - intent_prompt = _as_text( - intent_raw.get("protocol") or intent_raw.get("pack") or "" - ) + intent_prompt = _as_text(intent_raw.get("protocol") or "") routing_patches = _policy_from_routing(_as_map(raw.get("routing"))) runtime_patches, runtime_flags = _policy_from_runtime(_as_map(raw.get("runtime"))) diff --git a/apps/api/app/services/design/runtime/graph/build.py b/apps/api/app/services/design/runtime/graph/build.py index e571ab12..128d828e 100644 --- a/apps/api/app/services/design/runtime/graph/build.py +++ b/apps/api/app/services/design/runtime/graph/build.py @@ -855,15 +855,9 @@ def _review_loop_max_from_profile() -> int | None: def _normalize_design_intensity(raw: Any) -> str: - s = str(raw or "").strip().lower().replace("_", "-") - if s in ("light", "low", "轻度"): - return "light" - if s in ("high", "高"): - return "high" - if s in ("extreme", "max", "极高"): - return "extreme" - if s in ("medium", "mid", "中", "标准", ""): - return "medium" + s = str(raw or "").strip().lower() + if s in ("light", "medium", "high", "extreme"): + return s return "medium" @@ -1038,7 +1032,6 @@ async def run_agent_graph(inp: AgentGraphRunInput) -> AsyncIterator[dict[str, An spatial_summary=spatial_summary if isinstance(spatial_summary, dict) else None, ) rt.flags["mode"] = ui_mode - rt.flags["locale"] = out_locale rt.flags["output_locale"] = out_locale intensity = _normalize_design_intensity(intensity_in) rt.flags["design_intensity"] = intensity diff --git a/apps/api/app/services/design/runtime/graph/llm_io.py b/apps/api/app/services/design/runtime/graph/llm_io.py index 56a7053d..cd66a120 100644 --- a/apps/api/app/services/design/runtime/graph/llm_io.py +++ b/apps/api/app/services/design/runtime/graph/llm_io.py @@ -240,7 +240,7 @@ def _resolve_and_log_model( changed = bool(prev) and prev != family state.push_log( phase="model_route", - skill_key=str(skill.get("skill_key") or skill.get("name") or "") or None, + skill_key=str(skill.get("skill_key") or "") or None, from_model=prev or None, model=family, model_reason=reason, @@ -251,7 +251,7 @@ def _resolve_and_log_model( attempt=int(attempt) if attempt is not None else None, user_selected_model=(user_selected_model or "auto"), llm_user=_clip_llm_raw( - f"resolve_model skill={skill.get('skill_key') or skill.get('name')}\n" + f"resolve_model skill={skill.get('skill_key')}\n" f"run_mode={run_mode}\nattempt={attempt}\n" f"has_images={has_images}\n" f"user_selected={user_selected_model or 'auto'}\n" @@ -323,7 +323,7 @@ def _int_rule(rules: dict[str, str], key: str, default: int) -> int: return default -# Stable tip codes → FE i18n (`agent.uxTip*`). English fallback for logs / old clients. +# Stable tip codes → FE i18n (`agent.uxTip*`). English text for logs when i18n is absent. _UX_TIP_FALLBACK: dict[str, str] = { "decide_failed": "Decision failed. Please try again.", "paint_failed": "Could not produce valid canvas ops. Please describe a more specific edit.", diff --git a/apps/api/app/services/design/runtime/graph/nodes/apply.py b/apps/api/app/services/design/runtime/graph/nodes/apply.py index eeaad0fd..f7eca116 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/apply.py +++ b/apps/api/app/services/design/runtime/graph/nodes/apply.py @@ -66,7 +66,7 @@ def _emit_hydrate_job_progress(rt: AgentRuntime, progress: int, status: str) -> def _op_id_of(op: dict[str, Any]) -> str: - raw = op.get("op_id") or (op.get("args") or {}).get("op_id") or "" + raw = op.get("op_id") or "" oid = str(raw).strip() if oid: return oid diff --git a/apps/api/app/services/design/runtime/graph/nodes/bootstrap.py b/apps/api/app/services/design/runtime/graph/nodes/bootstrap.py index 816ff5f0..f2c5354b 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/bootstrap.py +++ b/apps/api/app/services/design/runtime/graph/nodes/bootstrap.py @@ -79,7 +79,7 @@ async def _node_bootstrap(state: GraphState) -> Command: proposal_task_id=(rt.flags.get("pending_proposal") or {}).get("task_id"), interaction_mode=rt.flags.get("mode"), skill_refs=rt.flags.get("skill_refs"), - locale=rt.flags.get("locale"), + locale=rt.flags.get("output_locale"), design_intensity=rt.flags.get("design_intensity"), ), "run_lifecycle": { diff --git a/apps/api/app/services/design/runtime/graph/nodes/counterfactual.py b/apps/api/app/services/design/runtime/graph/nodes/counterfactual.py index fabc81f3..4a7634ff 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/counterfactual.py +++ b/apps/api/app/services/design/runtime/graph/nodes/counterfactual.py @@ -401,11 +401,7 @@ async def run_design_counterfactual(rt: AgentRuntime) -> dict[str, Any] | None: snap = getattr(rt, "visual_snapshot", None) if not isinstance(snap, dict): snap = None - selected = str( - flags.get("counterfactual_select") - or flags.get("counterfactual_selected_id") - or "" - ).strip() + selected = str(flags.get("selected_id") or "").strip() result = run_design_counterfactual_pipeline( observe_facts=observe if isinstance(observe, dict) else None, visual_snapshot=snap, diff --git a/apps/api/app/services/design/runtime/graph/nodes/decide.py b/apps/api/app/services/design/runtime/graph/nodes/decide.py index f5929d64..c95637dd 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/decide.py +++ b/apps/api/app/services/design/runtime/graph/nodes/decide.py @@ -150,9 +150,10 @@ class IntelligenceTaskProfile: def _normalized_intensity(intensity: str | None) -> str: - value = str(intensity or "medium").strip().lower().replace("_", "-") - aliases = {"low": "light", "mid": "medium", "max": "extreme"} - return aliases.get(value, value) + value = str(intensity or "medium").strip().lower() + if value in ("light", "medium", "high", "extreme"): + return value + return "medium" def intelligence_task_profile(rt: AgentRuntime) -> IntelligenceTaskProfile: @@ -199,9 +200,9 @@ def intel_hops_for_intensity(intensity: str | None) -> tuple[list[str], bool]: when the second return is True. """ level = _normalized_intensity(intensity) - if level in ("light", "low"): + if level == "light": return [], False - if level in ("medium", "mid", ""): + if level == "medium": return ["research", "strategy"], False if level == "high": return [ @@ -394,8 +395,6 @@ def _extract_design_brief(turn: dict[str, Any] | None, rt: AgentRuntime) -> str: """Return prompt-ready brief string; empty when missing/invalid for gate.""" t = turn if isinstance(turn, dict) else {} raw = t.get("design_brief") - if raw is None: - raw = t.get("designBrief") if raw is None or raw == "": raw = getattr(rt, "design_brief", "") or "" parsed = parse_design_brief(raw) @@ -454,8 +453,6 @@ def _stash_design_brief(rt: AgentRuntime, turn: dict[str, Any], *, round_i: int) """Validate + stash brief. Returns paint-facing text, or '' when missing/incomplete.""" t = turn if isinstance(turn, dict) else {} raw = t.get("design_brief") - if raw is None: - raw = t.get("designBrief") if raw is None or raw == "": flagged = rt.flags.get("design_brief") if isinstance(rt.flags, dict) else None raw = flagged if flagged else (getattr(rt, "design_brief", "") or "") @@ -463,8 +460,8 @@ def _stash_design_brief(rt: AgentRuntime, turn: dict[str, Any], *, round_i: int) if not parsed: return "" - turn_analyze = t.get("reference_analyze") or t.get("referenceAnalyze") - turn_dna = t.get("reference_dna") or t.get("referenceDna") + turn_analyze = t.get("reference_analyze") + turn_dna = t.get("reference_dna") if turn_analyze and not getattr(rt, "reference_analyze", None): apply_reference_intelligence( rt, compile_reference_intelligence(turn_analyze, turn_dna) diff --git a/apps/api/app/services/design/runtime/graph/nodes/governance.py b/apps/api/app/services/design/runtime/graph/nodes/governance.py index 4f3fb16c..40f93bae 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/governance.py +++ b/apps/api/app/services/design/runtime/graph/nodes/governance.py @@ -92,9 +92,6 @@ def _palette_colors(brief: dict[str, Any] | None) -> list[str]: colors.extend(str(v) for v in val.values()) elif isinstance(val, str): colors.append(val) - allowed = src.get("allowed_colors") or src.get("brand_colors") - if isinstance(allowed, list): - colors.extend(str(x) for x in allowed) out: list[str] = [] for c in colors: for hit in _HEX.findall(str(c)): @@ -168,8 +165,8 @@ def check_accessibility_lane( ) -> dict[str, Any]: src = brief if isinstance(brief, dict) else {} a11y = src.get("accessibility") if isinstance(src.get("accessibility"), dict) else {} - fg_c = str(fg or a11y.get("fg") or a11y.get("foreground") or "").strip() - bg_c = str(bg or a11y.get("bg") or a11y.get("background") or "").strip() + fg_c = str(fg or a11y.get("fg") or "").strip() + bg_c = str(bg or a11y.get("bg") or "").strip() # Spec example path: explicit contrast 2.8:1 fails. explicit = a11y.get("contrast_ratio") if explicit is not None: @@ -275,7 +272,7 @@ def check_design_system_lane(*, brief: dict[str, Any] | None = None) -> dict[str tokens = src.get("tokens") if isinstance(src.get("tokens"), dict) else {} spacing = tokens.get("spacing") if isinstance(tokens.get("spacing"), dict) else {} # Explicit violation flag or non-token spacing values. - if tokens.get("spacing_violation") or src.get("spacing_token_violation"): + if tokens.get("spacing_violation"): return { "lane": "design_system", "status": "fail", @@ -283,8 +280,8 @@ def check_design_system_lane(*, brief: dict[str, Any] | None = None) -> dict[str "evidence": ["spacing_token_violation"], "fix": "align spacing to design-system tokens", } - raw_spacing = spacing.get("values") or spacing.get("used") - allowed = spacing.get("allowed") or spacing.get("scale") + raw_spacing = spacing.get("used") + allowed = spacing.get("allowed") if isinstance(raw_spacing, list) and isinstance(allowed, list) and allowed: bad = [x for x in raw_spacing if x not in allowed] if bad: @@ -340,21 +337,14 @@ def check_tool_permission_lane( "evidence": [], "fix": "", } - allow = allowed_ops or { - "create_node", - "update_node", - "delete_node", - "set_frame", - "group", - "ungroup", - "reorder", - "set_text", - "set_fill", - "set_stroke", - } + allow = allowed_ops + if allow is None: + from app.services.design.ops.tool_ops_contract import allowed_canvas_tool_keys + + allow = set(allowed_canvas_tool_keys()) bad: list[str] = [] for op in ops: - name = str(op.get("op") or op.get("type") or op.get("name") or "").strip() + name = str(op.get("name") or "").strip() if name and name not in allow: bad.append(name) if bad: diff --git a/apps/api/app/services/design/runtime/graph/nodes/intent.py b/apps/api/app/services/design/runtime/graph/nodes/intent.py index 803e1716..8712e541 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/intent.py +++ b/apps/api/app/services/design/runtime/graph/nodes/intent.py @@ -90,7 +90,7 @@ async def _node_intent_classify(state: GraphState) -> Command: if not isinstance(t, dict): continue role = "User" if str(t.get("role") or "") == "user" else "Assistant" - text = str(t.get("text") or t.get("content") or "").strip() + text = str(t.get("text") or "").strip() if text: dial_lines.append(f"{role}: {text[:400]}") t_intent = time.perf_counter() diff --git a/apps/api/app/services/design/runtime/graph/nodes/observe.py b/apps/api/app/services/design/runtime/graph/nodes/observe.py index 75ff2873..308f19a9 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/observe.py +++ b/apps/api/app/services/design/runtime/graph/nodes/observe.py @@ -51,8 +51,8 @@ def _num(v: Any, fallback: float = 0.0) -> float: def _node_box(node: dict[str, Any]) -> tuple[float, float, float, float] | None: - w = _num(node.get("w") if node.get("w") is not None else node.get("width")) - h = _num(node.get("h") if node.get("h") is not None else node.get("height")) + w = _num(node.get("w")) + h = _num(node.get("h")) if w <= 0 or h <= 0: return None return (_num(node.get("x")), _num(node.get("y")), w, h) @@ -83,12 +83,7 @@ def _gap_axis(a0: float, a1: float, b0: float, b1: float) -> float: def _is_text_node(node: dict[str, Any]) -> bool: - kind = str(node.get("type") or node.get("key") or "").strip().lower() - if kind == "text": - return True - if node.get("fontSize") is not None or node.get("text"): - return True - return False + return str(node.get("type") or "").strip().lower() == "text" def _parse_pct_range(raw: Any) -> tuple[float | None, float | None]: @@ -144,7 +139,7 @@ def _pick_focus_frame( return f counts: dict[str, int] = {} for n in nodes: - nid = str(n.get("frameId") or n.get("frame_id") or "").strip() + nid = str(n.get("frameId") or "").strip() if nid: counts[nid] = counts.get(nid, 0) + 1 if counts: @@ -158,8 +153,8 @@ def _pick_focus_frame( def _frame_box(frame: dict[str, Any] | None) -> tuple[float, float, float, float] | None: if not frame: return None - w = _num(frame.get("w") if frame.get("w") is not None else frame.get("width")) - h = _num(frame.get("h") if frame.get("h") is not None else frame.get("height")) + w = _num(frame.get("w")) + h = _num(frame.get("h")) if w <= 0 or h <= 0: return None return (_num(frame.get("x")), _num(frame.get("y")), w, h) @@ -225,7 +220,7 @@ def build_scene_visual_snapshot( if area > title_area: title_area = area continue - fill = str(n.get("fill") or n.get("fillColor") or "").strip() + fill = str(n.get("fill") or "").strip() if fill: color_area += area if area > hero_area: @@ -584,7 +579,7 @@ def _normalize_resume_snap(raw: Any) -> dict[str, Any] | None: if raw is None: return None if isinstance(raw, dict): - if raw.get("timeout") or raw.get("kind") == "timeout": + if raw.get("timeout"): return None if raw.get("cancelled") or raw.get("paused"): return None @@ -665,7 +660,7 @@ def _op_receipt_issues( for op in emitted_ops or []: if not isinstance(op, dict): continue - oid = str(op.get("op_id") or (op.get("args") or {}).get("op_id") or "").strip() + oid = str(op.get("op_id") or "").strip() if oid: expected[oid] = str(op.get("name") or "op").strip() or "op" if not expected: diff --git a/apps/api/app/services/design/runtime/graph/nodes/research.py b/apps/api/app/services/design/runtime/graph/nodes/research.py index b6a03636..8a2faea8 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/research.py +++ b/apps/api/app/services/design/runtime/graph/nodes/research.py @@ -242,7 +242,6 @@ def run_design_research_pipeline( "avoid": avoid[:10], "adopt": adopt[:10], "anti_category_strategy": anti[:16], - "hypotheses": why[:8], "why_effective": why[:8], "sources": sources[:24], "summary": ( @@ -274,7 +273,7 @@ def should_run_design_research(rt: AgentRuntime) -> bool: def _eval_patterns_from_rt(rt: AgentRuntime) -> list[dict[str, Any]]: flags = rt.flags if isinstance(rt.flags, dict) else {} - raw = flags.get("eval_failure_patterns") or flags.get("skill_failures") + raw = flags.get("eval_patterns") if isinstance(raw, list): return [x for x in raw if isinstance(x, dict)] return [] @@ -326,7 +325,7 @@ def format_research_for_decide(report: dict[str, Any] | None) -> str: if anti: lines.append("ANTI-CATEGORY STRATEGY:") lines.extend(f"- {x}" for x in anti) - why = list(src.get("why_effective") or src.get("hypotheses") or [])[:6] + why = list(src.get("why_effective") or [])[:6] if why: lines.append("why_effective:") lines.extend(f"- {x}" for x in why) diff --git a/apps/api/app/services/design/runtime/graph/nodes/review.py b/apps/api/app/services/design/runtime/graph/nodes/review.py index 843f216a..66dcd3c3 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/review.py +++ b/apps/api/app/services/design/runtime/graph/nodes/review.py @@ -186,7 +186,7 @@ def _issues_as_dicts(raw: Any) -> list[dict[str, Any]]: _REPAIR_REDUCE_ACTIONS = frozenset({"reduce_size"}) _REPAIR_INCREASE_ACTIONS = frozenset({"increase_size"}) _REPAIR_FORBIDDEN_PATCH_KEYS = frozenset( - {"nodeid", "id", "frameid", "type", "name", "op_id", "opid", "tool"} + {"nodeid", "id", "frameid", "type", "name", "op_id", "tool"} ) _REPAIR_PATCH_KEYS = frozenset( { @@ -199,7 +199,7 @@ def _issues_as_dicts(raw: Any) -> list[dict[str, Any]]: "fill", "opacity", "stroke", - "strokewidth", + "borderwidth", "x", "y", "width", @@ -228,6 +228,20 @@ def _repair_norm_action(raw: Any) -> str: return str(raw or "").strip().lower().replace(" ", "_").replace("-", "_") +def _scene_delta_to_update_args(snap: dict[str, Any], cur: dict[str, Any]) -> dict[str, Any]: + """Scene snapshot uses w/h; update_node args use width/height.""" + raw: dict[str, Any] = {} + for key, val in snap.items(): + if key == "id" or val == cur.get(key): + continue + raw[key] = val + if "w" in raw: + raw["width"] = raw.pop("w") + if "h" in raw: + raw["height"] = raw.pop("h") + return _sanitize_repair_patch(raw) + + def _sanitize_repair_patch(raw: Any) -> dict[str, Any]: if not isinstance(raw, dict): return {} @@ -252,8 +266,8 @@ def _scale_existing_node(node: dict[str, Any], factor: float) -> dict[str, Any]: if fs > 0: return {"fontSize": max(8, int(round(fs * factor)))} try: - w = float(node.get("w") if node.get("w") is not None else node.get("width") or 0) - h = float(node.get("h") if node.get("h") is not None else node.get("height") or 0) + w = float(node.get("w") or 0) + h = float(node.get("h") or 0) except (TypeError, ValueError): return {} if w <= 8 or h <= 8: @@ -349,8 +363,8 @@ def mark_update(nid: str, patch: dict[str, Any]) -> None: def _is_image_node(node: dict[str, Any]) -> bool: - kind = str(node.get("type") or node.get("key") or "").strip().lower() - if kind in ("image", "img"): + kind = str(node.get("type") or "").strip().lower() + if kind == "image": return True return bool(str(node.get("src") or "").strip()) and kind not in ("text",) @@ -1161,7 +1175,7 @@ def _accept(text: str) -> bool: if not _accept(text): continue sev = str(item.get("severity") or "").strip().lower() - lane = str(item.get("lane") or item.get("area") or "").strip() + lane = str(item.get("lane") or "").strip() if lane == "aesthetic": lane = "anti_slop" if sev == "blocker": @@ -1180,7 +1194,7 @@ def _accept(text: str) -> bool: { "issue": text[:200], "evidence": evidence, - "fix": str(item.get("fix_hint") or item.get("fix") or "").strip()[:200], + "fix": str(item.get("fix_hint") or "").strip()[:200], "lane": lane, }, ) @@ -1289,7 +1303,7 @@ def attach_judge(rt: AgentRuntime, verdict: dict[str, Any]) -> dict[str, Any]: anti_slop_hits=verdict.get("anti_slop_hits") if isinstance(verdict.get("anti_slop_hits"), list) else [], - llm_overall=verdict.get("overall", verdict.get("total")), + llm_overall=verdict.get("overall"), visual_diff=visual_diff, ) rt.judge_verdict = judge @@ -1332,11 +1346,8 @@ def _slim_restore_node(node: dict[str, Any]) -> dict[str, Any]: "y", "w", "h", - "width", - "height", "fontSize", "fill", - "fillColor", "text", "opacity", "rotation", @@ -1348,7 +1359,7 @@ def _slim_restore_node(node: dict[str, Any]) -> dict[str, Any]: "lineHeight", "letterSpacing", "stroke", - "strokeWidth", + "borderWidth", "color", ): if node.get(key) is not None: @@ -1371,9 +1382,7 @@ def compile_restore_ops( cur = living.get(nid) if not cur: continue - patch = _sanitize_repair_patch( - {k: v for k, v in snap.items() if k != "id" and v != cur.get(k)} - ) + patch = _scene_delta_to_update_args(snap, cur) if patch: ops.append({"name": "update_node", "args": {"nodeId": nid, **patch}}) if extra: @@ -1566,7 +1575,7 @@ def _scene_digest(rt: AgentRuntime) -> str: lines = [body[:2200], "RECENT_PAINT_OPS:"] for op in ops: if isinstance(op, dict): - lines.append(f"- {str(op.get('name') or op.get('tool') or '')[:40]}") + lines.append(f"- {str(op.get('name') or '')[:40]}") return "\n".join(lines)[:2800] @@ -2304,13 +2313,6 @@ async def _node_review_agent(state: GraphState) -> Command: else None, } judge = rt.judge_verdict if isinstance(rt.judge_verdict, dict) else {} - if isinstance(rt.flags, dict): - if strengths: - rt.flags["review_strengths"] = strengths - if weaknesses: - rt.flags["review_weaknesses"] = weaknesses - if market_gap: - rt.flags["market_gap"] = market_gap if isinstance(rt.judge_verdict, dict): if strengths: rt.judge_verdict["strengths"] = strengths diff --git a/apps/api/app/services/design/runtime/graph/nodes/settle.py b/apps/api/app/services/design/runtime/graph/nodes/settle.py index f7659ab4..c5a66b25 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/settle.py +++ b/apps/api/app/services/design/runtime/graph/nodes/settle.py @@ -391,12 +391,12 @@ async def _node_settle(state: GraphState) -> Command: ] strengths = [ str(x).strip() - for x in list(judge.get("strengths") or flags.get("review_strengths") or [])[:4] + for x in list(judge.get("strengths") or [])[:4] if str(x).strip() ] weaknesses = [ str(x).strip() - for x in list(judge.get("weaknesses") or flags.get("review_weaknesses") or [])[:4] + for x in list(judge.get("weaknesses") or [])[:4] if str(x).strip() ] next_steps: list[str] = [] @@ -409,7 +409,7 @@ async def _node_settle(state: GraphState) -> Command: next_steps.append(fix) elif issue: next_steps.append(issue) - market_gap = str(judge.get("market_gap") or flags.get("market_gap") or "").strip() + market_gap = str(judge.get("market_gap") or "").strip() summary_payload: dict[str, Any] = { "type": "design_summary", "visibility": "user", diff --git a/apps/api/app/services/design/runtime/graph/nodes/tournament.py b/apps/api/app/services/design/runtime/graph/nodes/tournament.py index 7f778ff0..b7e3a07c 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/tournament.py +++ b/apps/api/app/services/design/runtime/graph/nodes/tournament.py @@ -386,11 +386,7 @@ async def run_design_tournament(rt: AgentRuntime) -> dict[str, Any] | None: flags = rt.flags if isinstance(rt.flags, dict) else {} research = flags.get("design_research") flags = rt.flags if isinstance(rt.flags, dict) else {} - user_pick = str( - flags.get("tournament_user_pick") - or flags.get("user_candidate_pick") - or "" - ).strip() + user_pick = str(flags.get("user_pick") or "").strip() result = run_design_tournament_pipeline( candidates_bundle=bundle if isinstance(bundle, dict) else None, research=research if isinstance(research, dict) else None, diff --git a/apps/api/app/services/design/runtime/graph/paint_kit.py b/apps/api/app/services/design/runtime/graph/paint_kit.py index 652ad9be..26a7180d 100644 --- a/apps/api/app/services/design/runtime/graph/paint_kit.py +++ b/apps/api/app/services/design/runtime/graph/paint_kit.py @@ -169,8 +169,8 @@ def _structure_verify_issues( zero_box = 0 for n in clean_nodes[:80]: try: - w = float(n.get("w") or n.get("width") or 0) - h = float(n.get("h") or n.get("height") or 0) + w = float(n.get("w") or 0) + h = float(n.get("h") or 0) except (TypeError, ValueError): w, h = 0.0, 0.0 if w <= 0 or h <= 0: @@ -496,7 +496,7 @@ def _ops_for_log(ops: list[dict[str, Any]] | None, *, limit: int = 30) -> list[d for op in list(ops or [])[:limit]: if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op") or op.get("tool") or "").strip() + name = str(op.get("name") or "").strip() args = op.get("args") if isinstance(op.get("args"), dict) else {} slim: dict[str, Any] = {} for k, v in list(args.items())[:12]: diff --git a/apps/api/app/services/design/runtime/graph/scene_log.py b/apps/api/app/services/design/runtime/graph/scene_log.py index 46092623..93b2fe5b 100644 --- a/apps/api/app/services/design/runtime/graph/scene_log.py +++ b/apps/api/app/services/design/runtime/graph/scene_log.py @@ -223,14 +223,8 @@ def _scene_digest( if nodes: lines.append("SCENE_NODES:") for n in nodes[:limit]: - fill = ( - n.get("fill") - or n.get("fillColor") - or n.get("backgroundColor") - or n.get("color") - or "" - ) - stroke = n.get("stroke") or n.get("strokeColor") or "" + fill = n.get("fill") or "" + stroke = n.get("stroke") or "" fill_s = str(fill).strip()[:48] stroke_s = str(stroke).strip()[:32] color_bit = "" @@ -239,7 +233,7 @@ def _scene_digest( if stroke_s: color_bit += f" stroke={stroke_s}" lines.append( - f"- id={n.get('id')} type={n.get('type') or n.get('key')} " + f"- id={n.get('id')} type={n.get('type') or ''} " f"frameId={n.get('frameId') or ''} " f"text={(str(n.get('text') or '')[:40])}" f"{color_bit}" diff --git a/apps/api/app/services/design/runtime/graph/turns.py b/apps/api/app/services/design/runtime/graph/turns.py index 8dadb9d6..3a97b7f7 100644 --- a/apps/api/app/services/design/runtime/graph/turns.py +++ b/apps/api/app/services/design/runtime/graph/turns.py @@ -461,7 +461,7 @@ def _thought_prompt_variables(rt: Any) -> dict[str, str]: if not isinstance(t, dict): continue role = "User" if str(t.get("role") or "") == "user" else "Assistant" - text = _as_text(t.get("text") or t.get("content")).strip() + text = _as_text(t.get("text")).strip() if not text: continue dial_lines.append(f"{role}: {text[:dialogue_limit]}") diff --git a/apps/api/app/services/design/runtime/host/placement.py b/apps/api/app/services/design/runtime/host/placement.py index 4849a8f4..64888420 100644 --- a/apps/api/app/services/design/runtime/host/placement.py +++ b/apps/api/app/services/design/runtime/host/placement.py @@ -5,13 +5,12 @@ from app.services.design.ops.tool_ops_contract import format_op_error -def _box_num(d: dict[str, Any], *keys: str, default: float = 0.0) -> float: - for k in keys: - if k in d and d[k] is not None: - try: - return float(d[k]) - except (TypeError, ValueError): - pass +def _box_num(d: dict[str, Any], key: str, *, default: float = 0.0) -> float: + if key in d and d[key] is not None: + try: + return float(d[key]) + except (TypeError, ValueError): + pass return default @@ -50,8 +49,8 @@ def _world_occupied_in_viewport( for n in spatial.get("focused") or []: if not isinstance(n, dict): continue - w = _box_num(n, "w", "width") - h = _box_num(n, "h", "height") + w = _box_num(n, "w") + h = _box_num(n, "h") if w <= 1 or h <= 1: continue box = { @@ -65,19 +64,19 @@ def _world_occupied_in_viewport( for f in spatial.get("peripheral") or []: if not isinstance(f, dict): continue - w = _box_num(f, "w", "width") - h = _box_num(f, "h", "height") + w = _box_num(f, "w") + h = _box_num(f, "h") if w <= 1 or h <= 1: continue box = {"x": _box_num(f, "x"), "y": _box_num(f, "y"), "w": w, "h": h} if _boxes_overlap(box, vp, gap=0): out.append(box) - if in_frame and _box_num(focus_frame, "w", "width") > 8: + if in_frame and _box_num(focus_frame, "w") > 8: fb = { "x": fox, "y": foy, - "w": _box_num(focus_frame, "w", "width"), - "h": _box_num(focus_frame, "h", "height"), + "w": _box_num(focus_frame, "w"), + "h": _box_num(focus_frame, "h"), } if _boxes_overlap(fb, vp, gap=0): # Treat the artboard shell as occupied so free-canvas creates sit beside it. @@ -151,8 +150,8 @@ def _derive_suggested_place_world( spatial = spatial if isinstance(spatial, dict) else {} vp_raw = spatial.get("viewport") if isinstance(vp_raw, dict): - vw = _box_num(vp_raw, "w", "width") - vh = _box_num(vp_raw, "h", "height") + vw = _box_num(vp_raw, "w") + vh = _box_num(vp_raw, "h") if vw > 8 and vh > 8: vp = { "x": _box_num(vp_raw, "x"), @@ -169,20 +168,20 @@ def _derive_suggested_place_world( if isinstance(sp, dict) and isinstance(focus_frame, dict): fox = _box_num(focus_frame, "x") foy = _box_num(focus_frame, "y") - fw = _box_num(focus_frame, "w", "width") - fh = _box_num(focus_frame, "h", "height") + fw = _box_num(focus_frame, "w") + fh = _box_num(focus_frame, "h") if fw > 8 and fh > 8: return { "x": round(fox + _box_num(sp, "x")), "y": round(foy + _box_num(sp, "y")), - "w": round(_box_num(sp, "w", "width", default=320)), - "h": round(_box_num(sp, "h", "height", default=200)), + "w": round(_box_num(sp, "w", default=320)), + "h": round(_box_num(sp, "h", default=200)), } if isinstance(focus_frame, dict): fox = _box_num(focus_frame, "x") foy = _box_num(focus_frame, "y") - fw = _box_num(focus_frame, "w", "width") - fh = _box_num(focus_frame, "h", "height") + fw = _box_num(focus_frame, "w") + fh = _box_num(focus_frame, "h") if fw > 8 and fh > 8: cw = min(320.0, max(80.0, fw * 0.25)) ch = min(200.0, max(80.0, fh * 0.25)) @@ -227,8 +226,8 @@ def _point_outside_world_box( ) -> bool: bx = _box_num(box, "x") by = _box_num(box, "y") - bw = _box_num(box, "w", "width") - bh = _box_num(box, "h", "height") + bw = _box_num(box, "w") + bh = _box_num(box, "h") if bw <= 0 or bh <= 0: return False return ( @@ -243,7 +242,7 @@ def _create_op_placement_fields(op: dict[str, Any]) -> tuple[Any, Any, str]: """Return (x, y, frameId) from normalized {args} or flat model shape.""" args = op.get("args") if isinstance(op.get("args"), dict) else None src = args if args is not None else op - return src.get("x"), src.get("y"), str(src.get("frameId") or src.get("frame_id") or "").strip() + return src.get("x"), src.get("y"), str(src.get("frameId") or "").strip() def _batch_opens_new_frame(ops: list[dict[str, Any]]) -> bool: @@ -278,17 +277,17 @@ def _placement_errors_for_free_creates(rt: Any, ops: list[dict[str, Any]]) -> li focus_frame = _focus_frame_from_rt(rt) vp = spatial.get("viewport") if isinstance(spatial, dict) else None # Prefer artboard bounds when present — FE camera viewport is noisier (Yjs/pan lag). - if isinstance(focus_frame, dict) and _box_num(focus_frame, "w", "width") > 0: + if isinstance(focus_frame, dict) and _box_num(focus_frame, "w") > 0: view_box = focus_frame pad = max( 48.0, - 0.2 * min(_box_num(view_box, "w", "width"), _box_num(view_box, "h", "height")), + 0.2 * min(_box_num(view_box, "w"), _box_num(view_box, "h")), ) - elif isinstance(vp, dict) and _box_num(vp, "w", "width") > 0: + elif isinstance(vp, dict) and _box_num(vp, "w") > 0: view_box = vp pad = max( 96.0, - 0.4 * min(_box_num(view_box, "w", "width"), _box_num(view_box, "h", "height")), + 0.4 * min(_box_num(view_box, "w"), _box_num(view_box, "h")), ) else: return [] diff --git a/apps/api/app/services/design/runtime/host/prompts.py b/apps/api/app/services/design/runtime/host/prompts.py index a80c07c0..2db656f5 100644 --- a/apps/api/app/services/design/runtime/host/prompts.py +++ b/apps/api/app/services/design/runtime/host/prompts.py @@ -68,10 +68,7 @@ def locale_for_runtime(rt: Any | None = None, *, explicit: str | None = None) -> if rt is not None: flags = getattr(rt, "flags", None) if isinstance(flags, dict) and not client: - client = ( - str(flags.get("locale") or flags.get("output_locale") or "").strip() - or None - ) + client = str(flags.get("output_locale") or "").strip() or None prompt = str(getattr(rt, "prompt", "") or "") profile_locale = "zh-CN" try: diff --git a/apps/api/app/services/design/runtime/host/resources.py b/apps/api/app/services/design/runtime/host/resources.py index dc9615dc..4b38a20c 100644 --- a/apps/api/app/services/design/runtime/host/resources.py +++ b/apps/api/app/services/design/runtime/host/resources.py @@ -295,7 +295,7 @@ async def _load_deferred_subagents( results = list(harvested) for job in jobs: - aid = str(job.get("id") or job.get("agent_id") or "").strip() + aid = str(job.get("id") or "").strip() # Poll-only: job_id without spawn id — already harvested above. if not aid: continue @@ -305,7 +305,6 @@ async def _load_deferred_subagents( images = list(getattr(rt, "images", None) or [])[:4] or None payload = { "id": aid, - "agent_id": aid, "task": task_text, "images": images, "timeout": job.get("timeout") or 90.0, diff --git a/apps/api/app/services/design/runtime/models_route.py b/apps/api/app/services/design/runtime/models_route.py index f2081d8c..47c7fa9c 100644 --- a/apps/api/app/services/design/runtime/models_route.py +++ b/apps/api/app/services/design/runtime/models_route.py @@ -204,17 +204,7 @@ def normalize_session_action(raw: str | None) -> str: s = str(raw or "").strip().lower() if s in SESSION_ACTIONS: return s - aliases = { - "clear": "clear_context", - "clearcontext": "clear_context", - "new_chat": "clear_context", - "newchat": "clear_context", - "reset": "clear_context", - "reset_chat": "clear_context", - "cancel": "stop", - "abort": "stop", - } - return aliases.get(s, "") + return "" def normalize_proposal_action( @@ -453,7 +443,7 @@ def model_supports_vision(model_ref: str | None) -> bool: item = get_model(low) if item: - types = item.get("referenceTypes") or item.get("reference_types") or [] + types = item.get("referenceTypes") or [] if isinstance(types, list) and types: return "vision" in types except Exception: @@ -595,15 +585,11 @@ def apply_user_route_overrides( ) out["precheck.model_threshold"] = serialized - vision = str( - overrides.get("vision") or overrides.get("vision_model") or "" - ).strip() + vision = str(overrides.get("vision") or "").strip() if vision and vision.lower() not in ("auto", "platform", "default"): out["precheck.vision_model"] = vision - image = str( - overrides.get("image") or overrides.get("image_default_model") or "" - ).strip() + image = str(overrides.get("image") or "").strip() if image and image.lower() not in ("auto", "platform", "default"): out["assets.image_default_model"] = image @@ -782,11 +768,11 @@ def scene_target_catalog(scene_nodes: list[dict[str, Any]] | None) -> str: if not isinstance(node, dict): continue node_id = str(node.get("id") or "").strip()[:64] - node_type = str(node.get("type") or node.get("kind") or "node").strip()[:32] + node_type = str(node.get("type") or "node").strip()[:32] if not node_id: continue name = "" - for key in ("name", "title", "text", "content", "label"): + for key in ("name", "text"): value = str(node.get(key) or "").strip().replace("\n", " ") if value: name = value[:80] @@ -973,15 +959,11 @@ async def classify_user_intent( ] elif isinstance(structured, dict): raw_intent = structured.get("intent") - raw_lane = structured.get("paint_lane") or structured.get("paintLane") + raw_lane = structured.get("paint_lane") rationale = structured.get("rationale") reply = structured.get("reply") - raw_action = structured.get("proposal_action") or structured.get( - "proposalAction" - ) - raw_session = structured.get("session_action") or structured.get( - "sessionAction" - ) + raw_action = structured.get("proposal_action") + raw_session = structured.get("session_action") raw_clarification_needed = structured.get("needs_clarification") raw_clarification = structured.get("clarification") raw_clarification_options = structured.get("clarification_options") diff --git a/apps/api/app/services/design/runtime/pipeline_progress.py b/apps/api/app/services/design/runtime/pipeline_progress.py index a70db018..d82e552d 100644 --- a/apps/api/app/services/design/runtime/pipeline_progress.py +++ b/apps/api/app/services/design/runtime/pipeline_progress.py @@ -72,7 +72,7 @@ def decorate(self, payload: dict[str, Any]) -> dict[str, Any]: "phase": stage, "elapsed_ms": max(0, int((time.time() - self.t0) * 1000)), "can_cancel": not terminal, - "can_resume": bool(payload.get("resumable")), + "resumable": bool(payload.get("resumable")), }, } diff --git a/apps/api/app/services/design/runtime/subagent.py b/apps/api/app/services/design/runtime/subagent.py index f59db41b..5e50b788 100644 --- a/apps/api/app/services/design/runtime/subagent.py +++ b/apps/api/app/services/design/runtime/subagent.py @@ -117,23 +117,17 @@ def parse_need_subagents(raw: Any) -> list[dict[str, Any]]: aid = item.strip() if not aid: continue - job = {"id": aid, "agent_id": aid, "task": "", "background": False} + job = {"id": aid, "task": "", "background": False} elif isinstance(item, dict): - aid = str( - item.get("id") or item.get("agent_id") or item.get("subagent") or "" - ).strip() + aid = str(item.get("id") or "").strip() job_id = str(item.get("job_id") or "").strip() or None # Poll-only: {"job_id": "..."} without a new spawn id. if not aid and not job_id: continue - bg = item.get("background") - if bg is None: - bg = item.get("async") job = { "id": aid, - "agent_id": aid, - "task": str(item.get("task") or item.get("prompt") or "").strip(), - "background": bool(bg), + "task": str(item.get("task") or "").strip(), + "background": bool(item.get("background")), "images": item.get("images"), "timeout": item.get("timeout"), "job_id": job_id, @@ -409,12 +403,7 @@ async def run_subagent( if not isinstance(payload, dict): payload = {} duration_ms = max(0, int((time.perf_counter() - t0) * 1000)) - summary = str( - payload.get("summary") - or payload.get("text") - or payload.get("fix_brief") - or "" - ).strip()[:400] + summary = str(payload.get("summary") or "").strip()[:400] return SubAgentResult( agent_id=spec.id, ok=True, @@ -437,7 +426,7 @@ async def run_subagents_parallel( return [] async def _one(job: dict[str, Any]) -> SubAgentResult: - aid = str(job.get("agent_id") or job.get("id") or "").strip() + aid = str(job.get("id") or "").strip() spec = None if profile is not None: spec = profile.get_subagent(aid) diff --git a/apps/api/app/services/llm/__init__.py b/apps/api/app/services/llm/__init__.py index 2e37b298..b7a61d0d 100644 --- a/apps/api/app/services/llm/__init__.py +++ b/apps/api/app/services/llm/__init__.py @@ -199,12 +199,13 @@ def list_llm_models( "description": m.get("description"), "provider": provider, "kind": "text", - "api_model": m.get("api_model") or m.get("apiModel") or m["id"], + "apiModel": m.get("apiModel") or m["id"], "iconKey": m.get("iconKey"), "iconUrl": m.get("iconUrl"), "price": m.get("price"), - "max_attachments": int(m.get("max_attachments") or m.get("maxAttachments") or 8), + "maxAttachments": int(m.get("maxAttachments") or 8), "thinking": bool(m.get("thinking")), + "referenceTypes": m.get("referenceTypes") or ["text"], } ) @@ -216,8 +217,9 @@ def list_llm_models( "label": "Doubao Seed (custom ep)", "provider": "doubao", "kind": "text", - "api_model": seed, - "max_attachments": 8, + "apiModel": seed, + "maxAttachments": 8, + "referenceTypes": ["text"], } ) @@ -229,8 +231,9 @@ def list_llm_models( "label": "Doubao Pro (custom ep)", "provider": "doubao", "kind": "text", - "api_model": pro, - "max_attachments": 8, + "apiModel": pro, + "maxAttachments": 8, + "referenceTypes": ["text"], } ) @@ -259,9 +262,6 @@ def list_image_models( if not _provider_unlocked(provider, unlocked, strict=strict): continue mid = m["id"] - api_model = m.get("api_model") or m.get("apiModel") or mid - limits = m.get("imageLimits") or m.get("image_limits") - price_meta = m.get("priceMeta") or m.get("price_meta") models.append( { "id": mid, @@ -269,17 +269,14 @@ def list_image_models( "description": m.get("description"), "provider": provider, "kind": "image", - "api_model": api_model, + "apiModel": m.get("apiModel") or mid, "iconKey": m.get("iconKey"), "iconUrl": m.get("iconUrl"), "price": m.get("price"), - "priceMeta": price_meta, - "price_meta": price_meta, - "max_attachments": int( - m.get("max_attachments") or m.get("maxAttachments") or 14 - ), - "imageLimits": limits, - "image_limits": limits, + "priceMeta": m.get("priceMeta"), + "maxAttachments": int(m.get("maxAttachments") or 14), + "imageLimits": m.get("imageLimits"), + "referenceTypes": m.get("referenceTypes") or ["image"], } ) return models @@ -305,7 +302,6 @@ def list_video_models( if not _provider_unlocked(provider, unlocked, strict=strict): continue mid = m["id"] - api_model = m.get("api_model") or m.get("apiModel") or mid models.append( { "id": mid, @@ -313,13 +309,11 @@ def list_video_models( "description": m.get("description"), "provider": provider, "kind": "video", - "api_model": api_model, + "apiModel": m.get("apiModel") or mid, "iconKey": m.get("iconKey"), "iconUrl": m.get("iconUrl"), "price": m.get("price"), - "max_attachments": int( - m.get("max_attachments") or m.get("maxAttachments") or 4 - ), + "maxAttachments": int(m.get("maxAttachments") or 4), } ) return models @@ -345,7 +339,6 @@ def list_audio_models( if not _provider_unlocked(provider, unlocked, strict=strict): continue mid = m["id"] - api_model = m.get("api_model") or m.get("apiModel") or mid models.append( { "id": mid, @@ -353,13 +346,11 @@ def list_audio_models( "description": m.get("description"), "provider": provider, "kind": "audio", - "api_model": api_model, + "apiModel": m.get("apiModel") or mid, "iconKey": m.get("iconKey"), "iconUrl": m.get("iconUrl"), "price": m.get("price"), - "max_attachments": int( - m.get("max_attachments") or m.get("maxAttachments") or 0 - ), + "maxAttachments": int(m.get("maxAttachments") or 0), } ) return models @@ -395,10 +386,10 @@ def resolve_provider(model_string: str | None) -> tuple[str, str]: meta = catalog.get(model) if meta: provider = str(meta.get("provider") or settings.llm_provider or "doubao") - return provider, str(meta.get("api_model") or meta["id"]) + return provider, str(meta.get("apiModel") or meta["id"]) for m in list_all_models(): - if str(m.get("api_model") or "") == model: + if str(m.get("apiModel") or "") == model: return str(m.get("provider") or "doubao"), model # provider/model form, e.g. doubao/ep-xxxx or openrouter/anthropic/claude-sonnet-4 diff --git a/apps/api/app/services/llm/audio.py b/apps/api/app/services/llm/audio.py index 22149347..cd95d057 100644 --- a/apps/api/app/services/llm/audio.py +++ b/apps/api/app/services/llm/audio.py @@ -54,7 +54,7 @@ def resolve_audio_model(model: str | None = None) -> str: def _api_model_id(catalog_id: str) -> str: for m in list_audio_models(): if m["id"] == catalog_id: - return str(m.get("api_model") or m["id"]) + return str(m.get("apiModel") or m["id"]) return catalog_id or _DEFAULT_AUDIO_MODEL diff --git a/apps/api/app/services/llm/byok_presets.py b/apps/api/app/services/llm/byok_presets.py index 53e2c2b7..6a3984ed 100644 --- a/apps/api/app/services/llm/byok_presets.py +++ b/apps/api/app/services/llm/byok_presets.py @@ -64,7 +64,7 @@ def _sanitize_platform(raw: Any) -> dict[str, Any] | None: return None pid = str(raw.get("id") or "").strip().lower() name = str(raw.get("name") or "").strip() - base_url = str(raw.get("baseUrl") or raw.get("base_url") or "").strip().rstrip("/") + base_url = str(raw.get("baseUrl") or "").strip().rstrip("/") if not pid or not name or not base_url: return None kinds_raw = raw.get("kinds") or ["text"] @@ -83,7 +83,7 @@ def _sanitize_platform(raw: Any) -> dict[str, Any] | None: "kinds": kinds, "rowId": platform_byok_row_id(pid), } - icon = str(raw.get("iconKey") or raw.get("icon_key") or "").strip() + icon = str(raw.get("iconKey") or "").strip() if icon: out["iconKey"] = icon hint = str(raw.get("hint") or "").strip() diff --git a/apps/api/app/services/llm/catalog_store.py b/apps/api/app/services/llm/catalog_store.py index cca4c2f6..1c4fc6ae 100644 --- a/apps/api/app/services/llm/catalog_store.py +++ b/apps/api/app/services/llm/catalog_store.py @@ -65,8 +65,6 @@ def _normalize_reference_types(raw: Any, *, kind: str = 'text') -> list[str]: if isinstance(raw, (list, tuple, set)): for x in raw: t = str(x or '').strip().lower() - if t in ('multimodal', 'multi'): - t = 'vision' if t in REFERENCE_TYPES and t not in items: items.append(t) if items: @@ -156,7 +154,7 @@ def resolve_image_limits(raw: Any = None, *, preset: str | None = None) -> dict[ out['resolutions'] = [ str(x).strip().upper() for x in res if str(x).strip() ] - dr = raw.get('default_resolution') or raw.get('defaultResolution') + dr = raw.get('default_resolution') if dr: out['default_resolution'] = str(dr).strip().upper() if 'supports_output_format' in raw: @@ -166,12 +164,12 @@ def resolve_image_limits(raw: Any = None, *, preset: str | None = None) -> dict[ transport = raw.get('transport') if transport: out['transport'] = str(transport).strip().lower() - aspects = raw.get('aspect_ratios') or raw.get('aspectRatios') + aspects = raw.get('aspect_ratios') if isinstance(aspects, list): out['aspect_ratios'] = [ str(x).strip() for x in aspects if str(x).strip() ] - tables = raw.get('size_tables') or raw.get('sizeTables') + tables = raw.get('size_tables') if isinstance(tables, dict) and tables: cleaned: dict[str, dict[str, str]] = {} for rk, mapping in tables.items(): @@ -612,23 +610,17 @@ def _pub(r: Any) -> dict[str, Any]: 'description': _row_get(r, 'description') or None, 'provider': _row_get(r, 'provider') or 'doubao', 'kind': kind, - 'reference_types': ref_types, 'referenceTypes': ref_types, - 'api_model': _row_get(r, 'api_model'), 'apiModel': _row_get(r, 'api_model'), 'iconKey': _row_get(r, 'icon_key') or None, 'iconUrl': _row_get(r, 'icon_url') or None, 'price': (str(price_raw).strip() if price_raw else None), - 'price_meta': price_meta, 'priceMeta': price_meta, - 'pricing_id': (_row_get(r, 'pricing_id') or None), 'pricingId': (_row_get(r, 'pricing_id') or None), - 'max_attachments': int(_row_get(r, 'max_attachments') or 8), 'maxAttachments': int(_row_get(r, 'max_attachments') or 8), 'thinking': bool(int(_row_get(r, 'thinking') or 0)), 'enabled': bool(int(_row_get(r, 'enabled') or 0)), 'sortOrder': int(_row_get(r, 'sort_order') or 100), - 'image_limits': image_limits, 'imageLimits': image_limits, 'createdAt': int(float(created_at) * 1000) if created_at else None, 'updatedAt': int(float(updated_at) * 1000) if updated_at else None, @@ -727,10 +719,8 @@ def upsert_model(payload: dict[str, Any]) -> dict[str, Any]: else: image_limits = None limits_json = _serialize_image_limits(image_limits) - meta_in_payload = 'priceMeta' in payload or 'price_meta' in payload + meta_in_payload = 'priceMeta' in payload meta_payload = payload.get('priceMeta') - if meta_payload is None: - meta_payload = payload.get('price_meta') now = time.time() with Session(engine) as session: # Admin re-adding a previously deleted seed clears the tombstone. diff --git a/apps/api/app/services/llm/image.py b/apps/api/app/services/llm/image.py index f9619aaa..5ce60aa4 100644 --- a/apps/api/app/services/llm/image.py +++ b/apps/api/app/services/llm/image.py @@ -116,7 +116,7 @@ def _api_model_id(catalog_id: str) -> str: """Catalog id may differ from the Ark model / endpoint id.""" for m in list_image_models(): if m["id"] == catalog_id: - return str(m.get("api_model") or m["id"]) + return str(m.get("apiModel") or m["id"]) return catalog_id or (_admin_image_default() or settings.image_default_model or _DEFAULT_IMAGE_MODEL).strip() @@ -205,9 +205,7 @@ def _catalog_image_limits(catalog_id: str) -> dict[str, Any]: from app.services.llm.catalog_store import get_model, resolve_image_limits row = get_model(catalog_id) or {} - limits = resolve_image_limits( - row.get("imageLimits") or row.get("image_limits"), - ) + limits = resolve_image_limits(row.get("imageLimits")) if limits: return limits provider = str(row.get("provider") or "").strip().lower() @@ -219,7 +217,7 @@ def _catalog_image_limits(catalog_id: str) -> dict[str, Any]: pass for m in list_image_models(): if m.get("id") == catalog_id: - lim = m.get("imageLimits") or m.get("image_limits") + lim = m.get("imageLimits") if isinstance(lim, dict) and lim: return lim if str(m.get("provider") or "").lower() == "openrouter": @@ -399,7 +397,7 @@ def _image_provider(catalog_id: str) -> str: def _max_refs_for(catalog_id: str, default: int = 14) -> int: for m in list_image_models(): if m.get("id") == catalog_id: - raw = m.get("max_attachments") + raw = m.get("maxAttachments") if isinstance(raw, int) and raw > 0: return raw break diff --git a/apps/api/app/services/llm/image_tools.py b/apps/api/app/services/llm/image_tools.py index 80eb696c..a4869a12 100644 --- a/apps/api/app/services/llm/image_tools.py +++ b/apps/api/app/services/llm/image_tools.py @@ -98,8 +98,8 @@ def _prompt_for( if kind in ("editText", "editElements", "detectRegions"): return "unused" if kind == "replaceText": - original = str(m.get("originalText") or m.get("from") or "").strip() - new = str(m.get("newText") or m.get("to") or "").strip() + original = str(m.get("originalText") or "").strip() + new = str(m.get("newText") or "").strip() if not original or not new: raise ValueError("replaceText requires meta.originalText and meta.newText") return ( diff --git a/apps/api/app/services/llm/price_sync.py b/apps/api/app/services/llm/price_sync.py index e0ad79e3..286fce8f 100644 --- a/apps/api/app/services/llm/price_sync.py +++ b/apps/api/app/services/llm/price_sync.py @@ -175,7 +175,7 @@ def sync_openrouter_catalog_prices(*, only_empty: bool = False) -> dict[str, Any for row in rows: if str(row.get("provider") or "").lower() != "openrouter": continue - api_model = str(row.get("apiModel") or row.get("api_model") or "").strip() + api_model = str(row.get("apiModel") or "").strip() if not api_model: skipped.append({"id": row.get("id"), "reason": "no api_model"}) continue @@ -192,7 +192,7 @@ def sync_openrouter_catalog_prices(*, only_empty: bool = False) -> dict[str, Any endpoints = endpoints_by_id.get(api_model) price_meta: dict[str, Any] - if kind == "image" or "image" in (row.get("referenceTypes") or row.get("reference_types") or []): + if kind == "image" or "image" in (row.get("referenceTypes") or []): bill = _pick_image_billing(pricing, endpoints) if bill is None: skipped.append({"id": row.get("id"), "reason": "no_image_price", "apiModel": api_model}) @@ -263,18 +263,18 @@ def sync_openrouter_catalog_prices(*, only_empty: bool = False) -> dict[str, Any "id": row["id"], "label": row.get("label") or row["id"], "kind": kind if kind in ("text", "image") else "text", - "referenceTypes": row.get("referenceTypes") or row.get("reference_types") or ["text"], + "referenceTypes": row.get("referenceTypes") or ["text"], "provider": "openrouter", "apiModel": api_model, "description": row.get("description"), "iconKey": row.get("iconKey"), "iconUrl": row.get("iconUrl"), "price": price_str, - "maxAttachments": int(row.get("maxAttachments") or row.get("max_attachments") or 8), + "maxAttachments": int(row.get("maxAttachments") or 8), "thinking": bool(row.get("thinking")), "enabled": bool(row.get("enabled", True)), "sortOrder": int(row.get("sortOrder") or 100), - "imageLimits": row.get("imageLimits") or row.get("image_limits"), + "imageLimits": row.get("imageLimits"), "priceMeta": price_meta, } item = upsert_model(payload) diff --git a/apps/api/app/services/llm/pricing_registry.py b/apps/api/app/services/llm/pricing_registry.py index 67fc7f41..187ee3db 100644 --- a/apps/api/app/services/llm/pricing_registry.py +++ b/apps/api/app/services/llm/pricing_registry.py @@ -39,19 +39,14 @@ def _rates_list(raw: Any) -> list[dict[str, Any]]: def row_to_dict(row: PricingVersion) -> dict[str, Any]: return { "pricingVersionId": row.pricing_version_id, - "pricing_version_id": row.pricing_version_id, "pricingId": row.pricing_id, - "pricing_id": row.pricing_id, "provider": row.provider, "modelId": row.model_id, - "model_id": row.model_id, "currency": row.currency, "rates": _rates_list(row.rates_json), "status": row.status, "effectiveFrom": row.effective_from, - "effective_from": row.effective_from, "effectiveTo": row.effective_to, - "effective_to": row.effective_to, "source": row.source, "notes": row.notes or "", "createdAt": row.created_at, @@ -168,11 +163,7 @@ def get_pricing_version(pricing_version_id: str) -> dict[str, Any] | None: def upsert_pricing_version(payload: dict[str, Any]) -> dict[str, Any]: """Create or update a draft/pending version. Active publish goes through approve().""" now = time.time() - vid = str( - payload.get("pricingVersionId") - or payload.get("pricing_version_id") - or "" - ).strip() or _id() + vid = str(payload.get("pricingVersionId") or "").strip() or _id() rates = payload.get("rates") if rates is None: rates = [] @@ -184,13 +175,9 @@ def upsert_pricing_version(payload: dict[str, Any]) -> dict[str, Any]: pricing_version_id=vid, created_at=now, ) - row.pricing_id = str( - payload.get("pricingId") or payload.get("pricing_id") or row.pricing_id or "" - ).strip() + row.pricing_id = str(payload.get("pricingId") or row.pricing_id or "").strip() row.provider = str(payload.get("provider") or row.provider or "").strip() - row.model_id = str( - payload.get("modelId") or payload.get("model_id") or row.model_id or "" - ).strip() + row.model_id = str(payload.get("modelId") or row.model_id or "").strip() row.currency = str(payload.get("currency") or row.currency or "USD").strip() or "USD" row.rates_json = rates_json status = str(payload.get("status") or row.status or "draft").strip().lower() @@ -204,8 +191,8 @@ def upsert_pricing_version(payload: dict[str, Any]) -> dict[str, Any]: status = "draft" # Direct active only when explicitly requested via approve path preferred row.status = status - ef = payload.get("effectiveFrom", payload.get("effective_from", row.effective_from)) - et = payload.get("effectiveTo", payload.get("effective_to", row.effective_to)) + ef = payload.get("effectiveFrom", row.effective_from) + et = payload.get("effectiveTo", row.effective_to) row.effective_from = float(ef) if ef is not None else row.effective_from row.effective_to = float(et) if et is not None else row.effective_to row.source = str(payload.get("source") or row.source or "").strip() diff --git a/apps/api/app/services/llm/video.py b/apps/api/app/services/llm/video.py index b048ca49..f1ea98c7 100644 --- a/apps/api/app/services/llm/video.py +++ b/apps/api/app/services/llm/video.py @@ -49,7 +49,7 @@ def resolve_video_model(model: str | None = None) -> str: def _api_model_id(catalog_id: str) -> str: for m in list_video_models(): if m["id"] == catalog_id: - return str(m.get("api_model") or m["id"]) + return str(m.get("apiModel") or m["id"]) return catalog_id or "" diff --git a/apps/api/app/services/plaza/panel_png.py b/apps/api/app/services/plaza/panel_png.py index 3df36a59..b6c6acd9 100644 --- a/apps/api/app/services/plaza/panel_png.py +++ b/apps/api/app/services/plaza/panel_png.py @@ -28,10 +28,9 @@ def _num(value: Any, default: float = 0.0) -> float: def _image_src(node: dict[str, Any]) -> str: attrs = node.get("attrs") if isinstance(node.get("attrs"), dict) else {} - for key in ("src", "url", "href", "xlink:href"): - raw = str(attrs.get(key) or node.get(key) or "").strip() - if raw.startswith(("http://", "https://", "data:image/")): - return raw + raw = str(attrs.get("src") or "").strip() + if raw.startswith(("http://", "https://", "data:image/")): + return raw return "" diff --git a/apps/api/app/services/plaza/store.py b/apps/api/app/services/plaza/store.py index 62cebcce..7a198580 100644 --- a/apps/api/app/services/plaza/store.py +++ b/apps/api/app/services/plaza/store.py @@ -502,6 +502,51 @@ def _isolate_plaza_cover( return urls[0] if urls else None +def _overlay_json_list(raw: Any) -> list[Any]: + if isinstance(raw, list): + return raw + if isinstance(raw, str) and raw.strip(): + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return parsed if isinstance(parsed, list) else [] + return [] + + +def _overlay_plain_text(attrs: dict[str, Any]) -> str: + origin_lines: list[str] = [] + for block in _overlay_json_list(attrs.get("ORIGIN_DATA")): + if not isinstance(block, dict): + continue + children = block.get("children") + if not isinstance(children, list): + continue + origin_lines.append( + "".join(str(c.get("text") or "") for c in children if isinstance(c, dict)) + ) + origin = "\n".join(part for part in origin_lines if part).strip() + if origin: + return origin + data_lines: list[str] = [] + for run in _overlay_json_list(attrs.get("DATA")): + if not isinstance(run, dict): + continue + chars = run.get("chars") + if not isinstance(chars, list): + continue + data_lines.append( + "".join(str(item.get("char") or "") for item in chars if isinstance(item, dict)) + ) + data = "\n".join(data_lines).strip() + if data: + return data + md = attrs.get("markdown") + if isinstance(md, str) and md.strip(): + return md.strip() + return "" + + def _document_has_overlay_text(document: dict[str, Any] | None) -> bool: """True when the board has readable text — list covers must not be raw bitmaps alone.""" if not isinstance(document, dict): @@ -516,7 +561,7 @@ def _document_has_overlay_text(document: dict[str, Any] | None) -> bool: if kind != "text": continue attrs = raw.get("attrs") if isinstance(raw.get("attrs"), dict) else {} - if str(attrs.get("text") or "").strip(): + if _overlay_plain_text(attrs): return True return False diff --git a/apps/api/app/services/projects.py b/apps/api/app/services/projects.py index 35113f12..efbc7f31 100644 --- a/apps/api/app/services/projects.py +++ b/apps/api/app/services/projects.py @@ -340,6 +340,51 @@ def _normalize_incoming_urls(urls: list[str] | None) -> list[str]: _MIN_COVER_EDGE = 40 +def _cov_json_list(raw: Any) -> list[Any]: + if isinstance(raw, list): + return raw + if isinstance(raw, str) and raw.strip(): + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return parsed if isinstance(parsed, list) else [] + return [] + + +def _cov_plain_text(attrs: dict[str, Any]) -> str: + origin_lines: list[str] = [] + for block in _cov_json_list(attrs.get("ORIGIN_DATA")): + if not isinstance(block, dict): + continue + children = block.get("children") + if not isinstance(children, list): + continue + origin_lines.append( + "".join(str(c.get("text") or "") for c in children if isinstance(c, dict)) + ) + origin = "\n".join(part for part in origin_lines if part) + if origin: + return origin + data_lines: list[str] = [] + for run in _cov_json_list(attrs.get("DATA")): + if not isinstance(run, dict): + continue + chars = run.get("chars") + if not isinstance(chars, list): + continue + data_lines.append( + "".join(str(item.get("char") or "") for item in chars if isinstance(item, dict)) + ) + data = "\n".join(data_lines) + if data: + return data + md = attrs.get("markdown") + if isinstance(md, str) and md.strip(): + return md.strip() + return "" + + def _cov_num(value: Any, fallback: float = 0.0) -> float: try: n = float(value) @@ -513,22 +558,16 @@ def _cov_raster_shape(node: dict[str, Any]) -> bytes | None: canvas_w = out_w + pad * 2 canvas_h = out_h + pad * 2 - fill = _cov_parse_rgba(attrs.get("fill") or attrs.get("fill-color")) - stroke = _cov_parse_rgba( - attrs.get("stroke") or attrs.get("border-color") or attrs.get("borderColor") - ) - sw_raw = attrs.get("borderWidth") - if sw_raw is None: - sw_raw = attrs.get("border-width") - if sw_raw is None: - sw_raw = attrs.get("strokeWidth") + fill = _cov_parse_rgba(attrs.get("fill-color")) + stroke = _cov_parse_rgba(attrs.get("border-color")) + sw_raw = attrs.get("border-width") stroke_w = max(0.0, _cov_num(sw_raw, 0)) * scale if stroke is None and stroke_w <= 0: stroke = (51, 51, 51, 255) stroke_w = max(1.5, 2.0 * scale) key = str(node.get("key") or "") - shape_type = str(attrs.get("shapeType") or attrs.get("type") or "").lower() + shape_type = str(attrs.get("shapeType") or "").lower() if not shape_type and key == "rect": shape_type = "rect" if not shape_type: @@ -572,9 +611,7 @@ def _cov_raster_text(node: dict[str, Any]) -> bytes | None: except Exception: return None attrs = node.get("attrs") if isinstance(node.get("attrs"), dict) else {} - text = str( - attrs.get("text") or attrs.get("content") or node.get("text") or "" - ).strip() + text = _cov_plain_text(attrs).strip() if not text: return None w = max(64.0, _cov_num(node.get("width"), 160)) @@ -582,7 +619,7 @@ def _cov_raster_text(node: dict[str, Any]) -> bytes | None: scale = min(1.0, float(_COVER_EDGE) / max(w, h)) out_w = max(48, int(round(w * scale))) out_h = max(32, int(round(h * scale))) - fill = _cov_parse_rgba(attrs.get("fill") or attrs.get("color")) or (30, 30, 30, 255) + fill = _cov_parse_rgba(attrs.get("fill-color")) or (30, 30, 30, 255) img = Image.new("RGB", (out_w, out_h), (255, 255, 255)) draw = ImageDraw.Draw(img) try: diff --git a/apps/api/app/services/vision/crop.py b/apps/api/app/services/vision/crop.py index 5c0cfb95..3f0ad734 100644 --- a/apps/api/app/services/vision/crop.py +++ b/apps/api/app/services/vision/crop.py @@ -45,7 +45,7 @@ def attach_crops(img_bgr, blocks: list[dict[str, Any]], page_index: int = 0) -> for block in blocks: item = dict(block) btype = str(item.get("type") or "") - layout = str(item.get("layout_type") or btype).lower() + layout = str(item.get("layout_type") or "").lower() if btype == "table" or layout == "table": if settings.expand_table_cells: @@ -70,13 +70,13 @@ def attach_crops(img_bgr, blocks: list[dict[str, Any]], page_index: int = 0) -> out.append(item) continue - if btype in {"image", "figure"} or layout in {"figure", "image", "equation"}: + if btype == "image" or layout in {"figure", "image", "equation"}: if not item.get("src"): src = crop_region_to_data_url(img_bgr, item) if src: item["type"] = "image" item["src"] = src - item["layout_type"] = layout or btype + item["layout_type"] = layout or "image" else: item["type"] = "rect" item["fill"] = "#F0F0F0" diff --git a/apps/api/app/services/vision/image_edit.py b/apps/api/app/services/vision/image_edit.py index 41c3d96d..7eb88d7a 100644 --- a/apps/api/app/services/vision/image_edit.py +++ b/apps/api/app/services/vision/image_edit.py @@ -394,7 +394,7 @@ def _collect_text_blocks(path: Path) -> tuple[list[dict[str, Any]], str]: figures = [ b for b in blocks - if b.get("type") in {"image", "figure"} + if b.get("type") == "image" or str(b.get("layout_type") or "").lower() in {"figure", "image", "equation"} ] return merge_text_blocks(texts) + figures, engine @@ -449,7 +449,7 @@ def _collect_subjects(bgr, path: Path, texts: list[dict[str, Any]], mixed_blocks for b in mixed_blocks: if str(b.get("type") or "") == "text": continue - layout = str(b.get("layout_type") or b.get("type") or "").lower() + layout = str(b.get("layout_type") or "").lower() if layout not in {"figure", "image", "equation", "sam"}: continue region = { diff --git a/apps/api/app/services/wallet/billing.py b/apps/api/app/services/wallet/billing.py index a974dd57..93f4b2fd 100644 --- a/apps/api/app/services/wallet/billing.py +++ b/apps/api/app/services/wallet/billing.py @@ -4,7 +4,7 @@ Design runs authorize from ``TaskPricingSchema`` (base + steps). Capture prefers an optional remote quote (``credits_to_charge`` only). -Legacy chat/image helpers remain as OSS fallback when no quote is available. +OSS chat/image conversion remains when no quote is available. BYOK: waive provider credit conversion; still charge Agent orchestration (CreditPolicySchema.byok_agent_fee_credits). @@ -70,43 +70,36 @@ "period": "month", }, ) -_PLAN_ID_ALIASES = {"studio": "ultra", "basic": "plus", "hobby": "free"} _catalog_cache: tuple[float, list[dict[str, Any]]] | None = None _CATALOG_TTL_SEC = 60.0 -def _canonical_plan_id(raw: Any) -> str: - pid = str(raw or "").strip().lower() - return _PLAN_ID_ALIASES.get(pid, pid) +def _plan_id(raw: Any) -> str: + return str(raw or "").strip().lower() def _sanitize_plan_row(raw: Any) -> dict[str, Any] | None: if not isinstance(raw, dict): return None - pid = _canonical_plan_id(raw.get("planId") or raw.get("plan_id")) + pid = _plan_id(raw.get("planId")) if pid not in ("free", "plus", "pro", "ultra"): return None - feats = raw.get("features") if isinstance(raw.get("features"), dict) else {} - daily = feats.get("daily_runs") if "daily_runs" in feats else raw.get("dailyRuns") try: - price = int(raw.get("priceCny") if raw.get("priceCny") is not None else raw.get("list_price_cny") or 0) + price = int(raw.get("priceCny") or 0) except (TypeError, ValueError): price = 0 try: - credits = int( - raw.get("creditsIncluded") - if raw.get("creditsIncluded") is not None - else raw.get("credits_grant") or 0 - ) + credits = int(raw.get("creditsIncluded") or 0) except (TypeError, ValueError): credits = 0 row: dict[str, Any] = { "planId": pid, "priceCny": max(0, price), "creditsIncluded": max(0, credits), - "period": str(raw.get("period") or raw.get("credits_period") or "month"), + "period": str(raw.get("period") or "month"), } try: + daily = raw.get("dailyRuns") if daily is not None: row["dailyRuns"] = max(0, int(daily)) except (TypeError, ValueError): @@ -145,7 +138,7 @@ def public_plan_catalog(*, force: bool = False) -> list[dict[str, Any]]: def plan_row(plan_id: str) -> dict[str, Any] | None: - pid = _canonical_plan_id(plan_id) + pid = _plan_id(plan_id) for row in public_plan_catalog(): if row.get("planId") == pid: return row @@ -363,7 +356,7 @@ def image_model_credit_cost( for m in list_image_models(): if str(m.get("id") or "") == mid: - meta = m.get("priceMeta") or m.get("price_meta") + meta = m.get("priceMeta") price_cny = resolve_image_unit_cny( price=m.get("price"), price_meta=meta if isinstance(meta, dict) else None, diff --git a/apps/api/app/services/wallet/card_keys.py b/apps/api/app/services/wallet/card_keys.py index 07525729..c90ece85 100644 --- a/apps/api/app/services/wallet/card_keys.py +++ b/apps/api/app/services/wallet/card_keys.py @@ -53,15 +53,8 @@ "pro": 1030, "ultra": 4000, } -# Deprecated alias (always 0) — redeem no longer splits image gifts. -PLAN_IMAGE_CREDITS: dict[str, int] = { - "plus": 0, - "pro": 0, - "ultra": 0, -} VALID_PLAN_IDS = frozenset(PLAN_CREDITS.keys()) VALID_KINDS = frozenset({"credit", "plan"}) -TOKENS_PER_CREDIT = 15_000 # Membership length after redeeming a plan card key (calendar days). PLAN_DURATION_DAYS = 30 @@ -159,13 +152,13 @@ def _normalize_topup_amount(amount: int) -> int: def resolve_generate_spec( *, kind: str, - tokens: int, + credits: int, plan_id: str | None, ) -> tuple[str, int, str | None]: """ Normalize generate inputs → (kind, amount, plan_id). Top-ups are stored as kind=credit (积分). - ``tokens`` column on card_keys stores the 积分 face value. + DB column ``tokens`` stores the 积分 face value. """ k = str(kind or "credit").strip().lower() if k not in VALID_KINDS: @@ -174,13 +167,13 @@ def resolve_generate_spec( pid = normalize_plan_id(plan_id) if pid not in VALID_PLAN_IDS: raise ValueError("planId must be plus, pro, or ultra") - amt = int(tokens or 0) - if amt <= 0 or amt >= TOKENS_PER_CREDIT: + amt = int(credits or 0) + if amt <= 0: from app.services.wallet.billing import plan_credit_grant amt = int(plan_credit_grant(pid) or PLAN_CREDITS[pid]) return "plan", amt, pid - amt = _normalize_topup_amount(int(tokens or 0)) + amt = _normalize_topup_amount(int(credits or 0)) if amt <= 0: raise ValueError("amount must be > 0 for credit keys") return "credit", amt, None @@ -190,7 +183,7 @@ def _row_out( *, kid: Any, code: str | None, - tokens: int, + credits: int, kind: str, plan_id: str | None, status: str, @@ -201,7 +194,7 @@ def _row_out( return { "id": str(kid), "code": code, - "tokens": int(tokens), + "credits": int(credits), "kind": kind, "planId": plan_id, "status": status, @@ -214,7 +207,7 @@ def _row_out( def insert_card_keys( *, plaintexts: list[str], - tokens: int, + credits: int, expires_at: float | None, kind: str = "credit", plan_id: str | None = None, @@ -225,8 +218,8 @@ def insert_card_keys( from app import crud from app.core.db import engine - kind_n, tokens_n, plan_n = resolve_generate_spec( - kind=kind, tokens=tokens, plan_id=plan_id + kind_n, credits_n, plan_n = resolve_generate_spec( + kind=kind, credits=credits, plan_id=plan_id ) ensure_card_keys_v2() require_strong_card_key_salt() @@ -237,7 +230,7 @@ def insert_card_keys( row = crud.create_card_key( session=session, key_hash=hash_card_key(plain), - tokens=tokens_n, + tokens=credits_n, kind=kind_n, plan_id=plan_n, expires_at=expires_at, @@ -253,7 +246,7 @@ def insert_card_keys( def generate_card_keys( *, count: int, - tokens: int = 0, + credits: int = 0, expires_days: int = 0, kind: str = "credit", plan_id: str | None = None, @@ -269,8 +262,8 @@ def generate_card_keys( require_strong_card_key_salt() ensure_card_keys_v2() - kind_n, tokens_n, plan_n = resolve_generate_spec( - kind=kind, tokens=tokens, plan_id=plan_id + kind_n, credits_n, plan_n = resolve_generate_spec( + kind=kind, credits=credits, plan_id=plan_id ) expires_at = None @@ -294,7 +287,7 @@ def generate_card_keys( row = crud.create_card_key( session=session, key_hash=hash_card_key(plain), - tokens=tokens_n, + tokens=credits_n, kind=kind_n, plan_id=plan_n, expires_at=expires_at, @@ -307,7 +300,7 @@ def generate_card_keys( _row_out( kid=row.id, code=plain, - tokens=tokens_n, + credits=credits_n, kind=kind_n, plan_id=plan_n, status="unused", @@ -339,7 +332,7 @@ def list_card_keys(*, status: str | None = None, limit: int = 200) -> list[dict[ _row_out( kid=row.id, code=None, - tokens=int(row.tokens or 0), + credits=int(row.tokens or 0), kind=kind if kind in VALID_KINDS else "credit", plan_id=plan_id if plan_id in VALID_PLAN_IDS else None, status=str(row.status), @@ -450,8 +443,6 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: base = prev_expires next_expires = base + PLAN_DURATION_DAYS * 86400 gift = amount if amount > 0 else int(PLAN_CREDITS.get(plan_id) or 0) - if gift >= TOKENS_PER_CREDIT: - gift = int(PLAN_CREDITS.get(plan_id) or 0) amount = gift else: gift = _normalize_topup_amount(amount) @@ -511,9 +502,7 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: return { "kind": "plan" if kind == "plan" else "credit", "creditsAdded": gift, - "tokensAdded": gift, "credits": next_credits, - "tokens": next_credits, "planId": next_plan if ( next_plan == "free" or next_expires is None diff --git a/apps/api/app/services/wallet/db.py b/apps/api/app/services/wallet/db.py index b4d129fa..b3f28733 100644 --- a/apps/api/app/services/wallet/db.py +++ b/apps/api/app/services/wallet/db.py @@ -103,7 +103,7 @@ def ensure_user_balance(user_id: str, *, starting_tokens: int = 0) -> int: def get_wallet(user_id: str) -> dict[str, Any]: - """Unified 积分 + plan. ``credits`` and ``tokens`` are the same balance.""" + """Unified 积分 + plan. HTTP field is ``credits`` (DB column remains ``tokens``).""" from sqlmodel import Session from app import crud @@ -114,7 +114,6 @@ def get_wallet(user_id: str) -> dict[str, Any]: if not uid: return { "credits": 0, - "tokens": 0, "planId": "free", "planExpiresAt": None, "planLocked": False, @@ -134,7 +133,6 @@ def get_wallet(user_id: str) -> dict[str, Any]: return { "credits": credits, - "tokens": credits, "planId": effective, "planStored": stored, "planExpiresAt": expires_at, diff --git a/apps/api/scripts/gen_card_keys.py b/apps/api/scripts/gen_card_keys.py index 01efd6f6..80a6663f 100644 --- a/apps/api/scripts/gen_card_keys.py +++ b/apps/api/scripts/gen_card_keys.py @@ -7,7 +7,7 @@ 4. Delete that file after upload Usage (from apps/api): - python -m scripts.gen_card_keys --count 20 --tokens 10000 --expires-days 365 --out ./_card_keys_export.txt + python -m scripts.gen_card_keys --count 20 --credits 50 --expires-days 365 --out ./_card_keys_export.txt Env: CARD_KEY_SALT must be a strong random string (len>=24), same as the API. @@ -51,7 +51,7 @@ def main() -> int: help="Required for --kind plan: plus | pro | ultra", ) parser.add_argument( - "--tokens", + "--credits", type=int, default=0, help="Credits per key (required for credit; optional for plan — uses catalog default)", @@ -73,8 +73,8 @@ def main() -> int: if args.count <= 0 or args.count > 10_000: print("error: --count must be 1..10000", file=sys.stderr) return 1 - if args.kind == "credit" and args.tokens <= 0: - print("error: --tokens must be > 0 for credit keys", file=sys.stderr) + if args.kind == "credit" and args.credits <= 0: + print("error: --credits must be > 0 for credit keys", file=sys.stderr) return 1 if args.kind == "plan" and args.plan_id.strip().lower() not in ("plus", "pro", "ultra"): print("error: --plan-id must be plus|pro|ultra for plan keys", file=sys.stderr) @@ -107,7 +107,7 @@ def main() -> int: inserted = insert_card_keys( plaintexts=plaintexts, - tokens=args.tokens, + credits=args.credits, expires_at=expires_at, kind=args.kind, plan_id=args.plan_id or None, @@ -118,7 +118,7 @@ def main() -> int: header = ( f"# recombyn card keys — kind={args.kind} plan={args.plan_id or '-'} " - f"credits={args.tokens} each — count={inserted}\n" + f"credits={args.credits} each — count={inserted}\n" f"# Upload to your card platform, then DELETE this file.\n" f"# Generated at unix={int(time.time())}\n" ) diff --git a/apps/api/tests/design_engine/test_design_governance.py b/apps/api/tests/design_engine/test_design_governance.py index b9536c7e..bed4d533 100644 --- a/apps/api/tests/design_engine/test_design_governance.py +++ b/apps/api/tests/design_engine/test_design_governance.py @@ -112,7 +112,7 @@ def test_pass_clean_brief(): "accessibility": {"fg": "#111111", "bg": "#f5f5f5"}, }, prompt="editorial poster", - apply_ops=[{"op": "create_node"}], + apply_ops=[{"name": "create_shape", "args": {"shapeType": "rect"}}], ) assert result["status"] == "pass" assert result["repair_plan"] is None @@ -153,7 +153,7 @@ def test_fail_explain_repair_draft_not_ops(): }, prompt="use shutterstock hero", flags={"unauthorized_colors": ["#ff00aa"], "reference_similarity": 0.97}, - apply_ops=[{"op": "delete_database"}], + apply_ops=[{"name": "delete_database"}], ) assert result["status"] == "fail" assert result["explain"] diff --git a/apps/api/tests/design_engine/test_language_and_reply.py b/apps/api/tests/design_engine/test_language_and_reply.py index 0d574d96..9939288f 100644 --- a/apps/api/tests/design_engine/test_language_and_reply.py +++ b/apps/api/tests/design_engine/test_language_and_reply.py @@ -73,8 +73,9 @@ def test_design_intensity_maps_review_mode(): _review_mode_for_intensity, ) - assert _normalize_design_intensity("轻度") == "light" - assert _normalize_design_intensity("极高") == "extreme" + assert _normalize_design_intensity("light") == "light" + assert _normalize_design_intensity("extreme") == "extreme" + assert _normalize_design_intensity("unknown") == "medium" assert _review_mode_for_intensity("light") == "off" assert _review_mode_for_intensity("medium") == "auto" assert _review_mode_for_intensity("high") == "always" diff --git a/apps/api/tests/design_engine/test_optimization.py b/apps/api/tests/design_engine/test_optimization.py index 176eadaf..36ed6a5b 100644 --- a/apps/api/tests/design_engine/test_optimization.py +++ b/apps/api/tests/design_engine/test_optimization.py @@ -155,8 +155,8 @@ def test_restore_ops_update_and_delete_not_create(): hero = next( o for o in ops if o["name"] == "update_node" and o["args"].get("nodeId") == "hero" ) - assert hero["args"]["w"] == 720 - assert hero["args"]["h"] == 1100 + assert hero["args"]["width"] == 720 + assert hero["args"]["height"] == 1100 def test_controller_eats_score_issues_diff_iteration_cost(): diff --git a/apps/api/tests/unit_tests/test_agent_controller_parse.py b/apps/api/tests/unit_tests/test_agent_controller_parse.py index f69801ff..24fda92a 100644 --- a/apps/api/tests/unit_tests/test_agent_controller_parse.py +++ b/apps/api/tests/unit_tests/test_agent_controller_parse.py @@ -282,7 +282,7 @@ def test_heuristic_user_intent_gate(): from app.services.design.runtime.models_route import normalize_session_action assert normalize_session_action("clear_context") == "clear_context" - assert normalize_session_action("new_chat") == "clear_context" + assert normalize_session_action("new_chat") == "" assert normalize_session_action("stop") == "stop" assert normalize_session_action("canvas") == "" bare = heuristic_user_intent("清空上下文", has_images=False) diff --git a/apps/api/tests/unit_tests/test_design_run_lifecycle.py b/apps/api/tests/unit_tests/test_design_run_lifecycle.py index c94fed81..60216f81 100644 --- a/apps/api/tests/unit_tests/test_design_run_lifecycle.py +++ b/apps/api/tests/unit_tests/test_design_run_lifecycle.py @@ -282,7 +282,7 @@ def test_worker_snapshot_preserves_behavior_affecting_request_fields(): scene="website", focus_frame_id="f1", scene_nodes=[{"id": "n1", "type": "shape", "x": 1, "secret": "drop"}], - scene_frames=[{"id": "f1", "name": "Board", "width": 800, "ignored": True}], + scene_frames=[{"id": "f1", "name": "Board", "w": 800, "ignored": True}], images=["data:image/png;base64,x", "https://cdn.example.com/a.png"], style_group_id=7, ref_image_sizes=["10x20"], @@ -482,7 +482,7 @@ def test_filter_unemitted_ops_idempotent(): st = AgentRunState(task_id="t", trace_id="tr", goal="") ops = [ {"name": "create_rect", "op_id": "a1", "args": {}}, - {"name": "create_text", "args": {"op_id": "a2"}}, + {"name": "create_text", "op_id": "a2", "args": {}}, {"name": "noop", "args": {}}, ] assert _op_id_of(ops[0]) == "a1" diff --git a/apps/api/tests/unit_tests/test_design_sse_progress.py b/apps/api/tests/unit_tests/test_design_sse_progress.py index 3c7eaf56..e881ab75 100644 --- a/apps/api/tests/unit_tests/test_design_sse_progress.py +++ b/apps/api/tests/unit_tests/test_design_sse_progress.py @@ -53,7 +53,7 @@ def test_agent_event_envelope_is_stable_and_user_visible() -> None: "phase": "ops", "elapsed_ms": payload["agent_event"]["elapsed_ms"], "can_cancel": True, - "can_resume": False, + "resumable": False, } diff --git a/apps/api/tests/unit_tests/test_prompt_packs.py b/apps/api/tests/unit_tests/test_prompt_packs.py index 926f967c..92d5b92e 100644 --- a/apps/api/tests/unit_tests/test_prompt_packs.py +++ b/apps/api/tests/unit_tests/test_prompt_packs.py @@ -1,16 +1,6 @@ -from app.services.design.prompts.prompt_pack_store import ( - seed_prompt_overlay_nodes, -) from app.services.design.prompts.skill_store import format_skills_details -def test_seed_prompt_overlay_nodes_empty(): - """need_* overlay nodes are not seeded (skills carry playbooks).""" - nodes = seed_prompt_overlay_nodes() - assert nodes == [] - - - def test_playbooks_live_in_design_skills_packs(): from app.services.design.prompts.skill_store import ( _SEED as _SKILL_SEED, diff --git a/apps/api/tests/unit_tests/test_task_pricing_capture.py b/apps/api/tests/unit_tests/test_task_pricing_capture.py index 813e36b4..e9ad9ea9 100644 --- a/apps/api/tests/unit_tests/test_task_pricing_capture.py +++ b/apps/api/tests/unit_tests/test_task_pricing_capture.py @@ -65,9 +65,9 @@ def test_oss_plan_catalog_plus_sku(): plus = next(p for p in oss_plan_catalog() if p["planId"] == "plus") assert plus["priceCny"] == 49 assert plus["creditsIncluded"] == 340 - studio = _sanitize_plan_row( - {"plan_id": "studio", "list_price_cny": 499, "credits_grant": 4000} + ultra = _sanitize_plan_row( + {"planId": "ultra", "priceCny": 499, "creditsIncluded": 4000, "period": "month"} ) - assert studio and studio["planId"] == "ultra" + assert ultra and ultra["planId"] == "ultra" live = {p["planId"]: p for p in public_plan_catalog(force=True)} assert live["plus"]["priceCny"] == 49 diff --git a/apps/api/tests/unit_tests/test_tool_ops_contract.py b/apps/api/tests/unit_tests/test_tool_ops_contract.py index 1b098c2b..a39cf6b3 100644 --- a/apps/api/tests/unit_tests/test_tool_ops_contract.py +++ b/apps/api/tests/unit_tests/test_tool_ops_contract.py @@ -46,8 +46,8 @@ def test_rejects_unknown_node_id(): def test_dedupe_by_op_id(): raw_ops = [ - {"name": "update_node", "args": {"nodeId": "n1", "fill": "#111", "op_id": "same-id"}}, - {"name": "update_node", "args": {"nodeId": "n1", "fill": "#222", "op_id": "same-id"}}, + {"name": "update_node", "op_id": "same-id", "args": {"nodeId": "n1", "fill": "#111"}}, + {"name": "update_node", "op_id": "same-id", "args": {"nodeId": "n1", "fill": "#222"}}, ] ops, errs = normalize_agent_tool_ops( raw_ops, diff --git a/apps/web/src/components/account/AccountProfileTab.tsx b/apps/web/src/components/account/AccountProfileTab.tsx index 184af13b..59e91c1e 100644 --- a/apps/web/src/components/account/AccountProfileTab.tsx +++ b/apps/web/src/components/account/AccountProfileTab.tsx @@ -53,7 +53,7 @@ function readAvatarDataUrl(file: File): Promise { type Props = { user: AuthUser | null; - tokens: number; + credits: number; creditCap: number; planUsed: number; planRemaining: number; @@ -65,7 +65,7 @@ type Props = { /** Profile / account / billing cards for the account settings hub. */ function AccountProfileTab({ user, - tokens, + credits, creditCap, planUsed, planRemaining, @@ -296,7 +296,7 @@ function AccountProfileTab({ {t('wallet.credits')} - {t('wallet.creditsRemaining', { count: formatTokens(tokens) })} + {t('wallet.creditsRemaining', { count: formatTokens(credits) })}