diff --git a/.github/workflows/api-tests.yml b/.github/workflows/api-tests.yml deleted file mode 100644 index c377c5a0..00000000 --- a/.github/workflows/api-tests.yml +++ /dev/null @@ -1,59 +0,0 @@ -name: API Tests - -on: - push: - branches: [main, master, develop] - paths: - - 'apps/api/**' - - '.github/workflows/api-tests.yml' - pull_request: - paths: - - 'apps/api/**' - - '.github/workflows/api-tests.yml' - -jobs: - pytest: - runs-on: ubuntu-latest - defaults: - run: - working-directory: apps/api - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - cache: pip - cache-dependency-path: apps/api/pyproject.toml - - - name: Install API (+ test extras) - run: | - python -m pip install --upgrade pip - pip install -e "../../packages/scene-builder-py" - pip install -e "../../packages/protocol" - pip install -e "../../packages/runtime" - pip install -e "../../packages/intelligence-client" - pip install -e "../../packages/agent-sdk" - pip install -e "../../packages/skill-sdk" - pip install -e "../../packages/plugin-sdk" - pip install -e "../../packages/billing-sdk" - pip install -e ".[dev]" - - - name: Alembic single head - run: python -m pytest tests/unit_tests/test_llm_facade_adr0006.py::test_alembic_single_head -q - - - name: Hydrate route coverage floor - run: > - python -m pytest tests/unit_tests/test_design_hydrate_jobs.py - --cov=app.api.routes.design_hydrate_jobs - --cov-report=term-missing - --cov-fail-under=95 - - - name: Unit tests - run: python -m pytest tests/unit_tests -n auto - - - name: Integration tests - run: python -m pytest tests/integration_tests - - - name: Coverage (unit + integration) - run: python -m pytest --cov=app --cov-report=term-missing diff --git a/.github/workflows/web-tests.yml b/.github/workflows/web-tests.yml deleted file mode 100644 index c9aaddc0..00000000 --- a/.github/workflows/web-tests.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Web Tests - -on: - pull_request: - paths: - - 'apps/web/**' - - 'packages/tsconfig/**' - - 'packages/eslint-config/**' - - 'packages/contracts/**' - - 'turbo.json' - - 'package.json' - - 'package-lock.json' - - '.github/workflows/web-tests.yml' - push: - branches: [main, master, develop] - paths: - - 'apps/web/**' - - 'packages/tsconfig/**' - - 'packages/eslint-config/**' - - 'packages/contracts/**' - - 'turbo.json' - - 'package.json' - - 'package-lock.json' - - '.github/workflows/web-tests.yml' - -jobs: - unit: - runs-on: ubuntu-latest - defaults: - run: - working-directory: . - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version: '22' - cache: npm - cache-dependency-path: package-lock.json - - - name: Install - run: npm ci - - - name: Unit tests - run: npm run test:web - - - name: Canvas stress bench - run: npm run test:stress --workspace=apps/web - - - name: Coverage - run: npm run test:web:coverage diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c49bdde9..7743ce3e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -156,7 +156,7 @@ Use the checklist in [`.github/PULL_REQUEST_TEMPLATE.md`](./.github/PULL_REQUEST ## Intelligence providers -Design Runtime calls `packages/intelligence-client` (`DesignIntelligenceClient`). The default is **BasicLocal** (in-repo, no network). Optional remote providers use `RECOMBYN_INTELLIGENCE_MODE=cloud` + `RECOMBYN_INTELLIGENCE_URL` (legacy `INTELLIGENCE_*` still accepted) and must implement the open `IntelligenceProvider` protocol — see [ADR 0017](./docs/adr/0017-intelligence-provider-boundary.md). Compose override: `docker-compose.intelligence.yml` (`--profile intelligence`). **Do not** add docs that describe closed / proprietary provider internals in this repository. +Design Runtime calls `packages/intelligence-client` (`DesignIntelligenceClient`). The default is **BasicLocal** (in-repo, no network). Optional remote providers use `RECOMBYN_INTELLIGENCE_MODE=cloud` + `RECOMBYN_INTELLIGENCE_URL` and must implement the open `IntelligenceProvider` protocol — see [ADR 0017](./docs/adr/0017-intelligence-provider-boundary.md). Compose override: `docker-compose.intelligence.yml` (`--profile intelligence`). **Do not** add docs that describe closed / proprietary provider internals in this repository. Shared wire contract lives in `packages/protocol` (`recombyn-protocol`). Bump its version when method names / request keys / usable rules change ([ADR 0024](./docs/adr/0024-protocol-version-cross-repo-ci.md)). Operators who maintain a private Intelligence service should depend on that package and run compatibility tests against it — do not hand-copy method lists into closed repos. diff --git a/README.md b/README.md index 77880c82..805a2cda 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,35 @@ docker compose up -d --build More options (env, LLM keys, production hardening): **[docs/self-hosting.md](docs/self-hosting.md)** · Postgres: **[docs/postgres-switch.md](docs/postgres-switch.md)** +### Compose recipes + +Use `docker-compose.yml` as the base stack, then layer overrides only when needed: + +```bash +# 1) Base self-host stack (web + api + collab + mysql + redis + worker) +docker compose -f docker-compose.yml up -d --build + +# 2) Base + ClamAV upload scanning +docker compose --profile av \ + -f docker-compose.yml \ + -f docker-compose.av.yml \ + up -d --build + +# 3) Base + external/sibling intelligence provider service +docker compose --profile intelligence \ + -f docker-compose.yml \ + -f docker-compose.intelligence.yml \ + up -d --build + +# 4) Base stack from pre-built GHCR images (skip local image builds) +docker compose -f docker-compose.yml -f docker-compose.ghcr.yml pull +docker compose -f docker-compose.yml -f docker-compose.ghcr.yml up -d +``` + +Tip: if you layer `*.av.yml` or `*.intelligence.yml`, keep the matching profile flag (`--profile av` / `--profile intelligence`) in the same command. + +Env tip: keep Compose variables in repo-root `.env` (for example `RECOMBYN_TAG`, `RECOMBYN_INTELLIGENCE_*`) and API app variables in `apps/api/.env`; avoid passing env values inline in shell commands. + ### Local development ```bash diff --git a/apps/api/.env.example b/apps/api/.env.example index e78f378b..28429d2f 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -13,7 +13,7 @@ ENABLE_SAM=false ENABLE_LAMA=false LAMA_USE_SAM_MASK=true -# Object storage (S3-compatible). Empty = local disk. +# Object storage (S3-style). Empty = local disk. S3_ENABLED=false # S3_ENDPOINT_URL= # S3_ACCESS_KEY= @@ -45,16 +45,12 @@ S3_ENABLED=false # DESIGN_PLUGIN_DISK_INSTALL=false # AGENT_PROFILE_ID=design.canvas # Design Intelligence client (ADR 0017). local = BasicLocal (default). -# Prefer RECOMBYN_INTELLIGENCE_*; legacy INTELLIGENCE_* still accepted. +# Prefer RECOMBYN_INTELLIGENCE_*. # remote|cloud → HTTP provider implementing open IntelligenceProvider methods. # RECOMBYN_INTELLIGENCE_MODE=local # RECOMBYN_INTELLIGENCE_URL= # RECOMBYN_INTELLIGENCE_API_KEY= # RECOMBYN_INTELLIGENCE_TIMEOUT_SEC=30 -# INTELLIGENCE_PROVIDER=local -# INTELLIGENCE_REMOTE_URL= -# INTELLIGENCE_REMOTE_API_KEY= -# INTELLIGENCE_REMOTE_TIMEOUT_SEC=30 # DESIGN_CRITIQUE_ENABLED=true # DESIGN_REVIEW_AGENT_ENABLED=true # DESIGN_GRAPH_NODE_TIMEOUT_SEC=180 diff --git a/apps/api/app/api/routes/admin/common.py b/apps/api/app/api/routes/admin/common.py index 14518c09..34299129 100644 --- a/apps/api/app/api/routes/admin/common.py +++ b/apps/api/app/api/routes/admin/common.py @@ -123,9 +123,9 @@ class AdjustTokensIn(BaseModel): class GenerateCardKeysIn(BaseModel): count: int = Field(default=10, ge=1, le=100) - """credit = unified 积分 top-up; plan = membership + monthly 积分; token = legacy alias of credit.""" + """credit = unified 积分 top-up; plan = membership + monthly 积分.""" kind: str = Field(default="credit", max_length=16) - # Face value in 积分 (legacy million-Token faces are converted server-side). + # Face value in 积分. tokens: 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) @@ -220,7 +220,6 @@ class RuntimeSettingIn(BaseModel): "precheck.user_preset.balanced", "precheck.user_preset.quality", "assets.image_default_model", - "byok.preset_providers", "byok.preset_platforms", } ) diff --git a/apps/api/app/api/routes/admin/design.py b/apps/api/app/api/routes/admin/design.py index 408eac1b..620681d5 100644 --- a/apps/api/app/api/routes/admin/design.py +++ b/apps/api/app/api/routes/admin/design.py @@ -203,7 +203,7 @@ def admin_design_stage_reviews( minRating: int | None = Query(default=None, ge=1, le=5), maxRating: int | None = Query(default=None, ge=1, le=5), ) -> dict[str, Any]: - """Historical stage ratings (legacy training runs).""" + """Historical stage ratings.""" return list_stage_reviews( page=page, page_size=pageSize, diff --git a/apps/api/app/api/routes/auth.py b/apps/api/app/api/routes/auth.py index 734f6e1d..e80ab631 100644 --- a/apps/api/app/api/routes/auth.py +++ b/apps/api/app/api/routes/auth.py @@ -328,7 +328,7 @@ class EmailActivateIn(BaseModel): @router.post("/email/activate", response_model=AuthSessionOut) def email_activate(body: EmailActivateIn, request: Request) -> dict[str, Any]: - """Consume one-time /activate/{{id}} link → session (legacy magic-link mails).""" + """Consume one-time /activate/{{id}} link → session (email magic-link mails).""" ip = _client_ip(request) try: email = consume_activate_token(body.id) @@ -582,7 +582,6 @@ def wallet_me(current_user: CurrentUser) -> dict[str, Any]: return { "credits": credits, "tokens": credits, - "imageCredits": credits, **_wallet_plan_fields(snap), "ledger": list_ledger(current_user.id), } @@ -605,7 +604,6 @@ def wallet_ledger( return { "credits": credits, "tokens": credits, - "imageCredits": credits, **_wallet_plan_fields(snap), **list_ledger_page(current_user.id, page=page, page_size=pageSize, kind=kind), } @@ -650,7 +648,6 @@ def wallet_redeem( "tokensAdded": added, "credits": credits, "tokens": credits, - "imageCredits": credits, **_wallet_plan_fields(snap), "ledger": list_ledger(current_user.id), } diff --git a/apps/api/app/api/routes/chat.py b/apps/api/app/api/routes/chat.py index c60cabc0..e0509e51 100644 --- a/apps/api/app/api/routes/chat.py +++ b/apps/api/app/api/routes/chat.py @@ -30,11 +30,9 @@ from app.services.llm.usage_log import bind_usage_context from app.services.wallet.db import ( consume_free_daily_quota, - get_user_image_credits, get_user_plan, get_user_tokens, is_wallet_billing_enabled, - spend_image_credits, spend_tokens, ) @@ -110,19 +108,6 @@ def _charge(user_id: str, amount: int, detail: str) -> None: raise HTTPException(status_code=400, detail=str(err)) from err -def _charge_image_credits(user_id: str, amount: int, detail: str) -> None: - if amount <= 0 or not is_wallet_billing_enabled(): - return - try: - spend_image_credits(user_id, amount, detail) - except ValueError as err: - if str(err) == "insufficient_image_credits": - raise HTTPException(status_code=402, detail="Insufficient credits") from err - raise HTTPException(status_code=400, detail=str(err)) from err - - - - def _charge_image( user_id: str, requested_model: str | None, @@ -146,9 +131,9 @@ def _charge_image( if plan == "free": mid = _FREE_IMAGE_MODEL cost = image_model_credit_cost(mid, count=n, resolution=resolution) - bal = get_user_image_credits(user_id) + bal = get_user_tokens(user_id) if bal >= cost: - _charge_image_credits(user_id, cost, "AI image generation") + _charge(user_id, cost, "AI image generation") return mid, cost if consume_free_daily_quota(user_id): return mid, 0 @@ -162,7 +147,7 @@ def _charge_image( if mid else DEFAULT_IMAGE_CREDITS * n ) - _charge_image_credits(user_id, cost, "AI image generation") + _charge(user_id, cost, "AI image generation") return mid, cost @@ -182,7 +167,7 @@ def _charge_video( else DEFAULT_IMAGE_CREDITS ) cost = max(DEFAULT_IMAGE_CREDITS, int(cost or DEFAULT_IMAGE_CREDITS)) - _charge_image_credits(user_id, cost, "AI video generation") + _charge(user_id, cost, "AI video generation") return requested, cost @@ -192,7 +177,7 @@ def _charge_audio(user_id: str, requested_model: str | None) -> tuple[str | None if is_desktop_local() or uses_user_platform_byok(user_id, requested): return requested, 0 cost = max(DEFAULT_IMAGE_CREDITS, int(DEFAULT_IMAGE_CREDITS or 1)) - _charge_image_credits(user_id, cost, "AI audio generation") + _charge(user_id, cost, "AI audio generation") return requested, cost @@ -210,7 +195,7 @@ def get_models( platforms_payload = list_byok_platforms() # Local desktop: no platform catalog (even if machine .env has provider keys). - # End users add OpenAI-compatible BYOK in Agent settings; FE merges vault models. + # End users add OpenAI-style BYOK in Agent settings; FE merges vault models. if is_desktop_local(): return { "models": [], @@ -221,7 +206,6 @@ def get_models( "clientRegion": "local", "openrouterAvailable": False, "byokPlatforms": platforms_payload, - "byokPresets": platforms_payload, } from app.services.geoip import ( @@ -258,7 +242,6 @@ def get_models( "clientRegion": country, "openrouterAvailable": or_ok, "byokPlatforms": platforms_payload, - "byokPresets": platforms_payload, } @router.post("/message") diff --git a/apps/api/app/api/routes/image_tools.py b/apps/api/app/api/routes/image_tools.py index 63696f2e..ad0a7555 100644 --- a/apps/api/app/api/routes/image_tools.py +++ b/apps/api/app/api/routes/image_tools.py @@ -15,7 +15,7 @@ uses_llm_for_kind, ) from app.services.wallet.billing import DEFAULT_IMAGE_CREDITS, image_model_credit_cost -from app.services.wallet.db import is_wallet_billing_enabled, spend_image_credits +from app.services.wallet.db import is_wallet_billing_enabled, spend_tokens router = APIRouter(prefix="/image", tags=["image-tools"]) @@ -31,7 +31,7 @@ "detectRegions": 0, "replaceText": 30, "vector": 20, - "adjust": 0, # FE uses CSS filters; API adjust is legacy / unused + "adjust": 0, # FE uses CSS filters; API adjust is unused } @@ -49,10 +49,10 @@ def _charge(user_id: str, amount: int, detail: str) -> None: if amount <= 0 or not is_wallet_billing_enabled(): return try: - spend_image_credits(user_id, amount, detail) + spend_tokens(user_id, amount, detail) except ValueError as err: - if str(err) == "insufficient_image_credits": - raise HTTPException(status_code=402, detail="Insufficient tokens") from err + if str(err) == "insufficient_tokens": + raise HTTPException(status_code=402, detail="Insufficient credits") from err raise HTTPException(status_code=400, detail=str(err)) from err @@ -78,10 +78,6 @@ def token_cost_for_kind( return int(_KIND_CREDIT_COST.get(k, DEFAULT_IMAGE_CREDITS)) -# Back-compat alias for older callers. -credit_cost_for_kind = token_cost_for_kind - - @router.get("/tools") def list_image_tools() -> dict[str, Any]: kinds = sorted(IMAGE_PROCESS_KINDS) @@ -89,8 +85,6 @@ def list_image_tools() -> dict[str, Any]: return { "kinds": kinds, "tokens": costs, - # Legacy key — same map as tokens. - "credits": costs, } @@ -124,5 +118,5 @@ async def post_image_process( raise HTTPException(status_code=502, detail=msg) from err if isinstance(result, dict): - result = {**result, "tokens": cost, "credits": cost} + result = {**result, "tokens": cost} return result diff --git a/apps/api/app/api/routes/plaza.py b/apps/api/app/api/routes/plaza.py index a9e29a82..e9ca3d4f 100644 --- a/apps/api/app/api/routes/plaza.py +++ b/apps/api/app/api/routes/plaza.py @@ -110,7 +110,7 @@ def plaza_feed( ) -> dict[str, Any]: """ Public plaza feed (no login required). - tab=recommended|latest (following deprecated — use authorIds to filter by creator) + tab=recommended|latest (use authorIds to filter by creator) category=optional category filter (website|mobile|image|poster|video) authorIds=comma-separated user ids to filter works by creator. """ diff --git a/apps/api/app/core/config.py b/apps/api/app/core/config.py index 31857236..6e7f9424 100644 --- a/apps/api/app/core/config.py +++ b/apps/api/app/core/config.py @@ -161,12 +161,10 @@ class Settings(BaseSettings): agent_profile_id: str = "design.canvas" # Design Intelligence client (ADR 0017). local = BasicLocal; remote = HTTP provider. - # Prefer RECOMBYN_INTELLIGENCE_*; legacy INTELLIGENCE_* still accepted. intelligence_provider: str = Field( default="local", validation_alias=AliasChoices( "RECOMBYN_INTELLIGENCE_MODE", - "INTELLIGENCE_PROVIDER", "intelligence_provider", ), ) @@ -174,7 +172,6 @@ class Settings(BaseSettings): default="", validation_alias=AliasChoices( "RECOMBYN_INTELLIGENCE_URL", - "INTELLIGENCE_REMOTE_URL", "intelligence_remote_url", ), ) @@ -182,7 +179,6 @@ class Settings(BaseSettings): default="", validation_alias=AliasChoices( "RECOMBYN_INTELLIGENCE_API_KEY", - "INTELLIGENCE_REMOTE_API_KEY", "intelligence_remote_api_key", ), ) @@ -190,7 +186,6 @@ class Settings(BaseSettings): default=30.0, validation_alias=AliasChoices( "RECOMBYN_INTELLIGENCE_TIMEOUT_SEC", - "INTELLIGENCE_REMOTE_TIMEOUT_SEC", "intelligence_remote_timeout_sec", ), ) diff --git a/apps/api/app/crud.py b/apps/api/app/crud.py index f7eff1e9..e0d455b4 100644 --- a/apps/api/app/crud.py +++ b/apps/api/app/crud.py @@ -440,7 +440,6 @@ def ensure_user_balance_row( row = UserBalance( user_id=uid, tokens=int(starting_tokens), - image_credits=0, plan_id="free", plan_expires_at=None, updated_at=now, @@ -2419,7 +2418,7 @@ def list_decision_log_page( status: str | None = None, q: str | None = None, ) -> tuple[list[Any], int]: - """Light decision-log list using JSON extract (same SQL as legacy admin path).""" + """Light decision-log list using JSON extract.""" where = [ "meta_json IS NOT NULL", "TRIM(meta_json) != ''", diff --git a/apps/api/app/main.py b/apps/api/app/main.py index ffea541f..af733de3 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -65,7 +65,7 @@ def _configure_logging() -> None: pass for _name in ( "services.design.runtime.orchestrator", - "services.design.runtime.agent_controller", + "services.design.runtime.graph.build", "services.design.runtime.llm_step", "design.run_api", "design.llm_step", diff --git a/apps/api/app/models.py b/apps/api/app/models.py index 3f388780..58ecd429 100644 --- a/apps/api/app/models.py +++ b/apps/api/app/models.py @@ -194,7 +194,6 @@ class UserBalance(SQLModel, table=True): user_id: str = Field(primary_key=True, max_length=64) tokens: int = Field(default=0) - image_credits: int = Field(default=0) plan_id: str = Field(default="free", max_length=16) plan_expires_at: Optional[float] = Field(default=None) updated_at: float = Field(default=0.0) @@ -297,7 +296,7 @@ class CardKey(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) key_hash: str = Field(index=True, unique=True, max_length=128) tokens: int = 0 - kind: str = Field(default="token", max_length=16) + kind: str = Field(default="credit", max_length=16) plan_id: Optional[str] = Field(default=None, max_length=16) status: str = Field(default="unused", max_length=16) expires_at: Optional[float] = Field(default=None) diff --git a/apps/api/app/services/agent_memory/kg.py b/apps/api/app/services/agent_memory/kg.py index c919aa32..57854751 100644 --- a/apps/api/app/services/agent_memory/kg.py +++ b/apps/api/app/services/agent_memory/kg.py @@ -217,10 +217,6 @@ def extract_factual_triples_from_episode( return _dedupe_triples(triples)[:24] -# Back-compat alias for callers / tests. -extract_triples_from_episode = extract_factual_triples_from_episode - - def _dedupe_triples( triples: list[tuple[str, str, str]], ) -> list[tuple[str, str, str]]: diff --git a/apps/api/app/services/agent_memory/long_term.py b/apps/api/app/services/agent_memory/long_term.py index a34453d5..9de8cea5 100644 --- a/apps/api/app/services/agent_memory/long_term.py +++ b/apps/api/app/services/agent_memory/long_term.py @@ -1,30 +1,16 @@ -"""Long-term user memory — LangGraph Store (docs) + legacy MySQL table bridge.""" +"""Long-term user memory backed by LangGraph Store.""" from __future__ import annotations import logging import threading -import time import uuid from dataclasses import dataclass from pathlib import Path from typing import Any from langchain.tools import ToolRuntime, tool -from sqlmodel import Session - -from app import crud -from app.core.db import engine -from app.models import AgentLongMemory -from app.services.agent_memory.text_embed import ( - cosine, - get_text_embeddings, - pack_vec, - retrieve_mode, - schedule_background, - unpack_vec, -) -from app.services.db import init_schema +from app.services.agent_memory.text_embed import get_text_embeddings logger = logging.getLogger(__name__) @@ -379,50 +365,6 @@ def run_long_term_tool_call( return f"Unknown long-term tool: {name}" -def embed_long_memory(memory_id: str) -> bool: - mid = (memory_id or "").strip() - if not mid: - return False - try: - init_schema() - with Session(engine) as session: - row = crud.get_agent_long_memory(session=session, memory_id=mid) - if not row: - return False - vec = get_text_embeddings().embed_query_raw(str(row.text or "")) - if vec is None: - crud.update_agent_long_memory_embed( - session=session, - memory_id=mid, - embed_status="failed", - updated_at=time.time(), - ) - return False - from app.services.agent_memory.clip_encoder import EMB_DIM, MODEL_ID - - crud.update_agent_long_memory_embed( - session=session, - memory_id=mid, - emb=pack_vec(vec), - emb_dim=int(EMB_DIM), - emb_model=MODEL_ID, - embed_status="ready", - score=1.0, - updated_at=time.time(), - ) - return True - except Exception: - logger.exception("embed_long_memory failed id=%s", mid) - return False - - -def schedule_embed_long_memory(memory_id: str) -> None: - mid = (memory_id or "").strip() - if not mid: - return - schedule_background(f"long-embed-{mid[:12]}", lambda: embed_long_memory(mid)) - - def list_long_hits( user_id: str, *, @@ -438,114 +380,7 @@ def list_long_hits( if not uid: return [] - # Official LangGraph Store first (cross-thread long-term memory). - store_hits = search_long_term_store(uid, query=query or "", limit=k) - if len(store_hits) >= k: - return store_hits[:k] - - init_schema() - mode = retrieve_mode(rules, "memory.long.retrieve", "embedding") - legacy: list[dict[str, Any]] = [] - if mode == "embedding" and (query or "").strip(): - got = _list_long_by_embedding(uid, query.strip(), k) - if got is not None: - legacy = got - if not legacy: - legacy = _list_long_recency(uid, k) - - # Prefer store docs, then fill from legacy table (dedupe by text). - seen = {str(h.get("text") or "") for h in store_hits} - out = list(store_hits) - for h in legacy: - t = str(h.get("text") or "") - if not t or t in seen: - continue - seen.add(t) - out.append(h) - if len(out) >= k: - break - return out[:k] - - -def _list_long_recency(uid: str, k: int) -> list[dict[str, Any]]: - with Session(engine) as session: - rows = crud.list_agent_long_memory_recent( - session=session, user_id=uid, limit=k - ) - out: list[dict[str, Any]] = [] - for r in rows: - text = str(r.text or "").strip() - if not text: - continue - out.append( - { - "kind": str(r.kind or "preference"), - "text": text[:500], - "score": float(r.score) if r.score is not None else None, - "retrieve": "recency", - } - ) - return out - - -def _list_long_by_embedding( - uid: str, query: str, k: int -) -> list[dict[str, Any]] | None: - qvec = get_text_embeddings().embed_query_raw(query) - if qvec is None: - return None - with Session(engine) as session: - # Pinned always preferred; then rank ready embeddings. - rows = crud.list_agent_long_memory_recent( - session=session, user_id=uid, limit=200 - ) - - pinned: list[dict[str, Any]] = [] - scored: list[tuple[float, Any]] = [] - pending: list[str] = [] - for r in rows: - text = str(r.text or "").strip() - if not text: - continue - if int(r.pinned or 0): - pinned.append( - { - "kind": str(r.kind or "preference"), - "text": text[:500], - "score": 1.0, - "retrieve": "pinned", - } - ) - continue - status = str(r.embed_status or "") - vec = unpack_vec(r.emb) if status == "ready" else None - if vec is None: - if status in ("pending", "", "failed"): - pending.append(str(r.id or "")) - continue - scored.append((cosine(qvec, vec), r)) - - for mid in pending[:3]: - schedule_embed_long_memory(mid) - - if not scored and not pinned: - return None - - scored.sort(key=lambda x: -x[0]) - out = list(pinned[:k]) - for sim, r in scored: - if len(out) >= k: - break - text = str(r.text or "").strip() - out.append( - { - "kind": str(r.kind or "preference"), - "text": text[:500], - "score": round(float(sim), 4), - "retrieve": "embedding", - } - ) - return out + return search_long_term_store(uid, query=query or "", limit=k) def insert_long_memory( @@ -555,39 +390,11 @@ def insert_long_memory( text: str, pinned: bool = False, ) -> str: - init_schema() mid = f"alm_{uuid.uuid4().hex[:16]}" - now = time.time() uid = (user_id or "").strip() body = (text or "")[:2000] kind_s = (kind or "preference")[:32] - with Session(engine) as session: - crud.insert_agent_long_memory( - session=session, - row=AgentLongMemory( - id=mid, - user_id=uid, - kind=kind_s, - text=body, - status="active", - pinned=1 if pinned else 0, - score=1.0, - emb=None, - emb_dim=0, - emb_model="", - embed_status="pending", - created_at=now, - updated_at=now, - ), - ) - schedule_embed_long_memory(mid) - # Official Store mirror (docs long-term memory). - try: - put_long_term_store( - uid, key=mid, kind=kind_s, text=body, pinned=pinned - ) - except Exception: - logger.warning("Store put failed for %s", mid, exc_info=True) + put_long_term_store(uid, key=mid, kind=kind_s, text=body, pinned=pinned) return mid @@ -602,19 +409,7 @@ def load_user_design_memory(user_id: str) -> dict[str, Any]: if not uid: return empty_design_memory()["user"] try: - init_schema() - with Session(engine) as session: - rows = crud.list_agent_long_memory_recent( - session=session, user_id=uid, limit=40 - ) - hits = [ - { - "kind": str(r.kind or "preference"), - "text": str(r.text or "").strip(), - "score": float(r.score) if r.score is not None else None, - } - for r in rows - ] + hits = search_long_term_store(uid, limit=40) return user_design_from_long_hits(hits) except Exception: logger.debug("load_user_design_memory failed user=%s", uid[:12], exc_info=True) diff --git a/apps/api/app/services/assets.py b/apps/api/app/services/assets.py index 5d264abb..42383a35 100644 --- a/apps/api/app/services/assets.py +++ b/apps/api/app/services/assets.py @@ -80,18 +80,13 @@ def _image_data_url(data: bytes, mime: str) -> str: def _normalize_asset_url(url: str | None, object_key: str | None) -> str: - """Rewrite legacy bare storage keys so FE can hydrate via /uploads/files.""" + """Normalize storage URL fields for FE.""" raw = (url or "").strip() key = (object_key or "").replace("\\", "/").lstrip("/") if not raw and key: return _display_url(key) if raw.startswith(("http://", "https://", "data:", "/")): return raw - # Local storage.url_for used to return the bare key (assets/…, uploads/…). - if key and (raw == key or raw.startswith(("assets/", "uploads/", "projects/", "font-tasks/"))): - return _display_url(key) - if raw.startswith(("assets/", "uploads/", "projects/", "font-tasks/")): - return _display_url(raw) return raw diff --git a/apps/api/app/services/auth/email_store.py b/apps/api/app/services/auth/email_store.py index f6e08ee1..89b09033 100644 --- a/apps/api/app/services/auth/email_store.py +++ b/apps/api/app/services/auth/email_store.py @@ -595,7 +595,7 @@ def _maybe_delete_avatar_object(url: str | None) -> None: def heal_avatar_if_data_url(user: EmailUser) -> EmailUser: - """One-shot migrate legacy base64 custom avatars out of the users table.""" + """One-shot move base64 custom avatars out of the users table.""" raw = (user.avatar_custom or user.avatar or "").strip() if not raw.startswith("data:image/"): return user diff --git a/apps/api/app/services/auth/orgs.py b/apps/api/app/services/auth/orgs.py index 93108896..5859c501 100644 --- a/apps/api/app/services/auth/orgs.py +++ b/apps/api/app/services/auth/orgs.py @@ -450,8 +450,3 @@ def remove_org_member(*, org_id: str, user_id: str, actor_user_id: str) -> dict[ session.delete(target) session.commit() return {"orgId": oid, "userId": uid, "removed": True} - - -# Back-compat alias used by older call sites / tests. -def invite_org_member(**kwargs: Any) -> dict[str, Any]: - return create_org_invite(**kwargs) diff --git a/apps/api/app/services/chat_store.py b/apps/api/app/services/chat_store.py index bf6d498d..59ba9e1a 100644 --- a/apps/api/app/services/chat_store.py +++ b/apps/api/app/services/chat_store.py @@ -42,13 +42,13 @@ def _pack_message_meta(m: dict[str, Any]) -> str | None: meta["contentMarked"] = content_marked # Normalize snake_case aliases once, then copy Ask/resume fields. aliases = { - "designTaskId": m.get("designTaskId") or m.get("design_task_id"), - "canResume": True if (m.get("canResume") is True or m.get("can_resume") is True) else None, - "proposedOps": m.get("proposedOps") or m.get("proposed_ops"), + "designTaskId": m.get("designTaskId"), + "canResume": True if m.get("canResume") is True else None, + "proposedOps": m.get("proposedOps"), "choices": m.get("choices"), - "applyChoice": m.get("applyChoice") or m.get("apply_choice"), - "choiceUi": m.get("choiceUi") or m.get("choice_ui"), - "proposalId": m.get("proposalId") or m.get("proposal_id"), + "applyChoice": m.get("applyChoice"), + "choiceUi": m.get("choiceUi"), + "proposalId": m.get("proposalId"), } _copy_ask_fields({k: v for k, v in aliases.items() if v is not None}, meta) if not meta: diff --git a/apps/api/app/services/db/__init__.py b/apps/api/app/services/db/__init__.py index 5dcedf57..40abdf76 100644 --- a/apps/api/app/services/db/__init__.py +++ b/apps/api/app/services/db/__init__.py @@ -621,7 +621,7 @@ def begin_write(conn: ConnectionWrapper) -> None: def init_schema() -> None: - """Ensure schema is at Alembic head (replaces legacy hand-written DDL).""" + """Ensure schema is at Alembic head.""" global _SCHEMA_READY with _LOCK: if _SCHEMA_READY: diff --git a/apps/api/app/services/design/admin/admin_store.py b/apps/api/app/services/design/admin/admin_store.py index 97cbedc5..4ed0dc8e 100644 --- a/apps/api/app/services/design/admin/admin_store.py +++ b/apps/api/app/services/design/admin/admin_store.py @@ -98,8 +98,7 @@ def upsert_skill(payload: dict[str, Any]) -> dict[str, Any]: NS_USER, SOURCE_ADMIN, SOURCE_FILE, - SOURCE_SEED, - _CORE_RESERVED_KEYS, + _CORE_RESERVED_KEYS, qualify_skill_key, save_skill_revision, split_namespace_key, @@ -191,10 +190,10 @@ def upsert_skill(payload: dict[str, Any]) -> dict[str, Any]: existing_ns = str(cur.namespace or "").strip().lower() # Editing seed/file: keep source + key + namespace (ops can customize body). # Seed sync is insert-only, so these edits are not reclaimed. - if existing_source in (SOURCE_SEED, SOURCE_FILE): + if existing_source != SOURCE_ADMIN: source = existing_source skill_key = existing_key or skill_key - namespace = existing_ns or (NS_CORE if existing_source == SOURCE_SEED else NS_EXT) + namespace = existing_ns or NS_EXT meta_source = existing_source else: source = SOURCE_ADMIN @@ -380,14 +379,14 @@ def soft_delete_skill(skill_id: int) -> bool: from app import crud from app.core.db import engine - from app.services.design.prompts.skill_store import SOURCE_FILE, SOURCE_SEED + from app.services.design.prompts.skill_store import SOURCE_FILE with Session(engine) as session: row = crud.get_design_skill(session=session, item_id=int(skill_id)) if not row: return False src = str(row.source or "").strip().lower() - if src in (SOURCE_SEED, SOURCE_FILE): + if src == SOURCE_FILE: raise ValueError("cannot delete seed/file skill via admin") session.delete(row) session.commit() @@ -437,7 +436,6 @@ def list_global_rules() -> list[dict[str, Any]]: with Session(engine) as session: rows = crud.list_all_design_global_rules(session=session) # Hide internal/ops markers from Admin table (still in DB when needed). - hide_prefixes = ("legacy.agent_zero_",) hide_exact = frozenset( { "content_pack_version", @@ -447,8 +445,7 @@ def list_global_rules() -> list[dict[str, Any]]: return [ _rule_row_out(r) for r in rows - if not str(getattr(r, "rule_key", None) or "").startswith(hide_prefixes) - and str(getattr(r, "rule_key", None) or "") not in hide_exact + if str(getattr(r, "rule_key", None) or "") not in hide_exact ] @@ -1715,7 +1712,7 @@ def _fix_mode_fork_edge( condition="mode=ask&ops_valid", priority=10, ) - # Drop legacy hydrate / dual_sample nodes; action owns hydrate. + # Drop hydrate / dual_sample nodes; action owns hydrate. _drop_phases = {"hydrate", "dual_sample"} if ids & _drop_phases: for e in edges: @@ -1989,7 +1986,7 @@ def _fix_mode_fork_edge( priority=9, ) - # Collapse legacy leaf model nodes (simple/medium/complex/vision/multimodal) + # 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", @@ -2071,7 +2068,7 @@ def _is_leaf_model(n: dict[str, Any]) -> bool: e["priority"] = 10 changed = True - # Collapse duplicate edge ids (legacy normalize could append same eid twice). + # Collapse duplicate edge ids (normalization could append same eid twice). seen_eids: set[str] = set() deduped_edges: list[dict[str, Any]] = [] for e in edges: @@ -2103,16 +2100,15 @@ def _load_flows_catalog() -> list[dict[str, Any]]: items = [] if items: return items - # Migrate legacy single graph into catalog. - legacy = get_agent_flow_config() + # Seed default flow catalog when KV is empty. seed = { "id": "default", "name": "默认 Agent 流程", "description": "当前线上 Design Agent 默认执行图(LangGraph runtime)", "updatedAt": int(time.time() * 1000), "createdAt": int(time.time() * 1000), - "graph": legacy.get("graph") or _empty_graph(), - "phaseMap": legacy.get("phaseMap") or dict(_load_default_agent_phase_map()), + "graph": _load_default_agent_flow_graph(), + "phaseMap": dict(_load_default_agent_phase_map()), } _save_flows_catalog([seed]) return [seed] @@ -2351,7 +2347,7 @@ def publish_agent_flow(flow_id: str, *, note: str = "") -> dict[str, Any] | None _save_flows_catalog(items) # Invalidate LangGraph cache if present try: - from app.services.design.runtime.agent_controller import invalidate_agent_graph_cache + from app.services.design.runtime.graph.build import invalidate_agent_graph_cache invalidate_agent_graph_cache(fid) except Exception: @@ -2419,7 +2415,7 @@ def update_agent_flow( if str(k).strip() and str(v).strip() } it["updatedAt"] = int(time.time() * 1000) - # Sync legacy default keys when editing default flow. + # Sync default flow keys when editing default flow. if fid == "default" and isinstance(it.get("graph"), dict): upsert_global_rule( rule_key=_AGENT_FLOW_RULE_KEY, @@ -3478,17 +3474,6 @@ def ensure_stage_rules() -> None: ) except Exception: pass - # Legacy wipe marker: insert only — never DELETE Admin rules/skills/flows. - try: - crud.insert_design_global_rule_if_missing( - session=session, - rule_key="legacy.agent_zero_v3", - rule_value=str(int(time.time())), - description="历史清空标记(已禁用实际清空,避免覆盖库内数据)", - updated_at=time.time(), - ) - except Exception: - pass session.commit() diff --git a/apps/api/app/services/design/admin/blob_codec.py b/apps/api/app/services/design/admin/blob_codec.py index 7df29dcc..3413d9df 100644 --- a/apps/api/app/services/design/admin/blob_codec.py +++ b/apps/api/app/services/design/admin/blob_codec.py @@ -1,6 +1,6 @@ """Compact binary helpers for design media + embedding BLOBs (MySQL LONGBLOB). -- Vectors: optional light zstd (fallback zlib); raw float32 still readable. +- Vectors: optional light zstd (fallback zlib). - Thumbs: webp quality≈70 for DB preview; originals stay on object storage. """ @@ -10,10 +10,9 @@ import zlib from typing import Any -# zstd frame if available; else zlib. Magic lets readers accept legacy raw float32. +# zstd frame if available; else zlib. _MAGIC_ZSTD = b"ZST1" _MAGIC_ZLIB = b"ZL1\0" -_MAGIC_RAW = b"" # bare float32 bytes (legacy) def _zstd_mod() -> Any | None: @@ -37,7 +36,7 @@ def pack_emb_blob(raw: bytes, *, level: int = 3) -> bytes: def unpack_emb_blob(blob: bytes | bytearray | memoryview | None) -> bytes: - """Decode packed embedding; pass through legacy raw float32.""" + """Decode packed embedding.""" if blob is None: return b"" data = bytes(blob) @@ -50,7 +49,7 @@ def unpack_emb_blob(blob: bytes | bytearray | memoryview | None) -> bytes: return zstd.ZstdDecompressor().decompress(data[len(_MAGIC_ZSTD) :]) if data.startswith(_MAGIC_ZLIB): return zlib.decompress(data[len(_MAGIC_ZLIB) :]) - return data + raise ValueError("Unknown embedding blob header") def pack_text_blob(text: str, *, level: int = 19) -> bytes: diff --git a/apps/api/app/services/design/admin/dict_store.py b/apps/api/app/services/design/admin/dict_store.py index 410664d7..941526ca 100644 --- a/apps/api/app/services/design/admin/dict_store.py +++ b/apps/api/app/services/design/admin/dict_store.py @@ -259,7 +259,6 @@ def _seed_dict_rows(session: Session, *, now: float) -> None: or_( DesignDict.enabled == 0, col(DesignDict.label).like("%废弃%"), - col(DesignDict.label).like("%deprecated%"), ) ) ).all() diff --git a/apps/api/app/services/design/admin/stage_review_store.py b/apps/api/app/services/design/admin/stage_review_store.py index 9f8f49ec..72b549af 100644 --- a/apps/api/app/services/design/admin/stage_review_store.py +++ b/apps/api/app/services/design/admin/stage_review_store.py @@ -1,4 +1,4 @@ -"""Admin stage-review persistence (legacy training ratings).""" +"""Admin stage-review persistence (historical training ratings).""" from __future__ import annotations diff --git a/apps/api/app/services/design/img_layers/pipeline.py b/apps/api/app/services/design/img_layers/pipeline.py index af17ae60..a5aa2439 100644 --- a/apps/api/app/services/design/img_layers/pipeline.py +++ b/apps/api/app/services/design/img_layers/pipeline.py @@ -55,7 +55,7 @@ async def run_img_layers_job( refund_hold_fn: Any, scene: str | None = None, ) -> AsyncIterator[dict[str, Any]]: - """SSE stream compatible with FE tool_ops apply + result settle.""" + """SSE stream used by FE tool_ops apply + result settle.""" task_id = str(uuid.uuid4()) trace_id = str(uuid.uuid4()) sid = str(session_id or "").strip() diff --git a/apps/api/app/services/design/intelligence_runtime.py b/apps/api/app/services/design/intelligence_runtime.py index 64ef2afe..414a8d7f 100644 --- a/apps/api/app/services/design/intelligence_runtime.py +++ b/apps/api/app/services/design/intelligence_runtime.py @@ -5,8 +5,7 @@ usable results are applied onto Runtime slots; failures fall back to BasicLocal. Do not document proprietary backends here. -Stable surface matches ``DesignIntelligenceClient`` (propose_candidates, -swarm_direction, govern, autonomous_plan, …). Legacy aliases remain on the Client. +Stable surface matches ``DesignIntelligenceClient`` canonical methods. """ from __future__ import annotations @@ -14,7 +13,6 @@ from typing import Any from recombyn_intelligence_client import DesignIntelligenceClient, RemoteIntelligenceProvider -from recombyn_protocol import INTELLIGENCE_METHOD_ALIASES from app.core.config import settings @@ -24,9 +22,8 @@ def _wire_method(name: str) -> str: - """Canonical HTTP path segment (aliases collapse to stable names).""" - key = str(name or "").strip() - return INTELLIGENCE_METHOD_ALIASES.get(key, key) + """Canonical HTTP path segment.""" + return str(name or "").strip() def apply_intelligence_result( @@ -292,23 +289,6 @@ async def write_principle(self, rt: Any) -> dict[str, Any] | None: """Principle / knowledge write-back. BasicLocal has no private KG writer.""" return None - # Legacy aliases for callers that still talk to the Provider directly. - async def candidates(self, rt: Any) -> dict[str, Any] | None: - return await self.propose_candidates(rt) - - async def swarm(self, rt: Any) -> dict[str, Any] | None: - return await self.swarm_direction(rt) - - async def gate_governance(self, rt: Any) -> dict[str, Any]: - return await self.govern(rt) - - async def plan_autonomous(self, rt: Any) -> dict[str, Any] | None: - return await self.autonomous_plan(rt) - - async def sync_autonomous(self, rt: Any) -> dict[str, Any] | None: - return await self.autonomous_sync(rt) - - def build_design_intelligence_client() -> DesignIntelligenceClient: @@ -406,7 +386,3 @@ def call_remote_billing( def quote_remote_task_credits(body: dict[str, Any]) -> dict[str, Any] | None: """Optional host credit quote — wire returns credits only.""" return call_remote_billing("POST", "/billing/quote", json_body=body) - - -# Back-compat alias. -quote_intelligence_task_credits = quote_remote_task_credits 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 c6baaedb..62c50202 100644 --- a/apps/api/app/services/design/ops/tool_ops_contract.py +++ b/apps/api/app/services/design/ops/tool_ops_contract.py @@ -334,65 +334,16 @@ def _max_ops_per_step(rules: dict[str, str] | None) -> int: return n -_OP_META_KEYS = frozenset( - { - "name", - "tool", - "type", - "op", - "args", - "parameters", - "arguments", - "properties", - "props", - "updates", - "params", - "op_id", - "opId", - } -) -# Nested bags accepted as args payload (models often use parameters from FC habit). -_OP_NEST_ARG_KEYS = ( - "args", - "parameters", - "arguments", - "properties", - "props", - "updates", - "params", -) - - def _coerce_op_args(item: dict[str, Any]) -> dict[str, Any]: - """Normalize op payload to ``args``; accept ``parameters`` / ``arguments`` too.""" - args: dict[str, Any] = {} - # Prefer explicit args, then parameters/arguments, then other legacy nests. - for nest_key in _OP_NEST_ARG_KEYS: - nested = item.get(nest_key) - if not isinstance(nested, dict): - continue - for nk, nv in nested.items(): - args.setdefault(nk, nv) - if not args: - args = {k: v for k, v in item.items() if k not in _OP_META_KEYS} + """Normalize one tool_op to an ``args`` dict.""" + nested = item.get("args") + if isinstance(nested, dict): + args = dict(nested) else: - # Flat sibling fields fill gaps (e.g. name + top-level x). - for k, v in item.items(): - if k not in _OP_META_KEYS: - args.setdefault(k, v) - op_id = item.get("op_id") or item.get("opId") + 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] - if not args.get("nodeId"): - nid = ( - args.get("id") - or item.get("id") - or item.get("nodeId") - or item.get("node_id") - ) - if nid is not None and str(nid).strip(): - args["nodeId"] = str(nid).strip() - args.pop("id", None) return args @@ -404,26 +355,16 @@ def _parse_raw_ops(content: str | dict[str, Any] | list[Any] | None) -> list[dic data = extract_json(content or "") ops_raw: list[Any] = [] if isinstance(data, dict): - cand = data.get("ops") or data.get("tools") or data.get("actions") + cand = data.get("tool_ops") if isinstance(cand, list): ops_raw = cand - else: - type_name = str(data.get("type") or data.get("op") or "").strip() - if data.get("name") or data.get("tool") or type_name in allowed_canvas_tool_keys(): - ops_raw = [data] elif isinstance(data, list): ops_raw = data out: list[dict[str, Any]] = [] for item in ops_raw: if not isinstance(item, dict): continue - name = _canonicalize_op_name( - item.get("name") - or item.get("tool") - or item.get("type") - or item.get("op") - or "" - ) + name = _canonicalize_op_name(item.get("name") or "") if not name: continue out.append({"name": name, "args": _coerce_op_args(item)}) @@ -443,11 +384,7 @@ def _stable_op_id(name: str, args: dict[str, Any], index: int) -> str: def _lottie_animation_raw(args: dict[str, Any]) -> Any: - """First present animation payload among common create_lottie aliases.""" - for key in ("animationData", "lottie", "json", "animation"): - if args.get(key) is not None: - return args.get(key) - return None + return args.get("animationData") def _validate_single_op( @@ -464,7 +401,7 @@ def _validate_single_op( detail=f"name={name}", ) if name == "update_node": - nid = str(args.get("nodeId") or args.get("id") or "").strip() + nid = str(args.get("nodeId") or "").strip() if not nid: return format_op_error( "update_node_missing_nodeId", @@ -481,7 +418,6 @@ def _validate_single_op( return fill_err return None if name == "delete_nodes": - args = _normalize_node_id_list_args(args) ids = args.get("nodeIds") if not isinstance(ids, list) or not [x for x in ids if str(x).strip()]: return format_op_error( @@ -499,7 +435,7 @@ def _validate_single_op( ) return None if name == "delete_frame": - fid = str(args.get("frameId") or args.get("id") or "").strip() + fid = str(args.get("frameId") or "").strip() if not fid: return format_op_error( "delete_frame_missing_frameId", @@ -513,7 +449,7 @@ def _validate_single_op( ) return None if name == "create_svg" or name == "create_icon": - svg = str(args.get("svg") or args.get("iconSvg") or args.get("content") or "").strip() + svg = str(args.get("svg") or "").strip() if not svg: return format_op_error( f"{name}_missing_svg", @@ -530,12 +466,12 @@ def _validate_single_op( ) return None if name == "create_shape": - if args.get("shapeType") is None and args.get("type") is None: + if args.get("shapeType") is None: return format_op_error( "create_shape_missing_shapeType", fix="re-emit create_shape with args.shapeType (rect|ellipse|…)", ) - svg = str(args.get("svg") or args.get("iconSvg") or "").strip() + svg = str(args.get("svg") or "").strip() if svg: from app.services.design.ops.validate import validate_agent_svg_markup @@ -556,13 +492,13 @@ def _validate_single_op( return fill_err return None if name == "create_text": - if args.get("text") is None and args.get("content") is None: + if args.get("text") is None: if args.get("x") is None or args.get("y") is None: return format_op_error( "create_text_missing_text_or_position", fix="re-emit create_text with args.text and x/y", ) - text_s = str(args.get("text") if args.get("text") is not None else args.get("content") or "") + text_s = str(args.get("text") or "") if _EMOJI_AS_ICON_RE.search(text_s): stripped = _EMOJI_AS_ICON_RE.sub("", text_s).strip() # Short / emoji-only labels are marks — use create_icon / create_svg. @@ -576,7 +512,7 @@ def _validate_single_op( if name == "create_image": has_attach = args.get("attachmentIndex") is not None has_url = bool(str(args.get("src") or args.get("url") or "").strip()) - has_gen = bool(str(args.get("genPrompt") or args.get("prompt") or "").strip()) + has_gen = bool(str(args.get("genPrompt") or "").strip()) if not has_attach and not has_url and not has_gen: return format_op_error( "create_image_missing_source", @@ -584,7 +520,7 @@ def _validate_single_op( ) return None if name == "create_lottie": - has_gen = bool(str(args.get("genPrompt") or args.get("prompt") or "").strip()) + has_gen = bool(str(args.get("genPrompt") or "").strip()) raw = _lottie_animation_raw(args) has_data = False if isinstance(raw, dict) and raw.get("layers"): @@ -600,45 +536,7 @@ def _validate_single_op( return None -def _normalize_update_node_args(args: dict[str, Any]) -> dict[str, Any]: - """Backend-owned update_node hygiene before FE executes. - - - Map ``color`` → ``fill`` when fill is absent (shape/text recolor alias). - - Map inventory ``w``/``h`` → ``width``/``height`` when those are absent. - Keep all other fields as-is — no paint-vs-geometry filtering; FE patches - only keys present in args. - """ - out = dict(args) - if out.get("fill") is None and out.get("fillColor") is None and out.get("backgroundColor") is None: - color = out.get("color") - if color is not None and str(color).strip(): - out["fill"] = color - if out.get("width") is None and out.get("w") is not None: - out["width"] = out.get("w") - if out.get("height") is None and out.get("h") is not None: - out["height"] = out.get("h") - if out.get("shapeType") is None and out.get("type") is not None: - out["shapeType"] = out.get("type") - return out - - -def _normalize_node_id_list_args(args: dict[str, Any]) -> dict[str, Any]: - """Accept node_ids / ids aliases → nodeIds (models often emit snake_case).""" - out = dict(args) - if out.get("nodeIds") is None: - for alt in ("node_ids", "ids", "nodeIdList"): - raw = out.get(alt) - if isinstance(raw, list): - out["nodeIds"] = raw - break - if isinstance(raw, str) and raw.strip(): - out["nodeIds"] = [raw.strip()] - break - return out - - def _collect_delete_node_ids(args: dict[str, Any]) -> list[str]: - args = _normalize_node_id_list_args(args) ids = args.get("nodeIds") if not isinstance(ids, list): return [] @@ -706,8 +604,6 @@ def _reject_shape_morph_ops( create = ops[create_idxs[0]] cargs = create.get("args") if isinstance(create.get("args"), dict) else {} shape_type = cargs.get("shapeType") - if shape_type is None: - shape_type = cargs.get("type") if shape_type is None or not str(shape_type).strip(): return ops, [] drop = {delete_idxs[0], create_idxs[0]} @@ -750,7 +646,7 @@ def _reject_create_text_as_edit( if name != "create_text": kept.append(raw) continue - text = str(args.get("text") or args.get("content") or "") + text = str(args.get("text") or "") match = _find_matching_text_node(scene_nodes, text, used_text_ids) if not match: kept.append(raw) @@ -812,7 +708,7 @@ def _reject_ambient_mutates_on_new_design( name = str(raw.get("name") or "").strip() args = raw.get("args") if isinstance(raw.get("args"), dict) else {} if name == "update_node": - nid = str(args.get("nodeId") or args.get("id") or "").strip() + nid = str(args.get("nodeId") or "").strip() if nid and nid in scene_ids: errors.append( format_op_error( @@ -840,7 +736,7 @@ def _reject_ambient_mutates_on_new_design( ) continue if name == "delete_nodes": - ids = args.get("nodeIds") or args.get("ids") or [] + ids = args.get("nodeIds") or [] if not isinstance(ids, list): ids = [ids] if ids else [] hit = [str(x).strip() for x in ids if str(x).strip() in scene_ids] @@ -858,9 +754,7 @@ def _reject_ambient_mutates_on_new_design( ) continue if name == "delete_frame": - fid = str( - args.get("frameId") or args.get("id") or args.get("frame_id") or "" - ).strip() + fid = str(args.get("frameId") or "").strip() if fid and fid in frame_ids: errors.append( format_op_error( @@ -974,7 +868,6 @@ def normalize_agent_tool_ops( ) continue name = str(item.get("name") or "").strip() - # Accept args / parameters / arguments; normalize to args for FE. args = _coerce_op_args(item) if not name: errors.append( @@ -984,27 +877,6 @@ def normalize_agent_tool_ops( ) ) continue - # Alias normalize (shape type / text content) — keep below in original loop body - if name == "create_shape": - if args.get("shapeType") is None and args.get("type") is not None: - args["shapeType"] = args.get("type") - if name == "create_text": - if args.get("text") is None and args.get("content") is not None: - args["text"] = args.get("content") - if name in ( - "delete_nodes", - "align_nodes", - "distribute_nodes", - "reorder_nodes", - "group_nodes", - "ungroup_nodes", - "duplicate_nodes", - "flip_nodes", - "boolean_op", - ): - args = _normalize_node_id_list_args(args) - if name == "update_node": - args = _normalize_update_node_args(args) working.append({"name": name, "args": args}) # Validate intent — reject, do not rewrite into a "fixed" op. @@ -1053,7 +925,7 @@ def normalize_agent_tool_ops( continue a = op.get("args") or {} key = ( - f"{a.get('nodeId')}:{a.get('fill') or a.get('fillColor') or ''}:" + f"{a.get('nodeId')}:{a.get('fill') or ''}:" f"{a.get('cornerRadius') or ''}:{a.get('text') or ''}" ) if key in seen_updates: @@ -1092,10 +964,10 @@ def extract_and_validate_tool_ops( def _find_ops_array_body(text: str) -> str | None: - """Return the inside of \"ops\":[ ... ] (may be incomplete).""" + """Return the inside of ``\"tool_ops\":[ ... ]`` (may be incomplete).""" if not text: return None - m = re.search(r'"ops"\s*:\s*\[', text) + m = re.search(r'"tool_ops"\s*:\s*\[', text) if not m: return None return text[m.end() :] @@ -1211,11 +1083,11 @@ def tool_ops_batch_detail(batch: list[dict[str, Any]], *, limit: int = 10) -> st name = str(op.get("name") or "").strip() args = op.get("args") if isinstance(op.get("args"), dict) else {} if name == "create_shape": - st = str(args.get("shapeType") or args.get("type") or "shape").strip() or "shape" + st = str(args.get("shapeType") or "shape").strip() or "shape" fill = str(args.get("fill") or "").strip() parts.append(f"+{st}" + (f" ({fill})" if fill else "")) elif name == "create_text": - t = str(args.get("text") or args.get("content") or "").replace("\n", " ").strip() + t = str(args.get("text") or "").replace("\n", " ").strip() parts.append(f'+text "{t[:20]}"' if t else "+text") elif name == "create_image": parts.append("+image") @@ -1334,7 +1206,7 @@ def tool_ops_for_sse(ops: list[dict[str, Any]]) -> list[dict[str, Any]]: path = str(args.get("path") or "") logger.info( "[tool_ops path diag] type=%s xy=%s,%s size=%sx%s fill=%s pathLen=%s head=%s", - args.get("shapeType") or args.get("type"), + args.get("shapeType"), args.get("x"), args.get("y"), args.get("width"), @@ -1563,17 +1435,14 @@ def assess_tool_ops_result( name = str(o.get("name") or "").strip() args = o.get("args") if isinstance(o.get("args"), dict) else {} if name in create_names: - cid = str(args.get("id") or args.get("nodeId") or "").strip() + cid = str(args.get("nodeId") or "").strip() if cid: living_ids.add(cid) elif name != "create_frame": # Anonymous create still counts toward projected density. living_ids.add(f"__anon_{len(living_ids)}") - if name in ("delete_node", "remove_node", "delete_nodes"): - rid = str(args.get("id") or args.get("nodeId") or "").strip() - if rid: - living_ids.discard(rid) - for x in args.get("ids") or args.get("nodeIds") or []: + if name == "delete_nodes": + for x in args.get("nodeIds") or []: living_ids.discard(str(x or "").strip()) if len(living_ids) < max(1, min_creates // 2): return False, f"sparse_tool_ops:scene_too_thin:{len(living_ids)}" 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 6f43ea4e..0e392769 100644 --- a/apps/api/app/services/design/prompts/prompt_pack_store.py +++ b/apps/api/app/services/design/prompts/prompt_pack_store.py @@ -76,7 +76,7 @@ def _parse_pack_index(parsed: dict[str, Any]) -> tuple[dict[str, str], list[dict def _attach_bodies_from_dir( root: Path, items: list[dict[str, Any]] ) -> list[dict[str, Any]]: - """Load bodies from ``item.file`` section files, or legacy ``.md``.""" + """Load bodies from ``item.file`` section files.""" section_cache: dict[str, dict[str, str]] = {} out: list[dict[str, Any]] = [] @@ -101,14 +101,6 @@ def sections_for(rel: str) -> dict[str, str]: rel = _safe_seed_relpath(str(item.get("file") or "")) if rel: body = sections_for(rel).get(kind) or "" - if not body: - # Legacy: one file per kind at pack root. - body_path = root / f"{kind}.md" - if body_path.is_file(): - try: - body = body_path.read_text(encoding="utf-8") - except Exception: - body = "" merged = dict(item) merged["kind"] = kind merged["body"] = body @@ -117,7 +109,7 @@ def sections_for(rel: str) -> dict[str, str]: def _load_prompt_packs_seed() -> tuple[dict[str, str], list[dict[str, Any]]]: - """Prefer ``design_prompt_packs/_index.json`` + staged md; legacy monolith JSON fallback.""" + """Load ``design_prompt_packs/_index.json`` + staged markdown bodies.""" root = resolve_seed_dir("design_prompt_packs") index_path = root / "_index.json" if index_path.is_file(): @@ -129,14 +121,7 @@ def _load_prompt_packs_seed() -> tuple[dict[str, str], list[dict[str, Any]]]: labels, items = _parse_pack_index(parsed) return labels, _attach_bodies_from_dir(root, items) - legacy = resolve_seed_file("design_prompt_packs_seed.json") - try: - parsed = json.loads(legacy.read_text(encoding="utf-8")) - except Exception: - return {}, [] - if not isinstance(parsed, dict): - return {}, [] - return _parse_pack_index(parsed) + return {}, [] KIND_LABELS, _SEED = _load_prompt_packs_seed() @@ -149,7 +134,7 @@ def _load_prompt_packs_seed() -> tuple[dict[str, str], list[dict[str, Any]]]: def db_prompt_body(key: str) -> str: - """Enabled body from ``design_prompt_pack`` (then legacy ``design_system_prompt``). No seed.""" + """Enabled body from ``design_prompt_pack``. No seed fallback.""" kind = str(key or "").strip() if not kind: return "" @@ -157,17 +142,7 @@ def db_prompt_body(key: str) -> str: body = crud.get_design_prompt_pack_body(session=session, kind=kind) if body: return body - try: - from app.services.design.prompts.system_prompt_store import is_system_prompt_key - - if not is_system_prompt_key(kind): - return "" - row = crud.get_design_system_prompt(session=session, prompt_key=kind) - if not row or not int(row.enabled or 0): - return "" - return str(row.body or "").strip() - except Exception: - return "" + return "" def seed_prompt_body(key: str) -> str: @@ -352,7 +327,6 @@ def list_prompt_nodes_from_flow(*, graph: dict[str, Any] | None = None) -> list[ "resources", "precheck", "persona", - "legacy", ) _PROMPT_PACK_STAGES = frozenset(PROMPT_PACK_STAGES) @@ -430,11 +404,9 @@ def is_need_prompt_kind(kind: str) -> bool: def is_need_pack(row: dict[str, Any]) -> bool: - """Prefer pack ``type`` code; fall back to legacy kind allowlist.""" + """Need pack is determined by pack ``type`` code.""" t = str(row.get("type") or row.get("pack_type") or "").strip().lower() - if t: - return t == PACK_TYPE_NEED - return is_need_prompt_kind(str(row.get("kind") or "")) + return t == PACK_TYPE_NEED def _pub(r: Any) -> dict[str, Any]: @@ -450,10 +422,6 @@ def _get(key: str, default: Any = None) -> Any: raw_type = str(_get("pack_type") or "") pack_type = normalize_pack_type(raw_type, kind=kind) raw_used = str(_get("used_by") or "") - # Fall back to seed metadata when DB column empty. - if not raw_used.strip(): - seed_item = _SEED_BY_KIND.get(kind) or {} - raw_used = seed_item.get("usedBy") or seed_item.get("used_by") or "" used_by = normalize_used_by(raw_used) updated = _get("updated_at") return { @@ -669,7 +637,7 @@ def _apply_seed_fields_to_row(row: Any, seed_item: dict[str, Any], *, kind: str, def ensure_design_prompt_packs() -> None: - """Upsert packs from ``seeds/design_prompt_packs/``; prune junk; migrate legacy. + """Upsert packs from ``seeds/design_prompt_packs/`` and prune junk. Git seed is source of truth for body / title / when / scenes / used_by / pack_type / sort_order. Admin UI edits are overwritten on the next ensure (API boot). diff --git a/apps/api/app/services/design/prompts/skill_store/__init__.py b/apps/api/app/services/design/prompts/skill_store/__init__.py index 6066306a..43c35e50 100644 --- a/apps/api/app/services/design/prompts/skill_store/__init__.py +++ b/apps/api/app/services/design/prompts/skill_store/__init__.py @@ -1,7 +1,7 @@ """Runtime skills for lc_design — pluggable catalog + need_skills + triggers + files. Namespaces (conflict isolation): - - core — legacy SOURCE_SEED only (no longer shipped); bare keys stay BC aliases + - core — reserved namespace; only file-pack keys in NS_CORE (no DB seed source) - ext — file packs under ``skills/foundation|domains`` + ``plugins/skills`` (source=file) - user — admin / user-extension skills (source=admin); keys use ``user.`` @@ -21,7 +21,6 @@ NS_USER, SOURCE_ADMIN, SOURCE_FILE, - SOURCE_SEED, _ALWAYS_ALLOW_OPS, _INTERNAL_RESOURCE_KINDS, _MAX_USER_SKILL_ZIP_BYTES, @@ -30,7 +29,6 @@ _NS_KEY_RE, _PIN_RE, _PROTECTED_FROM_FILE, - _PROTECTED_FROM_SEED, _SKILL_MD_NAMES, _SLUG_RE, _SOURCE_TO_NS, @@ -155,7 +153,6 @@ __all__ = [ # constants - "SOURCE_SEED", "SOURCE_ADMIN", "SOURCE_FILE", "NS_CORE", @@ -163,7 +160,6 @@ "NS_USER", "MAX_SKILL_DETAIL_CHARS", "_ALWAYS_ALLOW_OPS", - "_PROTECTED_FROM_SEED", "_PROTECTED_FROM_FILE", "_VALID_NAMESPACES", "_SOURCE_TO_NS", diff --git a/apps/api/app/services/design/prompts/skill_store/constants.py b/apps/api/app/services/design/prompts/skill_store/constants.py index fae18974..b3bfee9d 100644 --- a/apps/api/app/services/design/prompts/skill_store/constants.py +++ b/apps/api/app/services/design/prompts/skill_store/constants.py @@ -11,18 +11,15 @@ _HOT_RELOAD_THREAD: threading.Thread | None = None _DISK_SIGNATURE: str | None = None -SOURCE_SEED = "seed" SOURCE_ADMIN = "admin" SOURCE_FILE = "file" -_PROTECTED_FROM_SEED = frozenset({SOURCE_ADMIN, SOURCE_FILE}) -_PROTECTED_FROM_FILE = frozenset({SOURCE_ADMIN, SOURCE_SEED}) +_PROTECTED_FROM_FILE = frozenset({SOURCE_ADMIN}) NS_CORE = "core" NS_EXT = "ext" NS_USER = "user" _VALID_NAMESPACES = frozenset({NS_CORE, NS_EXT, NS_USER}) _SOURCE_TO_NS = { - SOURCE_SEED: NS_CORE, SOURCE_FILE: NS_EXT, SOURCE_ADMIN: NS_USER, } @@ -57,8 +54,6 @@ "brand": 1, "craft": 2, "surface": 3, - "deliverable": 3, # legacy alias for surface - "ui": 3, # legacy alias for surface "image": 2, # helper craft (image_gen), not a competing surface "qa": 4, "agent": 5, diff --git a/apps/api/app/services/design/prompts/skill_store/ensure.py b/apps/api/app/services/design/prompts/skill_store/ensure.py index ee8ec70d..65c18d6d 100644 --- a/apps/api/app/services/design/prompts/skill_store/ensure.py +++ b/apps/api/app/services/design/prompts/skill_store/ensure.py @@ -16,7 +16,6 @@ from .constants import ( SOURCE_ADMIN, SOURCE_FILE, - SOURCE_SEED, _DISK_SIGNATURE, _HOT_RELOAD_STOP, _HOT_RELOAD_THREAD, @@ -152,7 +151,7 @@ def _allowed_resources_json(item: dict[str, Any], *, source: str) -> str | None: if parsed is None: if source == SOURCE_ADMIN: return json.dumps(["tools"], ensure_ascii=False) - if source in (SOURCE_SEED, SOURCE_FILE): + if source == SOURCE_FILE: return json.dumps( ["tools"], ensure_ascii=False ) @@ -218,9 +217,6 @@ def _upsert_owned_skill( next_ver = version if row: src = _normalize_source(_row_get(row, "source"), default=source) - # SOURCE_SEED is legacy-only; never upsert from that source path. - if source == SOURCE_SEED: - return if src in skip_sources: return try: @@ -229,7 +225,7 @@ def _upsert_owned_skill( cur_ver = 0 next_ver = ( max(version, cur_ver + 1) - if source in (SOURCE_SEED, SOURCE_FILE) + if source == SOURCE_FILE else max(version, 1) ) skill_id = int(row.id or 0) or None @@ -358,20 +354,6 @@ def _skills_disk_signature() -> str: parts.append(f"{root.name}/{pack.name}:err") return "|".join(parts) -def _prune_legacy_seed_skills(session: Session) -> None: - """Drop leftover SOURCE_SEED rows — playbooks live under ``skills/`` file packs.""" - from sqlmodel import select - - from app.models import DesignSkill - - for row in session.exec(select(DesignSkill)).all(): - key = str(_row_get(row, "skill_key") or "").strip() - src = _normalize_source(_row_get(row, "source"), default=SOURCE_SEED) - if src != SOURCE_SEED or not key: - continue - session.delete(row) - logger.info("pruned legacy seed skill %s (file packs only)", key) - def _prune_missing_file_skills( session: Session, *, file_keys: set[str] @@ -412,7 +394,6 @@ def ensure_design_skills(*, force: bool = False) -> None: if str(it.get("skill_key") or "").strip() } with Session(core_db.engine) as session: - _prune_legacy_seed_skills(session) _prune_missing_file_skills(session, file_keys=file_keys) _purge_system_skill_denylist(session) for item in file_items: diff --git a/apps/api/app/services/design/prompts/skill_store/keys.py b/apps/api/app/services/design/prompts/skill_store/keys.py index d1901c00..fc71d618 100644 --- a/apps/api/app/services/design/prompts/skill_store/keys.py +++ b/apps/api/app/services/design/prompts/skill_store/keys.py @@ -9,7 +9,6 @@ NS_USER, SOURCE_ADMIN, SOURCE_FILE, - SOURCE_SEED, _NS_KEY_RE, _PIN_RE, _SLUG_RE, @@ -20,7 +19,7 @@ def _normalize_source(raw: Any, *, default: str = SOURCE_ADMIN) -> str: s = str(raw or "").strip().lower() - if s in (SOURCE_SEED, SOURCE_ADMIN, SOURCE_FILE): + if s in (SOURCE_ADMIN, SOURCE_FILE): return s return default @@ -49,7 +48,6 @@ def qualify_skill_key(namespace: str, local_key: str) -> str: if not local: return "" if ns == NS_CORE: - # Core keeps bare storage keys for backward compatibility. return local return f"{ns}.{local}" 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 08412a70..75fbd4ac 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 @@ -299,28 +299,23 @@ def _public_skills_dirs() -> list[Path]: def _file_skills_dir() -> Path: - """Primary shipped skills dir (foundation first; legacy seeds fallback).""" + """Primary shipped skills dir (foundation first).""" foundation = _repo_root() / "skills" / "foundation" if foundation.is_dir(): return foundation - from app.core.config import resolve_seed_dir - - return resolve_seed_dir("design_skills") + return foundation def _file_skills_dirs() -> list[Path]: - """Public ``skills/*`` + legacy ``seeds/design_skills`` + ``plugins/skills``. + """Public ``skills/*`` + ``plugins/skills``. Later roots win on duplicate ``skill_key`` (private plugins override shipped packs). ``.agents/skills`` is IDE/Cursor tooling — not scanned by the Design Agent. """ - from app.core.config import api_seeds_dir - dirs: list[Path] = [] seen: set[str] = set() for root in ( *_public_skills_dirs(), - api_seeds_dir() / "design_skills", *_plugin_skills_dirs(), ): try: @@ -338,7 +333,7 @@ def _pack_has_product_meta(pack_dir: Path) -> bool: return any((pack_dir / name).is_file() for name in _META_NAMES) -# Legacy SOURCE_SEED / core-reserved path removed — skills ship as file packs only. +# Skills ship as file packs only (NS_CORE/NS_EXT); no DB seed source. _SEED: list[dict[str, Any]] = [] _SEED_BY_KEY: dict[str, dict[str, Any]] = {} _CORE_RESERVED_KEYS: frozenset[str] = frozenset() 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 6d999817..205b1694 100644 --- a/apps/api/app/services/design/prompts/skill_store/runtime.py +++ b/apps/api/app/services/design/prompts/skill_store/runtime.py @@ -19,7 +19,6 @@ NS_USER, SOURCE_ADMIN, SOURCE_FILE, - SOURCE_SEED, _ALWAYS_ALLOW_OPS, _DISK_SIGNATURE, _INTERNAL_RESOURCE_KINDS, @@ -299,7 +298,7 @@ def list_runtime_skills( return out def resolve_storage_skill_key(raw: str, *, scene: str = "") -> str | None: - """Map bare / namespaced / legacy refs onto the storage skill_key.""" + """Map bare / namespaced refs onto the storage skill_key.""" base, _, _ = parse_skill_pin(raw) s = base.strip().lower() if not s: @@ -586,6 +585,16 @@ def _skill_body_for_context(row: dict[str, Any], *, role: str = "paint") -> str: return body +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() + if role == "paint" and mode == "review": + return False + return True + + def format_skills_details( *, keys: list[str], @@ -692,6 +701,8 @@ def row_sort_key(r: dict[str, Any]) -> tuple[int, int, str]: name = str(r.get("name") or key) when = str(r.get("whenToUse") or "").strip() cat = str(r.get("category") or "agent").strip().lower() or "agent" + if not _skill_available_for_context(r, role=role): + continue body = _skill_body_for_context(r, role=role) budget = int(_SKILL_CATEGORY_BUDGET.get(cat, 1200)) if len(body) > budget: @@ -809,7 +820,7 @@ def preferred_tools_allowlist( for r in _iter_skills_for_keys(skill_keys, scene=scene): source = str(r.get("source") or "").strip().lower() ns = str(r.get("namespace") or _SOURCE_TO_NS.get(source, NS_USER)) - if source in (SOURCE_SEED, SOURCE_FILE) or ns in (NS_CORE, NS_EXT): + if source == SOURCE_FILE or ns in (NS_CORE, NS_EXT): only_custom = False prefs = r.get("preferredTools") or [] if prefs: @@ -848,7 +859,7 @@ def skill_resource_allowlist( if source == SOURCE_ADMIN or ns == NS_USER: saw_custom = True continue - if source in (SOURCE_SEED, SOURCE_FILE) or ns in (NS_CORE, NS_EXT): + if source == SOURCE_FILE or ns in (NS_CORE, NS_EXT): saw_platform_open = True elif source == SOURCE_ADMIN or ns == NS_USER: saw_custom = True @@ -890,7 +901,7 @@ def filter_ops_by_skill_output_schema( for op in ops or []: if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op_key") or "").strip() + name = str(op.get("name") or "").strip() if not name or name in allowed_ops: kept.append(op) continue @@ -931,7 +942,7 @@ def filter_ops_by_skill_allowlist( for op in ops or []: if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op_key") or "").strip() + name = str(op.get("name") or "").strip() if not name or name in allow: kept.append(op) continue @@ -1189,4 +1200,4 @@ def resolve_triggered_skill_keys( loaded.add(key) if len(out) >= effective_max: break - return out \ No newline at end of file + return out 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 3997f90c..7989d317 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 @@ -22,7 +22,6 @@ NS_USER, SOURCE_ADMIN, SOURCE_FILE, - SOURCE_SEED, _MAX_USER_SKILL_ZIP_BYTES, _MAX_USER_SKILL_ZIP_UNCOMPRESSED, _META_NAMES, @@ -398,7 +397,7 @@ def delete_end_user_skill(*, user_id: str, skill_id: int) -> bool: if owner != uid: raise ValueError("not_skill_owner") src = _normalize_source(_row_get(row, "source"), default=SOURCE_ADMIN) - if src in (SOURCE_SEED, SOURCE_FILE): + if src != SOURCE_ADMIN: raise ValueError("cannot_delete_system_skill") ok = crud.delete_owned_design_skill( session=session, item_id=int(skill_id), owner_user_id=uid diff --git a/apps/api/app/services/design/prompts/system_prompt_store.py b/apps/api/app/services/design/prompts/system_prompt_store.py index 1a47cda0..7f2f244c 100644 --- a/apps/api/app/services/design/prompts/system_prompt_store.py +++ b/apps/api/app/services/design/prompts/system_prompt_store.py @@ -100,43 +100,8 @@ def _row_to_item(row: Any) -> dict[str, Any]: } -def _load_legacy_global_rules() -> dict[str, str]: - """One-shot migrate from design_global_rule (table may be gone).""" - legacy: dict[str, str] = {} - try: - from sqlmodel import Session - - from app import crud - from app.core.db import engine - - with Session(engine) as session: - for r in crud.list_all_design_global_rules(session=session): - rk = str(r.rule_key or "") - if is_system_prompt_key(rk): - legacy[rk] = str(r.rule_value or "") - except Exception: - return {} - return legacy - - -def _delete_legacy_global_rules(keys: list[str]) -> None: - if not keys: - return - try: - from sqlmodel import Session - - from app import crud - from app.core.db import engine - - with Session(engine) as session: - crud.delete_design_global_rules_by_keys(session=session, keys=keys) - session.commit() - except Exception: - pass - - def ensure_system_prompts() -> None: - """Insert missing rows from prompt-pack seed; migrate legacy KV once. Never overwrite Admin body. + """Insert missing rows from prompt-pack seed. Never overwrite Admin body. Do not call ``ensure_design_catalog`` here — catalog invokes this while bootstrapping. """ @@ -148,7 +113,6 @@ def ensure_system_prompts() -> None: return seed_items = _load_seed_items() now = time.time() - legacy = _load_legacy_global_rules() with Session(engine) as session: existing = crud.list_design_system_prompt_keys(session=session) for it in seed_items: @@ -160,7 +124,7 @@ def ensure_system_prompts() -> None: selectable = 1 if bool(it.get("selectable")) else 0 sort_order = int(it.get("sortOrder") or 0) desc = str(it.get("description") or "").strip() - body = str(legacy.get(key) or it.get("body") or "") + body = str(it.get("body") or "") crud.insert_design_system_prompt_seed( session=session, prompt_key=key, @@ -193,7 +157,6 @@ def ensure_system_prompts() -> None: sort_order=sort_order, ) session.commit() - _delete_legacy_global_rules(list(legacy.keys())) _READY = True diff --git a/apps/api/app/services/design/runtime/agent_controller.py b/apps/api/app/services/design/runtime/agent_controller.py deleted file mode 100644 index c4e32503..00000000 --- a/apps/api/app/services/design/runtime/agent_controller.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Back-compat re-exports for tests and admin hooks.""" -from app.services.design.runtime.graph.build import ( - _bind_design_hold_fns, - _build_lc_design_graph, - _bump, - _cleanup_design_thread, - _commit, - _design_graph_node_timeout, - _design_graph_retry_policy, - _design_refund_hold_fn, - _design_settle_hold_fn, - _design_thread_id, - _get_design_graph_checkpointer, - _goto_cmd, - _lc_design_graph, - _unbind_design_hold_fns, - cleanup_design_checkpoint, - get_design_run_status, - invalidate_agent_graph_cache, - list_topology_templates, - request_design_cancel, - request_design_pause, - resolve_topology_graph, - resume_agent_graph, - run_agent_graph, - start_design_checkpoint_ttl_scheduler, - sweep_stale_design_checkpoints, - validate_profile_topology, -) -from app.services.design.runtime.graph.state import ( - AgentGraphRunInput, - AgentRunState as _AgentRunState, - AgentRuntime as _AgentRuntime, - AgentTurnSchema, - DecideTurnSchema, - GraphState, - PaintOpsSchema, - PaintToolOp, -) - - -class AgentRunState(_AgentRunState): - """Back-compat shim — checkpoint serde allows this module path.""" - - -class AgentRuntime(_AgentRuntime): - """Back-compat shim — checkpoint serde allows this module path.""" - - -from app.services.design.runtime.graph.support import ( - _ask_propose_user_text, - _chat_fallback_text, - _derive_suggested_place_world, - _ensure_propose_choice_ui, - _format_spatial_placement, - _is_canvas_work_intent, - _is_lean_paint_turn, - _lc_design_needs_canvas_ops, - _normalize_choice_ui, - _normalize_ops_payload, - _parse_agent_turn, - _placement_errors_for_free_creates, - _resolve_agent_persona, - _scene_digest, - _should_route_to_paint, - _turn_from_structured, - _paint_tool_keys_for_turn, - _ops_patch_too_broad, - _structure_verify_issues, -) - -__all__ = [n for n in dir() if not n.startswith("_") or n.startswith("__")] diff --git a/apps/api/app/services/design/runtime/agent_profile.py b/apps/api/app/services/design/runtime/agent_profile.py index c0774e18..09d4b201 100644 --- a/apps/api/app/services/design/runtime/agent_profile.py +++ b/apps/api/app/services/design/runtime/agent_profile.py @@ -318,11 +318,6 @@ def put(rule_key: str, value: Any, *, serialize: str | None = None) -> None: put("precheck.router_model", routing.get("router_model")) if "lanes" in routing: put("precheck.model_threshold", routing.get("lanes"), serialize="lanes") - # Keep legacy alias in sync when we write a literal map. - if "precheck.model_threshold" in patches and not patches[ - "precheck.model_threshold" - ].startswith("$kv:"): - patches["precheck.model_lanes"] = patches["precheck.model_threshold"] if "fallback" in routing: put("precheck.fallback_chain", routing.get("fallback"), serialize="fallback") if "vision_model" in routing: diff --git a/apps/api/app/services/design/runtime/graph/build.py b/apps/api/app/services/design/runtime/graph/build.py index d3e93e7e..31396d67 100644 --- a/apps/api/app/services/design/runtime/graph/build.py +++ b/apps/api/app/services/design/runtime/graph/build.py @@ -104,12 +104,7 @@ class _RunControl: _CACHE = _GraphCompileCache() _RUN = _RunControl() -# Back-compat names — tests / older pokes still import these module attrs. -_TEMPLATE_GRAPHS = _CACHE.templates _LC_DESIGN_GRAPH = None -_DESIGN_HOLD_FNS = _RUN.hold_fns -_RUN_INTENT = _RUN.intent -_ACTIVE_RUN_TASKS = _RUN.tasks _INTENT_PAUSE = "pause" _INTENT_CANCEL = "cancel" 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 b4bc8530..cdb7d47b 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/apply.py +++ b/apps/api/app/services/design/runtime/graph/nodes/apply.py @@ -112,11 +112,7 @@ def _emit_design_transaction( skill_key: str = "react", skill_name: str = "Design Agent", ) -> str: - """BEGIN → tool_ops chunks (BC) → COMMIT. Returns transaction_id. - - Keeps legacy ``tool_ops`` events so older FE clients still apply. - New clients also see ``transaction.begin|chunk|commit``. - """ + """BEGIN → transaction chunks → COMMIT. Returns transaction_id.""" st = rt.run phase = resolve_transaction_phase(rt) base_rev = 0 @@ -170,23 +166,6 @@ def _emit_design_transaction( "round": round_i, } ) - # BC: existing FE only listens for tool_ops. - _emit( - { - "type": "tool_ops", - "index": round_i, - "task_id": st.task_id, - "trace_id": st.trace_id, - "skill_key": skill_key, - "skill_name": skill_name, - "schema_version": TOOL_OPS_SCHEMA_VERSION, - "transaction_id": tx.transaction_id, - "transaction_phase": tx.phase, - "chunk_index": ci, - "chunk_total": len(chunks), - "ops": sse_ops, - } - ) for act in _tool_ops_activity_events( batch=chunk, totals={"created": 0, "updated": 0, "deleted": 0}, 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 e174b4ea..c854394f 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/bootstrap.py +++ b/apps/api/app/services/design/runtime/graph/nodes/bootstrap.py @@ -23,9 +23,9 @@ _persist_progress, ) from app.services.design.runtime.models_route import ( - clamp_tier, - enabled_tiers, - estimate_task_tier, + clamp_lane, + enabled_lanes, + heuristic_route_lane, ) @@ -176,13 +176,15 @@ async def _hydrate_pinned_skills(rt: AgentRuntime) -> None: def _apply_task_route_flags(rt: AgentRuntime) -> None: - """Estimate task tier + mode flags.""" + """Estimate route lane + mode flags.""" st = rt.run - st.task_tier = clamp_tier( - estimate_task_tier( - rt.prompt, rules=rt.rules, skill_category="agent", scene=rt.scene_key or None - ), - enabled_tiers(rt.rules), + st.task_tier = clamp_lane( + heuristic_route_lane( + rt.prompt, + has_images=bool(rt.images), + scene=rt.scene_key or None, + ).lane, + enabled_lanes(rt.rules), ) tier_label = st.task_tier or "-" # Do not set vision_used here — only after pixels are actually sent to the LLM. 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 e9281bf8..d63bf2e3 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/decide.py +++ b/apps/api/app/services/design/runtime/graph/nodes/decide.py @@ -3,6 +3,7 @@ import asyncio import json import time +from dataclasses import dataclass from typing import Any from langgraph.types import Command @@ -131,6 +132,59 @@ async def _load_turn_resources(rt: AgentRuntime) -> None: await load_deferred_resources(rt, rt.turn) +@dataclass(frozen=True) +class IntelligenceTaskProfile: + """Explicit budget for the intelligence layer on one user turn.""" + + route: str + foundation: tuple[str, ...] + hops: tuple[str, ...] + review: bool + write_principle: bool + + +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) + + +def intelligence_task_profile(rt: AgentRuntime) -> IntelligenceTaskProfile: + """Choose intelligence depth from intent and explicit quality demand. + + Canvas edits are deterministic work. They must not pay for design research + unless the user actually asks for a design direction or supplies a brief. + """ + intent = str( + getattr(rt, "classified_intent", "") + or getattr(getattr(rt, "run", None), "intent", "") + or "" + ).strip().lower() + intensity = _normalized_intensity((rt.flags or {}).get("design_intensity")) + quality = str((rt.flags or {}).get("design_quality") or "standard").strip().lower() + design_requested = _requires_design_brief(rt, intent) + explicit_quality = quality in {"high", "strict", "professional"} + if not design_requested and not explicit_quality: + return IntelligenceTaskProfile("direct", (), (), False, False) + + hops, write_principle = intel_hops_for_intensity(intensity) + review = intensity in {"high", "extreme"} or explicit_quality + foundation = ("analyze_reference",) if intensity == "light" and rt.images else ( + "analyze_reference", + "retrieve_memory", + "autonomous_plan", + ) + if intensity == "light": + hops = () + return IntelligenceTaskProfile( + "design" if design_requested else "quality", + foundation, + tuple(hops), + review, + write_principle and design_requested, + ) + + def intel_hops_for_intensity(intensity: str | None) -> tuple[list[str], bool]: """Map design_intensity → optional Intelligence hops + principle write. @@ -138,7 +192,7 @@ def intel_hops_for_intensity(intensity: str | None) -> tuple[list[str], bool]: then these hops, then review / optimize / autonomous_sync, then write_principle when the second return is True. """ - level = str(intensity or "medium").strip().lower().replace("_", "-") + level = _normalized_intensity(intensity) if level in ("light", "low"): return [], False if level in ("medium", "mid", ""): @@ -524,43 +578,49 @@ async def _node_design_agent(state: GraphState) -> Command: rt.last_reason = reason from app.services.design.intelligence_runtime import get_design_intelligence_client - intel = get_design_intelligence_client() - await intel.analyze_reference(rt) - await intel.retrieve_memory(rt) - await intel.autonomous_plan(rt) - - # Design intensity → Intelligence depth (not model thinking effort). - # light: ref+memory+plan only - # medium: + research/strategy - # high: + candidates/tournament/swarm - # extreme: + simulate/counterfactual + principle write - intensity = str((rt.flags or {}).get("design_intensity") or "medium").strip().lower() - hops, write_principle = intel_hops_for_intensity(intensity) - hop_runners = { - "research": intel.research, - "strategy": intel.strategy, - "propose_candidates": intel.propose_candidates, - "tournament": intel.tournament, - "swarm_direction": intel.swarm_direction, - "simulate": intel.simulate, - "counterfactual": intel.counterfactual, - } - for hop in hops: - runner = hop_runners.get(hop) + profile = intelligence_task_profile(rt) + rt.flags["intelligence_route"] = profile.route + rt.flags["intelligence_hops"] = list(profile.hops) + if profile.foundation: + intel = get_design_intelligence_client() + foundation_runners = { + "analyze_reference": intel.analyze_reference, + "retrieve_memory": intel.retrieve_memory, + "autonomous_plan": intel.autonomous_plan, + } + for step in profile.foundation: + runner = foundation_runners.get(step) + if runner is not None: + await runner(rt) + else: + intel = None + + hop_runners = {} + if intel is not None: + hop_runners = { + "research": intel.research, + "strategy": intel.strategy, + "propose_candidates": intel.propose_candidates, + "tournament": intel.tournament, + "swarm_direction": intel.swarm_direction, + "simulate": intel.simulate, + "counterfactual": intel.counterfactual, + } + for hop in profile.hops: + runner = hop_runners.get(hop) if intel is not None else None if runner is not None: await runner(rt) # Review/optimization are expensive and may trigger another design loop. # Keep them for explicit quality work or high-risk, multi-stage creation. - quality = str((rt.flags or {}).get("design_quality") or "standard").strip().lower() - review_required = intensity in {"high", "extreme", "max"} or quality in {"high", "strict"} - if review_required: + if profile.review and intel is not None: await intel.review(rt) await intel.optimize(rt) - await intel.autonomous_sync(rt) - if write_principle: + if "autonomous_plan" in profile.foundation and intel is not None: + await intel.autonomous_sync(rt) + if profile.write_principle and intel is not None: await intel.write_principle(rt) - intel_suffix = _intel_prompt_suffix(rt) + intel_suffix = _intel_prompt_suffix(rt) if profile.foundation else "" for _round in range(max_rounds): round_i = st.round 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 b473b220..7cafb20e 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/observe.py +++ b/apps/api/app/services/design/runtime/graph/nodes/observe.py @@ -803,7 +803,7 @@ def _is_high_stakes_review_turn(rt: Any) -> bool: for op in list(getattr(rt, "paint_ops", None) or []): if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op_key") or "").strip() + name = str(op.get("name") or "").strip() if name == "create_frame": frames += 1 if frames >= 2: @@ -832,6 +832,8 @@ def _should_route_to_review( mode = _review_mode(rt) if mode == "off": return False + if bool((getattr(rt, "flags", None) or {}).get("review_repair_used")): + return False try: from app.services.design.runtime.models_route import normalize_user_intent @@ -878,7 +880,7 @@ def _spatial_grounding_issues(rt: AgentRuntime) -> list[str]: op for op in (rt.paint_ops or []) if isinstance(op, dict) - and str(op.get("name") or op.get("op_key") or "").startswith("create_") + and str(op.get("name") or "").startswith("create_") ] pts = [xy for op in creates if (xy := _create_op_xy(op)) is not None] diff --git a/apps/api/app/services/design/runtime/graph/nodes/paint.py b/apps/api/app/services/design/runtime/graph/nodes/paint.py index 7499cdfd..9de18910 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/paint.py +++ b/apps/api/app/services/design/runtime/graph/nodes/paint.py @@ -347,8 +347,6 @@ async def _paint_structured() -> dict[str, Any]: else: raw_obj = {} ops_raw = raw_obj.get("tool_ops") - if ops_raw is None: - ops_raw = raw_obj.get("ops") reply = _as_text(raw_obj.get("reply")).strip() intent = str(raw_obj.get("intent") or want).strip().lower() if intent not in ("edit", "create"): 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 53d5871e..22a2cb36 100644 --- a/apps/api/app/services/design/runtime/graph/nodes/review.py +++ b/apps/api/app/services/design/runtime/graph/nodes/review.py @@ -1959,6 +1959,7 @@ def _try_repair_plan_command( rt.flags["critique_failed"] = True rt.flags["review_failed"] = True rt.flags["review_action"] = "repair" + rt.flags["review_repair_used"] = True rt.flags["rebuild"] = False rt.flags["repair"] = True rt.flags["retry"] = True @@ -2115,6 +2116,7 @@ async def _retry_paint_from_review( rt.flags["critique_failed"] = True rt.flags["review_failed"] = True rt.flags["review_action"] = action + rt.flags["review_repair_used"] = True rt.flags["rebuild"] = action == "rebuild" rt.flags["repair"] = action == "repair" rt.flags["retry"] = True 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 67843630..b0b4ce32 100644 --- a/apps/api/app/services/design/runtime/graph/paint_kit.py +++ b/apps/api/app/services/design/runtime/graph/paint_kit.py @@ -71,7 +71,7 @@ def _count_ok_creates( for op in paint_ops or []: if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op_key") or "").strip() + name = str(op.get("name") or "").strip() if not name.startswith("create_"): continue oid = str(op.get("op_id") or "") @@ -184,7 +184,7 @@ def _structure_verify_issues( def _op_tool_name(o: dict[str, Any]) -> str: - return str(o.get("name") or o.get("op_key") or "").strip() + return str(o.get("name") or "").strip() def _ops_have_create_frame(ops: list[dict[str, Any]]) -> bool: diff --git a/apps/api/app/services/design/runtime/graph/state.py b/apps/api/app/services/design/runtime/graph/state.py index fd75c714..703c1769 100644 --- a/apps/api/app/services/design/runtime/graph/state.py +++ b/apps/api/app/services/design/runtime/graph/state.py @@ -133,18 +133,18 @@ def parse_design_brief(raw: Any) -> dict[str, Any] | None: text = raw.strip() if not text: return None - # Prefer JSON object; plain prose kept as legacy thesis blob. + # Prefer JSON object; non-JSON strings are rejected. if text.startswith("{") and text.endswith("}"): try: parsed = json.loads(text) if isinstance(parsed, dict): data = parsed else: - return {"visual_thesis": text, "_legacy_prose": True} + return None except Exception: - return {"visual_thesis": text, "_legacy_prose": True} + return None else: - return {"visual_thesis": text, "_legacy_prose": True} + return None else: return None try: @@ -154,12 +154,9 @@ def parse_design_brief(raw: Any) -> dict[str, Any] | None: def design_brief_p0_missing(brief: dict[str, Any] | None) -> list[str]: - """Return missing P0 field names. Legacy prose briefs skip structured P0.""" + """Return missing P0 field names.""" if not brief: return list(DESIGN_BRIEF_P0_FIELDS) - if brief.get("_legacy_prose"): - # Accept one-shot prose during transition; still require non-empty thesis. - return [] if _brief_field_nonempty(brief.get("visual_thesis")) else ["visual_thesis"] missing: list[str] = [] for key in DESIGN_BRIEF_P0_FIELDS: if not _brief_field_nonempty(brief.get(key)): @@ -1600,7 +1597,7 @@ class AgentGraphRunInput: t0: float settle_hold_fn: Any refund_hold_fn: Any - # Stable API-assigned id for worker-backed runs; omitted by legacy callers. + # Stable API-assigned id for worker-backed runs. task_id: str | None = None apply_ops: list[dict[str, Any]] | None = None proposal_id: str | None = None @@ -1678,7 +1675,7 @@ class AgentRuntime: classified_intent: str = "" classified_paint_lane: str = "" classified_reply: str = "" - # Typed intent → execution hand-off. Kept in flags for checkpoint compatibility. + # Typed intent → execution hand-off. Kept in flags for checkpoints. design_plan: dict[str, Any] | None = None # Decide → paint/review execution contract (not craft curricula). design_brief: str = "" diff --git a/apps/api/app/services/design/runtime/graph/support.py b/apps/api/app/services/design/runtime/graph/support.py index d291bec5..647ad29f 100644 --- a/apps/api/app/services/design/runtime/graph/support.py +++ b/apps/api/app/services/design/runtime/graph/support.py @@ -1,4 +1,4 @@ -"""Back-compat barrel — prefer emit_sse / llm_io / turns / paint_kit / scene_log.""" +"""Barrel re-export for emit_sse / llm_io / turns / paint_kit / scene_log.""" from __future__ import annotations from app.services.design.runtime.graph.emit_sse import * # noqa: F403 diff --git a/apps/api/app/services/design/runtime/graph/turns.py b/apps/api/app/services/design/runtime/graph/turns.py index d6028ca8..8dadb9d6 100644 --- a/apps/api/app/services/design/runtime/graph/turns.py +++ b/apps/api/app/services/design/runtime/graph/turns.py @@ -30,6 +30,16 @@ _ASK_CHOICE_ACTIONS = frozenset({"apply", "reply", "dismiss"}) +def _thought_context_limits(rt: Any) -> tuple[int, int, int, int]: + """Bound memory and scene context by the work being decided.""" + intent = normalize_user_intent(getattr(rt, "classified_intent", None)) + if intent == "canvas_op": + return 900, 3, 280, 1400 + if getattr(rt, "pending_skill_details", ""): + return 1400, 4, 320, 1800 + return 1800, 5, 360, 2200 + + def _is_canvas_work_intent(raw: str | None) -> bool: s = str(raw or "").strip().lower() if s in CANVAS_WORK_INTENTS: @@ -120,14 +130,8 @@ def _normalize_choice_option(raw: Any) -> dict[str, str] | None: return {"label": label, "action": "reply"} if not isinstance(raw, dict): return None - label = _as_text( - raw.get("label") or raw.get("text") or raw.get("title") or raw.get("id") - ).strip()[:48] - action = _as_text(raw.get("action") or raw.get("role") or "reply").strip().lower() - if action in ("cancel", "close", "reject"): - action = "dismiss" - if action in ("ok", "confirm", "execute", "paint"): - action = "apply" + label = _as_text(raw.get("label")).strip()[:48] + action = _as_text(raw.get("action") or "reply").strip().lower() if action not in _ASK_CHOICE_ACTIONS: action = "reply" # apply/dismiss may omit label — FE fills i18n chrome. @@ -136,56 +140,35 @@ def _normalize_choice_option(raw: Any) -> dict[str, str] | None: return {"label": label, "action": action} def _choice_ui_raw_from_turn(obj: dict[str, Any]) -> Any: - """Prefer nested choice_ui; lift top-level mode+options when models flatten it.""" - nested = obj.get("choice_ui") or obj.get("choiceUi") or obj.get("ask_ui") - if nested: - return nested - mode = _as_text(obj.get("mode") or obj.get("type") or "").strip().lower() - options = obj.get("options") or obj.get("items") - if mode in ("freeform", "free_text", "input", "textarea"): - mode = "text" - if mode in _ASK_CHOICE_MODES and (isinstance(options, list) or mode == "text"): - lifted: dict[str, Any] = {"mode": mode} - if isinstance(options, list): - lifted["options"] = options - placeholder = _as_text( - obj.get("placeholder") or obj.get("hint") or obj.get("prompt") - ).strip() - if placeholder: - lifted["placeholder"] = placeholder[:120] - return lifted - return None + """Nested ``choice_ui`` only — flattened top-level mode/options is invalid.""" + return obj.get("choice_ui") def _normalize_choice_ui( raw: Any, *, - legacy_choices: list[str] | None = None, - legacy_apply: str = "", + fallback_choices: list[str] | None = None, + fallback_apply: str = "", ) -> dict[str, Any] | None: """Validate Ask choice format. Content labels stay model-authored.""" mode = "" options_raw: list[Any] = [] placeholder = "" if isinstance(raw, dict): - mode = _as_text(raw.get("mode") or raw.get("type") or "").strip().lower() - if mode in ("freeform", "free_text", "input", "textarea"): - mode = "text" - options_raw = list(raw.get("options") or raw.get("items") or raw.get("choices") or []) - placeholder = _as_text( - raw.get("placeholder") or raw.get("hint") or raw.get("prompt") - ).strip()[:120] + mode = _as_text(raw.get("mode")).strip().lower() + options_raw = list(raw.get("options") or []) + placeholder = _as_text(raw.get("placeholder")).strip()[:120] elif isinstance(raw, list): options_raw = list(raw) - if not options_raw and legacy_choices: - options_raw = list(legacy_choices) + if not options_raw and fallback_choices: + options_raw = list(fallback_choices) options: list[dict[str, str]] = [] for item in options_raw[:8]: opt = _normalize_choice_option(item) if not opt: continue options.append(opt) - apply_label = _as_text(legacy_apply).strip()[:48] + apply_label = _as_text(fallback_apply).strip()[:48] if apply_label: matched = False for opt in options: @@ -221,8 +204,8 @@ def _normalize_choice_ui( out["placeholder"] = placeholder return out -def _choice_ui_sync_compat(st: AgentRunState) -> None: - """Keep choices[] / apply_choice in sync for older SSE clients.""" +def _sync_choice_ui_fields(st: AgentRunState) -> None: + """Keep choices[] / apply_choice in sync with choice_ui for SSE clients.""" ui = st.choice_ui if isinstance(st.choice_ui, dict) else None if not ui: return @@ -241,31 +224,31 @@ def _choice_ui_sync_compat(st: AgentRunState) -> None: def _absorb_ask_choices(st: AgentRunState, turn: dict[str, Any]) -> None: """Persist Ask choice_ui from the model turn (create|edit propose included).""" - legacy_choices = list(turn.get("choices") or [])[:6] - legacy_apply = _as_text(turn.get("apply_choice")).strip() + fallback_choices = list(turn.get("choices") or [])[:6] + fallback_apply = _as_text(turn.get("apply_choice")).strip() raw_ui = turn.get("choice_ui") or _choice_ui_raw_from_turn(turn) ui = _normalize_choice_ui( raw_ui, - legacy_choices=legacy_choices, - legacy_apply=legacy_apply, + fallback_choices=fallback_choices, + fallback_apply=fallback_apply, ) st.choice_ui = ui if ui: - _choice_ui_sync_compat(st) + _sync_choice_ui_fields(st) return - st.choices = legacy_choices - if legacy_apply: - st.apply_choice = legacy_apply[:48] - if legacy_apply not in st.choices: - st.choices = [legacy_apply] + [c for c in st.choices if c != legacy_apply] + st.choices = fallback_choices + if fallback_apply: + st.apply_choice = fallback_apply[:48] + if fallback_apply not in st.choices: + st.choices = [fallback_apply] + [c for c in st.choices if c != fallback_apply] st.choices = st.choices[:6] def _ensure_propose_choice_ui(st: AgentRunState) -> dict[str, Any]: """Propose must expose format-valid choice_ui; do not invent question content.""" ui = _normalize_choice_ui( st.choice_ui, - legacy_choices=list(st.choices), - legacy_apply=st.apply_choice, + fallback_choices=list(st.choices), + fallback_apply=st.apply_choice, ) if not ui: # Structural chrome only — empty labels → FE i18n for confirm/cancel. @@ -282,7 +265,7 @@ def _ensure_propose_choice_ui(st: AgentRunState) -> dict[str, Any]: opts.insert(0, {"label": "", "action": "apply"}) ui = {**ui, "options": opts[:8]} st.choice_ui = ui - _choice_ui_sync_compat(st) + _sync_choice_ui_fields(st) return ui def _ask_propose_user_text(*, model_reply: str, detail: str) -> str: @@ -295,12 +278,10 @@ def _normalize_agent_turn_obj(obj: dict[str, Any] | None) -> dict[str, Any]: obj = obj if isinstance(obj, dict) else {} intent = str(obj.get("intent") or "").strip().lower() if intent not in ("chat", "ask", "done", "edit", "create"): - intent = "edit" if (obj.get("tool_ops") or obj.get("ops")) else "chat" + intent = "edit" if obj.get("tool_ops") else "chat" reply = _as_text(obj.get("reply")).strip() thought = _as_text(obj.get("thought")).strip() ops_raw = obj.get("tool_ops") - if ops_raw is None: - ops_raw = obj.get("ops") done = obj.get("done") if done is None: done = intent in ("chat", "ask", "done") @@ -309,18 +290,18 @@ def _normalize_agent_turn_obj(obj: dict[str, Any] | None) -> dict[str, Any]: if isinstance(raw_choices, list): for c in raw_choices: if isinstance(c, dict): - text = _as_text(c.get("label") or c.get("text") or "").strip() + text = _as_text(c.get("label") or "").strip() else: text = _as_text(c).strip() if text and text not in choices: choices.append(text[:48]) if len(choices) >= 6: break - apply_choice = _as_text(obj.get("apply_choice") or obj.get("applyChoice")).strip()[:48] + apply_choice = _as_text(obj.get("apply_choice")).strip()[:48] choice_ui = _normalize_choice_ui( _choice_ui_raw_from_turn(obj), - legacy_choices=choices, - legacy_apply=apply_choice, + fallback_choices=choices, + fallback_apply=apply_choice, ) if choice_ui: choices = [ @@ -338,16 +319,16 @@ def _normalize_agent_turn_obj(obj: dict[str, Any] | None) -> dict[str, Any]: apply_choice, ) need_tools = normalize_need_tools( - obj.get("need_tools") or obj.get("needTools") or obj.get("tools_needed") + obj.get("need_tools") ) from app.services.design.prompts.skill_store import parse_need_skills_with_pins from app.services.design.runtime.subagent import parse_need_subagents need_skills, skill_version_pins, skill_input_args, skill_parse_errs = ( - parse_need_skills_with_pins(obj.get("need_skills") or obj.get("needSkills")) + parse_need_skills_with_pins(obj.get("need_skills")) ) need_subagents = parse_need_subagents( - obj.get("need_subagents") or obj.get("needSubagents") + obj.get("need_subagents") ) return { "intent": intent, @@ -368,7 +349,7 @@ def _normalize_agent_turn_obj(obj: dict[str, Any] | None) -> dict[str, Any]: } def _parse_agent_turn(content: str) -> dict[str, Any]: - """Parse free-form model text → normalized turn (legacy / fallback).""" + """Parse free-form model text → normalized turn (fallback path).""" obj: dict[str, Any] = {} try: parsed = _agent_turn_parser().parse(content or "") @@ -427,6 +408,7 @@ def _thought_prompt_variables(rt: Any) -> dict[str, str]: else: canvas_size = _as_text(rt.canvas_size).strip() or "unknown" + memory_limit, dialogue_count, dialogue_limit, edit_context_limit = _thought_context_limits(rt) pending_parts: list[str] = [] _append_pending_reinject( pending_parts, @@ -471,18 +453,18 @@ def _thought_prompt_variables(rt: Any) -> dict[str, str]: + "\n".join(f"{i+1}. {s}" for i, s in enumerate(st.plan[:12])) + "\n\n" ) - memory_block = f"MEMORY:\n{rt.mem_blocks[:2500]}\n\n" if rt.mem_blocks else "" + memory_block = f"MEMORY:\n{rt.mem_blocks[:memory_limit]}\n\n" if rt.mem_blocks else "" recent_dialogue = "" if rt.mem_short: dial_lines: list[str] = [] - for t in list(rt.mem_short)[-8:]: + for t in list(rt.mem_short)[-dialogue_count:]: 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() if not text: continue - dial_lines.append(f"{role}: {text[:400]}") + dial_lines.append(f"{role}: {text[:dialogue_limit]}") if dial_lines: recent_dialogue = ( "RECENT_DIALOGUE (continue this thread; do not re-greet):\n" @@ -513,8 +495,8 @@ def _thought_prompt_variables(rt: Any) -> dict[str, str]: include_full_svg=False, scene_nodes=rt.scene_nodes, ) - if len(edit_context) > 2500: - edit_context = edit_context[:2500] + "\n…(edit_context truncated)" + if len(edit_context) > edit_context_limit: + edit_context = edit_context[:edit_context_limit] + "\n…(edit_context truncated)" try: @@ -569,7 +551,7 @@ def _format_thought_messages(rt: Any) -> tuple[str, str]: '_clear_ask_choice_state', '_normalize_choice_option', '_normalize_choice_ui', - '_choice_ui_sync_compat', + '_sync_choice_ui_fields', '_absorb_ask_choices', '_ensure_propose_choice_ui', '_ask_propose_user_text', diff --git a/apps/api/app/services/design/runtime/host/ops_gate.py b/apps/api/app/services/design/runtime/host/ops_gate.py index 374e69aa..bbae5db9 100644 --- a/apps/api/app/services/design/runtime/host/ops_gate.py +++ b/apps/api/app/services/design/runtime/host/ops_gate.py @@ -51,27 +51,17 @@ def _validate_ops_payload( def _op_name(op: dict[str, Any]) -> str: - return str(op.get("name") or op.get("op_key") or "").strip() + return str(op.get("name") or "").strip() def _normalize_ops_payload(raw: Any) -> Any: - """Accept op_key / ops aliases before schema validate.""" + """Pass through a tool_ops list or ``{tool_ops: [...]}`` envelope.""" if isinstance(raw, list): - out = [] - for item in raw: - if not isinstance(item, dict): - continue - d = dict(item) - if not (d.get("name") or d.get("type") or d.get("op") or d.get("tool")): - ok = str(d.get("op_key") or d.get("opKey") or "").strip() - if ok: - d["name"] = ok - out.append(d) - return out + return [item for item in raw if isinstance(item, dict)] if isinstance(raw, dict): - inner = raw.get("ops") or raw.get("tool_ops") + inner = raw.get("tool_ops") if isinstance(inner, list): - return {"ops": _normalize_ops_payload(inner)} + return {"tool_ops": _normalize_ops_payload(inner)} return raw return raw diff --git a/apps/api/app/services/design/runtime/host/placement.py b/apps/api/app/services/design/runtime/host/placement.py index 274ea2ec..4849a8f4 100644 --- a/apps/api/app/services/design/runtime/host/placement.py +++ b/apps/api/app/services/design/runtime/host/placement.py @@ -144,7 +144,7 @@ def _derive_suggested_place_world( ) -> dict[str, float] | None: """Viewport-first place: blank slot (align if possible) or camera center. - NOTE: The return value is used only for tests / legacy callers. + NOTE: The return value is used only for tests and utility callers. The paint prompt no longer injects these coords as suggestions to the model (see _format_spatial_placement which returns ""). """ @@ -251,7 +251,7 @@ def _batch_opens_new_frame(ops: list[dict[str, Any]]) -> bool: for op in ops: if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op_key") or "").strip() + name = str(op.get("name") or "").strip() if name in ("create_frame", "ensure_frame"): return True return False @@ -297,7 +297,7 @@ def _placement_errors_for_free_creates(rt: Any, ops: list[dict[str, Any]]) -> li for op in ops: if not isinstance(op, dict): continue - name = str(op.get("name") or op.get("op_key") or "").strip() + name = str(op.get("name") or "").strip() if name not in create_names: continue ox_raw, oy_raw, frame_id = _create_op_placement_fields(op) diff --git a/apps/api/app/services/design/runtime/host/resources.py b/apps/api/app/services/design/runtime/host/resources.py index 304de160..dc9615dc 100644 --- a/apps/api/app/services/design/runtime/host/resources.py +++ b/apps/api/app/services/design/runtime/host/resources.py @@ -245,7 +245,7 @@ async def _load_deferred_subagents( ) -> None: """Spawn Profile catalog subagents (sync await and/or background).""" jobs = parse_need_subagents( - turn.get("need_subagents") or turn.get("needSubagents") + turn.get("need_subagents") ) pending_job_ids = [ str(x).strip() @@ -398,7 +398,7 @@ async def load_deferred_resources( need_tools = list(turn.get("need_tools") or []) need_skills = list(turn.get("need_skills") or []) need_subagents = parse_need_subagents( - turn.get("need_subagents") or turn.get("needSubagents") + turn.get("need_subagents") ) # Pass-through only — no auto vision_scout / research. intent_l = str(turn.get("intent") or st.intent or "").strip() or "create" @@ -412,19 +412,21 @@ async def load_deferred_resources( existing=need_subagents, ) turn["need_subagents"] = need_subagents - # Auto-merge enabled skills whose triggers match (empty_canvas / intent / …). - # Domain playbooks live in skills + prompts. - for k in resolve_triggered_skill_keys( - scene=rt.scene_key or "", - empty_canvas=_canvas_is_empty(rt), - has_images=bool(rt.images), - intent=intent_l, - prompt_chars=len(str(rt.prompt or "").strip()), - prompt=str(rt.prompt or ""), - already_loaded=list(st.skills_loaded or []) + list(need_skills), - ): - if k not in need_skills: - need_skills.append(k) + # Auto skills are for design/create turns. Explicit pins and need_skills + # still work for every intent; ordinary edits must stay deterministic. + auto_skill_intents = {"create", "design"} + if intent_l in auto_skill_intents: + for k in resolve_triggered_skill_keys( + scene=rt.scene_key or "", + empty_canvas=_canvas_is_empty(rt), + has_images=bool(rt.images), + intent=intent_l, + prompt_chars=len(str(rt.prompt or "").strip()), + prompt=str(rt.prompt or ""), + already_loaded=list(st.skills_loaded or []) + list(need_skills), + ): + if k not in need_skills: + need_skills.append(k) # Surface → Core via _meta.extends (dedupe + category order inside expand). try: diff --git a/apps/api/app/services/design/runtime/models_route.py b/apps/api/app/services/design/runtime/models_route.py index b69efa1b..f2081d8c 100644 --- a/apps/api/app/services/design/runtime/models_route.py +++ b/apps/api/app/services/design/runtime/models_route.py @@ -12,7 +12,6 @@ - vision — must understand attached images - image — image-generation catalog slot (not a text chat lane) -Legacy Admin keys ``simple|medium|complex`` still parse → ``fast|standard|reasoning``. """ from __future__ import annotations @@ -29,14 +28,6 @@ ROUTE_LANES = ("fast", "standard", "reasoning", "vision") IMAGE_SLOT = "image" -# Old product keys → new lanes (read path only). -_LEGACY_LANE_ALIASES = { - "simple": "fast", - "medium": "standard", - "complex": "reasoning", - "else": "standard", -} - LANE_LABELS_ZH = { "fast": "轻量", "standard": "标准", @@ -268,37 +259,20 @@ def normalize_paint_lane(raw: str | None, *, intent: str) -> str: def normalize_user_intent(raw: str | None) -> str: - """Map classifier / legacy labels → chat | canvas_op | design.""" + """Accept only the canonical classifier intents.""" s = str(raw or "").strip().lower() if s in USER_INTENTS: return s - # Legacy two-axis / create|edit labels. - if s in ("create", "edit"): - return "canvas_op" - if s in ("basic",): - return "canvas_op" - if s == "ask": - return "design" return "chat" def normalize_intent_decision( raw_intent: str | None, raw_lane: str | None = None, - *, - raw_grade: str | None = None, ) -> tuple[str, str]: - """Return (intent, paint_lane). Accepts legacy work_grade / create|edit.""" + """Return the canonical (intent, paint_lane) pair.""" s = str(raw_intent or "").strip().lower() - g = str(raw_grade or "").strip().lower() lane = str(raw_lane or "").strip().lower() - if s in ("create", "edit"): - # Old primary create|edit + optional work_grade. - if g == "design": - return "design", normalize_paint_lane(lane or s, intent="design") - return "canvas_op", normalize_paint_lane(lane or s, intent="canvas_op") - if s == "basic": - return "canvas_op", normalize_paint_lane(lane or "create", intent="canvas_op") intent = normalize_user_intent(s) return intent, normalize_paint_lane(lane, intent=intent) @@ -325,19 +299,14 @@ def normalize_lane(raw: str | None) -> str: s = str(raw or "").strip().lower() if not s: return "standard" - s = _LEGACY_LANE_ALIASES.get(s, s) if s in ROUTE_LANES or s == IMAGE_SLOT: return s return "standard" def parse_model_lanes(rules: dict[str, str] | None) -> dict[str, str]: - """Parse Admin lane→model map from ``precheck.model_threshold`` (or ``model_lanes``).""" - raw = str( - (rules or {}).get("precheck.model_lanes") - or (rules or {}).get("precheck.model_threshold") - or "" - ).strip() + """Parse Admin lane→model map from ``precheck.model_threshold``.""" + raw = str((rules or {}).get("precheck.model_threshold") or "").strip() out: dict[str, str] = {} if not raw: return out @@ -346,27 +315,14 @@ def parse_model_lanes(rules: dict[str, str] | None) -> dict[str, str]: if not part or "->" not in part: continue left, right = part.split("->", 1) - key = normalize_lane(left.strip().lower()) - # Preserve explicit vision/image keys; normalize_lane maps else→standard. left_l = left.strip().lower() - if left_l in ("vision", "image"): - key = left_l - elif left_l == "else": - key = "else" + allowed = set(ROUTE_LANES) | {IMAGE_SLOT, "else"} + if left_l not in allowed: + continue + key = left_l val = right.strip() if key and val: out[key] = val - # Promote legacy-only maps that never used new names. - for legacy, lane in (("simple", "fast"), ("medium", "standard"), ("complex", "reasoning")): - if lane not in out: - # Re-parse raw for un-normalized legacy keys. - for part in raw.split(";"): - part = part.strip() - if not part or "->" not in part: - continue - left, right = part.split("->", 1) - if left.strip().lower() == legacy and right.strip(): - out.setdefault(lane, right.strip()) if "else" in out: out.setdefault("fast", out["else"]) out.setdefault("standard", out["else"]) @@ -393,7 +349,6 @@ def parse_fallback_chain(rules: dict[str, str] | None) -> list[str]: def enabled_lanes(rules: dict[str, str] | None) -> list[str]: raw = str( (rules or {}).get("precheck.route_lanes") - or (rules or {}).get("precheck.task_tiers") or "fast|standard|reasoning|vision" ).strip() lanes = [normalize_lane(x) for x in _split_list(raw, "|;,")] @@ -402,11 +357,6 @@ def enabled_lanes(rules: dict[str, str] | None) -> list[str]: return lanes or ["fast", "standard", "reasoning", "vision"] -# Back-compat -def enabled_tiers(rules: dict[str, str] | None) -> list[str]: - return enabled_lanes(rules) - - def clamp_lane(lane: str, enabled: list[str] | None) -> str: t = normalize_lane(lane) if t == "vision" and (not enabled or "vision" in [x.lower() for x in (enabled or [])]): @@ -428,10 +378,6 @@ def clamp_lane(lane: str, enabled: list[str] | None) -> str: return enabled_l[0] -def clamp_tier(tier: str, enabled: list[str] | None) -> str: - return clamp_lane(tier, enabled) - - def pick_fallback_model( primary: str, rules: dict[str, str] | None, @@ -613,7 +559,6 @@ def pin_user_locked_model_routes( out["precheck.model_threshold"] = ( f"fast->{mid};standard->{mid};reasoning->{mid};else->{mid}" ) - out["precheck.model_lanes"] = out["precheck.model_threshold"] out["precheck.vision_model"] = mid out["precheck.fallback_chain"] = mid out["agent.review.model"] = mid @@ -624,13 +569,13 @@ def apply_user_route_overrides( rules: dict[str, str] | None, overrides: dict[str, Any] | None, ) -> dict[str, str]: - """Merge user Auto prefs. Accepts new lanes and legacy simple/medium/complex.""" + """Merge user Auto preferences for canonical model lanes.""" out = dict(rules or {}) if not overrides or not isinstance(overrides, dict): return out lanes = parse_model_lanes(out) - for key in ("fast", "standard", "reasoning", "simple", "medium", "complex"): + for key in ("fast", "standard", "reasoning"): raw = overrides.get(key) mid = str(raw or "").strip() if mid and mid.lower() not in ("auto", "platform", "default"): @@ -649,7 +594,6 @@ def apply_user_route_overrides( if k and v and k in ("fast", "standard", "reasoning", "else", "vision", "image") ) out["precheck.model_threshold"] = serialized - out["precheck.model_lanes"] = serialized vision = str( overrides.get("vision") or overrides.get("vision_model") or "" @@ -705,7 +649,6 @@ def sanitize_rules_for_openrouter_region( if changed: serialized = _serialize_lanes(lanes) out["precheck.model_threshold"] = serialized - out["precheck.model_lanes"] = serialized vision = str(out.get("precheck.vision_model") or "").strip() if is_openrouter_model_ref(vision): out["precheck.vision_model"] = ( @@ -772,25 +715,6 @@ def heuristic_route_lane( ) -def estimate_task_tier( - prompt: str, - *, - rules: dict[str, str] | None = None, - skill_category: str | None = None, - scene: str | None = None, - has_images: bool = False, - canvas_node_count: int = 0, -) -> str: - """Back-compat name → returns a lane id (fast|standard|reasoning|vision).""" - del rules, skill_category - return heuristic_route_lane( - prompt, - has_images=has_images, - canvas_node_count=canvas_node_count, - scene=scene, - ).lane - - def model_for_lane( lane: str, rules: dict[str, str] | None, @@ -1047,11 +971,9 @@ async def classify_user_intent( raw_clarification_options = [ option.model_dump() for option in structured.clarification_options ] - raw_grade = None elif isinstance(structured, dict): raw_intent = structured.get("intent") raw_lane = structured.get("paint_lane") or structured.get("paintLane") - raw_grade = structured.get("work_grade") or structured.get("workGrade") rationale = structured.get("rationale") reply = structured.get("reply") raw_action = structured.get("proposal_action") or structured.get( @@ -1069,9 +991,7 @@ async def classify_user_intent( type(structured).__name__, ) return fallback - intent, lane = normalize_intent_decision( - raw_intent, raw_lane, raw_grade=raw_grade - ) + intent, lane = normalize_intent_decision(raw_intent, raw_lane) if intent not in USER_INTENTS: _log.warning( "intent_classify invalid intent=%r; using heuristic", raw_intent diff --git a/apps/api/app/services/design/runtime/orchestrator.py b/apps/api/app/services/design/runtime/orchestrator.py index 937e6e17..4514a9d1 100644 --- a/apps/api/app/services/design/runtime/orchestrator.py +++ b/apps/api/app/services/design/runtime/orchestrator.py @@ -70,7 +70,7 @@ _log = logging.getLogger(__name__) -# Fallback authorize ceilings if TaskPricing import fails (legacy band). +# Fallback authorize ceilings if TaskPricing import fails. AGENT_HOLD = 30 PARTIAL_HOLD = 10 SINGLE_HOLD = 20 diff --git a/apps/api/app/services/design/runtime/pipeline_progress.py b/apps/api/app/services/design/runtime/pipeline_progress.py index bbc0be28..181f692b 100644 --- a/apps/api/app/services/design/runtime/pipeline_progress.py +++ b/apps/api/app/services/design/runtime/pipeline_progress.py @@ -51,7 +51,7 @@ class PipelineSseState: event_seq: int = 0 def decorate(self, payload: dict[str, Any]) -> dict[str, Any]: - """Attach the stable AgentEvent envelope without changing legacy payloads.""" + """Attach the stable AgentEvent envelope without changing payload shape.""" self.remember_task_id(payload) self.event_seq += 1 event_type = str(payload.get("type") or "event") diff --git a/apps/api/app/services/design/runtime/subagent.py b/apps/api/app/services/design/runtime/subagent.py index e84fd0f6..f59db41b 100644 --- a/apps/api/app/services/design/runtime/subagent.py +++ b/apps/api/app/services/design/runtime/subagent.py @@ -218,7 +218,7 @@ def resolve_auto_need_subagents( """Pass-through for declared need_subagents (no auto scout/research). Ref look + design_brief synthesis belong to Decide. Review is a graph fork, - not an auto Decide spawn. ``profile`` / canvas flags kept for call-site compat. + not an auto Decide spawn. ``profile`` / canvas flags remain pass-through. """ _ = (profile, has_images, empty_canvas, intent, prompt_chars, already) return list(existing or []) diff --git a/apps/api/app/services/llm/__init__.py b/apps/api/app/services/llm/__init__.py index 03b15f5d..2e37b298 100644 --- a/apps/api/app/services/llm/__init__.py +++ b/apps/api/app/services/llm/__init__.py @@ -1,4 +1,4 @@ -"""OpenAI-compatible LLM router.""" +"""OpenAI-style LLM router.""" from __future__ import annotations @@ -87,7 +87,7 @@ def uses_user_platform_byok(user_id: str | None, model: str | None) -> bool: return provider in user_byok_platforms(user_id) -# OpenAI-compatible chat bases (`POST {base}/chat/completions`). +# OpenAI-style chat bases (`POST {base}/chat/completions`). PROVIDER_BASE_URLS: dict[str, str] = { "doubao": "https://ark.cn-beijing.volces.com/api/v3", "deepseek": "https://api.deepseek.com", @@ -401,17 +401,6 @@ def resolve_provider(model_string: str | None) -> tuple[str, str]: if str(m.get("api_model") or "") == model: return str(m.get("provider") or "doubao"), model - # Env-mapped legacy aliases only when the corresponding setting is set. - legacy = { - "doubao-seed-1-6-251015": (settings.doubao_seed_model or "").strip(), - "doubao-1-5-pro-32k-250115": (settings.doubao_pro_model or "").strip(), - "doubao-seed": (settings.doubao_seed_model or "").strip(), - "doubao-pro": (settings.doubao_pro_model or "").strip(), - } - mapped = legacy.get(model) - if mapped: - return "doubao", mapped - # provider/model form, e.g. doubao/ep-xxxx or openrouter/anthropic/claude-sonnet-4 if "/" in model: prefix, rest = model.split("/", 1) @@ -435,7 +424,7 @@ def resolve_provider(model_string: str | None) -> tuple[str, str]: def get_llm_endpoint(model_string: str | None = None) -> LlmEndpoint: """ - Resolve an OpenAI-compatible chat endpoint. + Resolve an OpenAI-style chat endpoint. Platform keys via apps/api/.env, or BYOK ``custom:`` using the request-scoped user from ``set_byok_user_id``. @@ -498,21 +487,21 @@ def _default_headers_for(endpoint: LlmEndpoint) -> dict[str, str]: return headers -_CompatChatOpenAI: type | None = None -_compat_openai_factory_ready = False +_PatchedChatOpenAI: type | None = None +_openai_factory_patched = False -def _compat_chat_openai_cls() -> type: +def _patched_chat_openai_cls() -> type: """Lazy subclass so langchain-openai is only required at call time.""" - global _CompatChatOpenAI - if _CompatChatOpenAI is not None: - return _CompatChatOpenAI + global _PatchedChatOpenAI + if _PatchedChatOpenAI is not None: + return _PatchedChatOpenAI from langchain_openai import ChatOpenAI from langchain_core.outputs import ChatGenerationChunk from langchain_core.messages import AIMessageChunk - class CompatChatOpenAI(ChatOpenAI): + class PatchedChatOpenAI(ChatOpenAI): """Keep provider reasoning deltas that stock ChatOpenAI drops.""" def _convert_chunk_to_generation_chunk( @@ -547,26 +536,26 @@ def _convert_chunk_to_generation_chunk( ) return gen - _CompatChatOpenAI = CompatChatOpenAI - return CompatChatOpenAI + _PatchedChatOpenAI = PatchedChatOpenAI + return PatchedChatOpenAI -def _ensure_compat_openai_for_factory() -> None: +def _ensure_patched_openai_for_factory() -> None: """ - Point LangChain's openai provider at CompatChatOpenAI so + Point LangChain's openai provider at PatchedChatOpenAI so ``init_chat_model(..., model_provider='openai')`` keeps reasoning deltas. """ - global _compat_openai_factory_ready - if _compat_openai_factory_ready: + global _openai_factory_patched + if _openai_factory_patched: return import langchain_openai from langchain.chat_models.base import _get_chat_model_creator - compat = _compat_chat_openai_cls() - langchain_openai.ChatOpenAI = compat # type: ignore[misc, assignment] + patched = _patched_chat_openai_cls() + langchain_openai.ChatOpenAI = patched # type: ignore[misc, assignment] _get_chat_model_creator.cache_clear() - _compat_openai_factory_ready = True + _openai_factory_patched = True def build_chat_model( @@ -598,7 +587,7 @@ def build_chat_model( ep = endpoint or get_llm_endpoint(model) api_model = (model_id_override or ep.model_id).strip() - _ensure_compat_openai_for_factory() + _ensure_patched_openai_for_factory() kwargs: dict[str, Any] = { "api_key": ep.api_key, diff --git a/apps/api/app/services/llm/agent.py b/apps/api/app/services/llm/agent.py index 9c3bca10..94825c7c 100644 --- a/apps/api/app/services/llm/agent.py +++ b/apps/api/app/services/llm/agent.py @@ -30,15 +30,10 @@ # Design outer graph state (AgentRuntime / nested dataclasses) — msgpack allowlist. # No pickle_fallback: callables must stay out of checkpointed state. -# Keep pre-app/ package paths so older checkpoints still deserialize. _CHECKPOINT_MSGPACK_MODULES: tuple[tuple[str, str], ...] = ( - ("app.services.design.runtime.agent_controller", "AgentRuntime"), - ("app.services.design.runtime.agent_controller", "AgentRunState"), ("app.services.design.runtime.graph.state", "AgentRuntime"), ("app.services.design.runtime.graph.state", "AgentRunState"), ("app.services.design.runtime.decision_log", "DesignRunDecision"), - ("services.design.runtime.agent_controller", "AgentRuntime"), - ("services.design.runtime.agent_controller", "AgentRunState"), ("services.design.runtime.graph.state", "AgentRuntime"), ("services.design.runtime.graph.state", "AgentRunState"), ("services.design.runtime.decision_log", "DesignRunDecision"), @@ -148,7 +143,7 @@ def assemble_turn_from_lc_tools( break elif name == "request_tool_schemas": need_tools.extend( - normalize_need_tools(args.get("op_keys") or args.get("tools") or args) + normalize_need_tools(args.get("op_keys") or args) ) need_tools = normalize_need_tools(need_tools) diff --git a/apps/api/app/services/llm/byok_presets.py b/apps/api/app/services/llm/byok_presets.py index aae124d3..53e2c2b7 100644 --- a/apps/api/app/services/llm/byok_presets.py +++ b/apps/api/app/services/llm/byok_presets.py @@ -17,8 +17,6 @@ logger = logging.getLogger(__name__) BYOK_PLATFORM_RULE_KEY = "byok.preset_platforms" -# Legacy override key from the per-model preset experiment — still read as fallback. -BYOK_PRESET_RULE_KEY = "byok.preset_providers" PLATFORM_ID_PREFIX = "platform:" @@ -99,7 +97,7 @@ def _load_admin_platforms() -> list[dict[str, Any]] | None: from app.services.design.readpath.catalog import get_global_rules rules = get_global_rules() or {} - raw = rules.get(BYOK_PLATFORM_RULE_KEY) or rules.get(BYOK_PRESET_RULE_KEY) + raw = rules.get(BYOK_PLATFORM_RULE_KEY) except Exception: return None if not raw or not str(raw).strip(): @@ -111,27 +109,11 @@ def _load_admin_platforms() -> list[dict[str, Any]] | None: return None if not isinstance(parsed, list): return None - # Accept either platform objects or legacy per-model preset objects (id+baseUrl). platforms = [] for item in parsed: if not isinstance(item, dict): continue - if item.get("kinds") or not item.get("models"): - p = _sanitize_platform(item) - if p: - platforms.append(p) - continue - # Legacy preset → treat as a single-endpoint platform (manual-style). - p = _sanitize_platform( - { - "id": item.get("id"), - "name": item.get("name"), - "baseUrl": item.get("baseUrl") or item.get("base_url"), - "website": item.get("website"), - "iconKey": item.get("iconKey") or item.get("icon_key"), - "kinds": ["text"], - } - ) + p = _sanitize_platform(item) if p: platforms.append(p) return platforms or None @@ -144,7 +126,3 @@ def list_byok_platforms() -> list[dict[str, Any]]: return override return [p for p in (_sanitize_platform(x) for x in _DEFAULT_BYOK_PLATFORMS) if p] - -def list_byok_presets() -> list[dict[str, Any]]: - """Backward-compatible alias — platforms shaped for older clients.""" - return list_byok_platforms() diff --git a/apps/api/app/services/llm/chat.py b/apps/api/app/services/llm/chat.py index 69a32b8d..414901b2 100644 --- a/apps/api/app/services/llm/chat.py +++ b/apps/api/app/services/llm/chat.py @@ -1,4 +1,4 @@ -"""Chat streaming via LangChain ChatOpenAI (OpenAI-compatible providers).""" +"""Chat streaming via LangChain ChatOpenAI (OpenAI-style providers).""" from __future__ import annotations diff --git a/apps/api/app/services/llm/image.py b/apps/api/app/services/llm/image.py index 56821d2f..f9619aaa 100644 --- a/apps/api/app/services/llm/image.py +++ b/apps/api/app/services/llm/image.py @@ -640,7 +640,7 @@ async def _generate_openrouter_image( def _byok_image_transport(base_url: str) -> str: """Infer the images API size contract from the provider host. - ``openai_image`` = fixed OpenAI size set (gpt-image-1 / DALL·E compatible). + ``openai_image`` = fixed OpenAI size set (gpt-image-1 / DALL·E set). ``ark_image`` = arbitrary WxH (Volcengine Ark / Doubao and most aggregators). """ host = (base_url or "").strip().lower() @@ -677,7 +677,7 @@ async def _generate_byok_image( resolution: str | None, images: list[str] | None, ) -> dict[str, Any]: - """Generate via a user's BYOK OpenAI-compatible ``images.generate`` endpoint. + """Generate via a user's BYOK OpenAI-style ``images.generate`` endpoint. Uses the user's own key/quota — never platform credits. """ diff --git a/apps/api/app/services/llm/image_price.py b/apps/api/app/services/llm/image_price.py index 904637b1..87653b46 100644 --- a/apps/api/app/services/llm/image_price.py +++ b/apps/api/app/services/llm/image_price.py @@ -79,9 +79,6 @@ def estimate_openrouter_output_tokens( return int(_GEMINI_OUTPUT_TOKENS.get(res, _GEMINI_OUTPUT_TOKENS[DEFAULT_IMAGE_RESOLUTION])) -# Back-compat alias used by price_sync. -estimate_output_image_tokens = estimate_openrouter_output_tokens - def price_by_resolution_map(meta: dict[str, Any] | None) -> dict[str, float]: if not isinstance(meta, dict): diff --git a/apps/api/app/services/llm/price_sync.py b/apps/api/app/services/llm/price_sync.py index f6987f48..e0ad79e3 100644 --- a/apps/api/app/services/llm/price_sync.py +++ b/apps/api/app/services/llm/price_sync.py @@ -18,7 +18,7 @@ DEFAULT_IMAGE_RESOLUTION, build_token_price_by_resolution_cny, default_gemini_token_by_resolution, - estimate_output_image_tokens, + estimate_openrouter_output_tokens, ) # Align with usage_log OpenRouter USD→CNY for admin P&L. @@ -207,7 +207,7 @@ def sync_openrouter_catalog_prices(*, only_empty: bool = False) -> dict[str, Any price_str = _fmt_cny(base_cny, digits=4) unit = "output_image_token" usd_raw = usd_tok - base_tok = estimate_output_image_tokens( + base_tok = estimate_openrouter_output_tokens( DEFAULT_IMAGE_RESOLUTION, token_by_resolution=tok_map ) price_meta = { diff --git a/apps/api/app/services/plaza/store.py b/apps/api/app/services/plaza/store.py index ad1b6a2d..62cebcce 100644 --- a/apps/api/app/services/plaza/store.py +++ b/apps/api/app/services/plaza/store.py @@ -137,7 +137,7 @@ def _row_cover_field(row: Any, key: str) -> str | None: def _parse_cover_urls(raw: str | None) -> list[str]: - """Decode cover_image_url — JSON array or legacy single URL.""" + """Decode cover_image_url JSON array.""" text = (raw or "").strip() if not text: return [] @@ -155,8 +155,7 @@ def _parse_cover_urls(raw: str | None) -> list[str]: if len(out) >= 4: break return out - one = _normalize_cover_url(text) - return [one] if one else [] + return [] def _encode_cover_urls(urls: list[str] | None) -> str | None: @@ -177,7 +176,7 @@ def _custom_cover_url(row: Any) -> str | None: def _default_cover_url(row: Any) -> str | None: - """First default cover URL (legacy helpers / repair).""" + """First default cover URL.""" urls = _default_cover_urls(row) return urls[0] if urls else None diff --git a/apps/api/app/services/projects.py b/apps/api/app/services/projects.py index 632bf779..35113f12 100644 --- a/apps/api/app/services/projects.py +++ b/apps/api/app/services/projects.py @@ -206,7 +206,7 @@ def _row_thumb_custom(row: Any) -> bool: def _parse_thumb_entries(raw: str | None) -> list[str]: - """Decode thumbnail_key — JSON array or legacy single COS key / URL.""" + """Decode thumbnail_key JSON array.""" text = (raw or "").strip() if not text: return [] @@ -224,7 +224,7 @@ def _parse_thumb_entries(raw: str | None) -> list[str]: if len(out) >= 4: break return out - return [text] + return [] def _encode_thumb_entries(entries: list[str] | None) -> str | None: @@ -237,8 +237,6 @@ def _encode_thumb_entries(entries: list[str] | None) -> str | None: break if not cleaned: return None - if len(cleaned) == 1: - return cleaned[0] encoded = json.dumps(cleaned, ensure_ascii=False) # Legacy MySQL VARCHAR(512) — prefer a shorter collage over failing PUT /projects. if len(encoded) <= 500: @@ -673,7 +671,7 @@ def _next_thumbnail( """Resolve next thumbnail_key (+ JSON array) and custom flag. Priority: custom client urls/data → keep custom lock → server auto from - document elements (or clear when document has no tiles) → legacy client + document elements (or clear when document has no tiles) → client urls/data → keep existing (only when document was not provided). """ # User-uploaded / explicit custom cover. diff --git a/apps/api/app/services/shares/store.py b/apps/api/app/services/shares/store.py index b9848b2b..744dd279 100644 --- a/apps/api/app/services/shares/store.py +++ b/apps/api/app/services/shares/store.py @@ -481,7 +481,7 @@ def sync_project_share_documents( """Keep linked share snapshots warm when the source project is saved. Preview GET already prefers the live project doc; this keeps document_json - useful for offline / legacy readers. + useful for offline readers. """ uid = (owner_id or "").strip() pid = (project_id or "").strip() diff --git a/apps/api/app/services/storage/__init__.py b/apps/api/app/services/storage/__init__.py index f5814565..58511844 100644 --- a/apps/api/app/services/storage/__init__.py +++ b/apps/api/app/services/storage/__init__.py @@ -1,4 +1,4 @@ -"""Object storage backends — local disk or S3-compatible (OSS/COS).""" +"""Object storage backends — local disk or S3-style (OSS/COS).""" from __future__ import annotations diff --git a/apps/api/app/services/vision/image_edit.py b/apps/api/app/services/vision/image_edit.py index 0df24c99..41c3d96d 100644 --- a/apps/api/app/services/vision/image_edit.py +++ b/apps/api/app/services/vision/image_edit.py @@ -517,7 +517,7 @@ async def decompose_image( Split an image into canvas layers. Returns ``{ image, layers, kind, width, height, engines, warnings }``. - ``image`` is the background layer (compat with existing finishImageProcess). + ``image`` is the background layer. """ if not ocr_available(): raise RuntimeError( diff --git a/apps/api/app/services/vision/ocr.py b/apps/api/app/services/vision/ocr.py index 27437e52..f4a11e56 100644 --- a/apps/api/app/services/vision/ocr.py +++ b/apps/api/app/services/vision/ocr.py @@ -185,7 +185,7 @@ def ocr_image(path: Path, page_index: int = 0, lang: str = "ch") -> list[dict[st """Run OCR and return text blocks in image pixel coordinates.""" engine = get_ocr(lang=lang) - # paddleocr 3.x: prefer predict(); ocr() is deprecated and may share the same path + # paddleocr 3.x: prefer predict(); ocr() may share the same path if hasattr(engine, "predict"): result = engine.predict(str(path)) blocks: list[dict[str, Any]] = [] diff --git a/apps/api/app/services/wallet/billing.py b/apps/api/app/services/wallet/billing.py index 039336e9..a974dd57 100644 --- a/apps/api/app/services/wallet/billing.py +++ b/apps/api/app/services/wallet/billing.py @@ -206,10 +206,6 @@ def load_billing_markup(rules: dict[str, Any] | None = None) -> float: return _as_float(_rules_map(rules).get(RULE_MARKUP), DEFAULT_MARKUP) -def load_billing_settings(rules: dict[str, Any] | None = None) -> tuple[float, float]: - """Return (markup, unused_legacy). Second value kept for call-site compatibility.""" - return load_billing_markup(rules), 1.0 - def load_credit_policy(rules: dict[str, Any] | None = None) -> CreditPolicySchema: """Public credit unit + BYOK agent fee (no host markup fields).""" @@ -308,7 +304,7 @@ def credits_per_cny() -> float: def tokens_to_credits(billed_tokens: int) -> int: - """Convert billed LLM tokens (after markup) into wallet 积分 (legacy).""" + """Convert billed LLM tokens (after markup) into wallet 积分.""" n = max(0, int(billed_tokens or 0)) if n <= 0: return 0 @@ -321,7 +317,7 @@ def charge_from_llm_tokens( rules: dict[str, Any] | None = None, markup: float | None = None, ) -> int: - """Convert provider LLM token usage into wallet 积分 (legacy fallback).""" + """Convert provider LLM token usage into wallet 积分 (OSS fallback when remote quote unavailable).""" tokens = max(0, int(actual_tokens or 0)) if tokens <= 0: return 0 @@ -406,7 +402,7 @@ def resolve_capture_credits( """Decide capture credits for settle. Prefer optional remote quote (credits only). Fallbacks: - BYOK agent fee → OSS TaskPricing/legacy hybrid. + BYOK agent fee → OSS TaskPricing/token fallback hybrid. Returns ``(credits, source)``. """ imgs = max(0, int(images_hydrated or 0)) @@ -447,14 +443,14 @@ def resolve_capture_credits( except Exception: pass - # OSS / Intelligence-down: TaskPricing band + legacy token/image as transitional. - legacy = charge_from_llm_tokens(tokens, rules=rules) + extra_img + # OSS / Intelligence-down: TaskPricing band + token fallback. + fallback = charge_from_llm_tokens(tokens, rules=rules) + extra_img sheet = resolve_task_pricing(run_mode, rules=rules) lo = max(0, int(sheet.base_credit or 0)) hi = max(lo, int(sheet.estimate_credits_high() or 0)) - if legacy <= 0: + if fallback <= 0: return max(1, lo or hi or 1), "task_pricing_floor" - capped = max(lo, min(legacy, max(hi * 3, hi, 1))) + capped = max(lo, min(fallback, max(hi * 3, hi, 1))) return capped, "oss_hybrid" @@ -521,21 +517,17 @@ def settle_token_hold( except ValueError: total = hold_n - # Align with protocol lifecycle capture envelope (wallet already mutated). try: - from app.services.wallet.lifecycle import capture_task_credits + from app.services.wallet.lifecycle import settle_task_credits - capture_task_credits( + settle_task_credits( user_id=uid, - hold=hold_n, - capture=total, + reserved=hold_n, + actual=total, task_id=task_id, detail=f"{note}:{source}", mutate_wallet=False, ) - except TypeError: - # Older capture_task_credits without mutate_wallet — skip envelope. - pass except Exception: pass return total diff --git a/apps/api/app/services/wallet/card_keys.py b/apps/api/app/services/wallet/card_keys.py index a9afa511..07525729 100644 --- a/apps/api/app/services/wallet/card_keys.py +++ b/apps/api/app/services/wallet/card_keys.py @@ -1,17 +1,16 @@ """Card-key generation, hashing, and redemption. Kinds: - - token: top up chat Token balance - - credit: top up image 积分 balance - - plan: sets membership + monthly Token gift (+ monthly 积分 gift) + - credit: top up unified 积分 + - plan: sets membership + monthly 积分 gift Pipeline: 1. Local random plaintext (XXXXX-XXXXX-XXXXX-XXXXX, no ambiguous chars) 2. hash = HMAC-SHA256(plaintext, CARD_KEY_SALT) 3. DB stores hash + kind/plan/tokens + status + expires_at (never plaintext) - 4. Redeem: hash → lookup → credit tokens and/or image_credits and/or set plan + 4. Redeem: hash → lookup → credit 积分 and/or set plan -Format v2: 4×5 segments (20 chars). Legacy short keys are deleted on upgrade. +Format v2: 4×5 segments (20 chars). """ from __future__ import annotations @@ -61,9 +60,7 @@ "ultra": 0, } VALID_PLAN_IDS = frozenset(PLAN_CREDITS.keys()) -# ``token`` kept as alias of ``credit`` for old admin clients. -VALID_KINDS = frozenset({"token", "credit", "plan"}) -# Align with services.wallet.billing.TOKENS_PER_CREDIT (legacy million-face → 积分). +VALID_KINDS = frozenset({"credit", "plan"}) TOKENS_PER_CREDIT = 15_000 # Membership length after redeeming a plan card key (calendar days). PLAN_DURATION_DAYS = 30 @@ -126,7 +123,7 @@ def hash_card_key(plaintext: str, salt: str | None = None) -> str: def ensure_card_keys_v2() -> None: - """One-shot: wipe all legacy short/SHA256 keys (format + hash changed).""" + """One-shot: wipe all short/SHA256 keys (format + hash changed).""" global _v2_ready if _v2_ready: return @@ -154,16 +151,9 @@ def normalize_plan_id(raw: Any) -> str: return "free" -def _normalize_topup_amount(kind: str, amount: int) -> int: - """Convert legacy Token-face amounts into 积分 when admin still sends millions.""" - amt = int(amount or 0) - if amt <= 0: - return amt - if kind == "token" and amt >= TOKENS_PER_CREDIT: - from math import ceil - - return max(1, int(ceil(amt / float(TOKENS_PER_CREDIT)))) - return amt +def _normalize_topup_amount(amount: int) -> int: + """Normalize top-up amounts to unified 积分.""" + return int(amount or 0) def resolve_generate_spec( @@ -174,12 +164,12 @@ def resolve_generate_spec( ) -> tuple[str, int, str | None]: """ Normalize generate inputs → (kind, amount, plan_id). - Top-ups are stored as kind=credit (积分). Legacy kind=token is aliased. + Top-ups are stored as kind=credit (积分). ``tokens`` column on card_keys stores the 积分 face value. """ k = str(kind or "credit").strip().lower() if k not in VALID_KINDS: - raise ValueError("kind must be token, credit, or plan") + raise ValueError("kind must be credit or plan") if k == "plan": pid = normalize_plan_id(plan_id) if pid not in VALID_PLAN_IDS: @@ -190,10 +180,9 @@ def resolve_generate_spec( amt = int(plan_credit_grant(pid) or PLAN_CREDITS[pid]) return "plan", amt, pid - amt = _normalize_topup_amount(k, int(tokens or 0)) + amt = _normalize_topup_amount(int(tokens or 0)) if amt <= 0: raise ValueError("amount must be > 0 for credit keys") - # Persist as credit; token is a deprecated alias. return "credit", amt, None @@ -343,7 +332,7 @@ def list_card_keys(*, status: str | None = None, limit: int = 200) -> list[dict[ db_rows = crud.list_card_keys(session=session, status=status, limit=limit) out: list[dict[str, Any]] = [] for row in db_rows: - kind = str(row.kind or "token").strip().lower() or "token" + kind = str(row.kind or "credit").strip().lower() or "credit" plan_raw = row.plan_id plan_id = str(plan_raw).strip().lower() if plan_raw else None out.append( @@ -351,7 +340,7 @@ def list_card_keys(*, status: str | None = None, limit: int = 200) -> list[dict[ kid=row.id, code=None, tokens=int(row.tokens or 0), - kind=kind if kind in VALID_KINDS else "token", + 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), created_at=float(row.created_at), @@ -425,9 +414,9 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: if expires is not None and float(expires) < now: raise RedeemError("expired", "Card key expired") - kind = str(row.kind or "token").strip().lower() or "token" + kind = str(row.kind or "credit").strip().lower() or "credit" if kind not in VALID_KINDS: - kind = "token" + raise RedeemError("invalid_kind", "Card key kind is invalid") plan_raw = row.plan_id plan_id = str(plan_raw).strip().lower() if plan_raw else None if kind == "plan" and plan_id not in VALID_PLAN_IDS: @@ -465,9 +454,7 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: gift = int(PLAN_CREDITS.get(plan_id) or 0) amount = gift else: - gift = _normalize_topup_amount( - "token" if kind == "token" else "credit", amount - ) + gift = _normalize_topup_amount(amount) amount = gift if gift <= 0: raise RedeemError("invalid_amount", "Card key amount invalid") @@ -476,7 +463,6 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: if bal: bal.tokens = next_credits - bal.image_credits = 0 bal.plan_id = next_plan bal.plan_expires_at = next_expires bal.updated_at = now @@ -486,7 +472,6 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: UserBalance( user_id=user_id, tokens=next_credits, - image_credits=0, plan_id=next_plan, plan_expires_at=next_expires, updated_at=now, @@ -527,10 +512,8 @@ def redeem_card_key(user_id: str, plaintext: str) -> dict[str, Any]: "kind": "plan" if kind == "plan" else "credit", "creditsAdded": gift, "tokensAdded": gift, - "imageCreditsAdded": 0, "credits": next_credits, "tokens": next_credits, - "imageCredits": 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 fa2433a4..b4d129fa 100644 --- a/apps/api/app/services/wallet/db.py +++ b/apps/api/app/services/wallet/db.py @@ -1,9 +1,4 @@ -"""Wallet balances / ledger — unified 积分 stored in ``tokens`` column. - -Legacy ``image_credits`` is migrated into ``tokens`` once -(``wallet_unified_credits_v1``), then kept at 0. API still exposes -``credits`` / ``tokens`` / ``imageCredits`` (aliases of the same balance). -""" +"""Wallet balances / ledger — unified 积分 stored in ``tokens`` column.""" from __future__ import annotations @@ -11,76 +6,21 @@ from app.services.db import init_schema -_UNIFIED_MIGRATION_ID = "wallet_unified_credits_v1" _SCALE_X10_MIGRATION_ID = "wallet_credits_scale_x10_v1" -# Historical: used only by the first unified migration (legacy Token → 积分). -_LEGACY_TOKENS_PER_CREDIT = 30_000 -_unified_ready = False _scale_x10_ready = False def init_wallet_db() -> None: init_schema() - ensure_unified_credits_migration() ensure_credits_scale_x10_migration() -def ensure_unified_credits_migration() -> None: - """One-shot: tokens(旧 Token) / 30000 + image_credits → 统一积分 in tokens.""" - global _unified_ready - if _unified_ready: - return - init_schema() - import time - from math import ceil - - from sqlmodel import Session - - from app import crud - from app.core.db import engine - - now = time.time() - with Session(engine) as session: - try: - crud.ensure_app_migrations_table(session=session) - except Exception: - pass - if crud.app_migration_applied( - session=session, migration_id=_UNIFIED_MIGRATION_ID - ): - _unified_ready = True - return - for r in crud.list_all_user_balances(session=session): - uid = str(r.user_id or "") - if not uid: - continue - old_tok = int(r.tokens or 0) - old_img = int(r.image_credits or 0) - # Large ``tokens`` = legacy LLM units; small = already 积分-sized. - if old_tok >= _LEGACY_TOKENS_PER_CREDIT: - merged = int(ceil(old_tok / float(_LEGACY_TOKENS_PER_CREDIT))) + old_img - else: - merged = old_tok + old_img - r.tokens = max(0, merged) - r.image_credits = 0 - r.updated_at = now - session.add(r) - crud.mark_app_migration( - session=session, - migration_id=_UNIFIED_MIGRATION_ID, - applied_at=now, - commit=False, - ) - session.commit() - _unified_ready = True - - def ensure_credits_scale_x10_migration() -> None: """One-shot: multiply wallet balances ×10 to match the new display scale.""" global _scale_x10_ready if _scale_x10_ready: return - ensure_unified_credits_migration() + init_schema() import time from sqlmodel import Session @@ -114,17 +54,14 @@ def ensure_credits_scale_x10_migration() -> None: __all__ = [ "init_wallet_db", - "ensure_unified_credits_migration", "ensure_user_balance", "get_user_tokens", - "get_user_image_credits", "get_user_plan", "get_wallet", "list_ledger", "list_ledger_page", "spend_tokens", "credit_tokens", - "spend_image_credits", "is_wallet_billing_enabled", "FREE_DAILY_LIMIT", "free_daily_remaining", @@ -154,7 +91,7 @@ def ensure_user_balance(user_id: str, *, starting_tokens: int = 0) -> int: from app import crud from app.core.db import engine - ensure_unified_credits_migration() + init_wallet_db() uid = (user_id or "").strip() if not uid: return 0 @@ -166,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. ``tokens`` / ``imageCredits`` / ``credits`` are the same balance.""" + """Unified 积分 + plan. ``credits`` and ``tokens`` are the same balance.""" from sqlmodel import Session from app import crud @@ -178,7 +115,6 @@ def get_wallet(user_id: str) -> dict[str, Any]: return { "credits": 0, "tokens": 0, - "imageCredits": 0, "planId": "free", "planExpiresAt": None, "planLocked": False, @@ -186,20 +122,19 @@ def get_wallet(user_id: str) -> dict[str, Any]: } import time - ensure_unified_credits_migration() + init_wallet_db() now = time.time() with Session(engine) as session: row = crud.ensure_user_balance_row(session=session, user_id=uid, starting_tokens=0) credits = int(row.tokens or 0) - stored = _normalize_plan(row.plan_id) + stored = normalize_plan(row.plan_id) expires_at = float(row.plan_expires_at) if row.plan_expires_at is not None else None - active = _plan_active(stored, expires_at, now=now) + active = plan_is_active(stored, expires_at, now=now) effective = stored if (stored == "free" or active) else "free" return { "credits": credits, "tokens": credits, - "imageCredits": credits, "planId": effective, "planStored": stored, "planExpiresAt": expires_at, @@ -221,10 +156,6 @@ def normalize_plan(raw: Any) -> str: return "free" -# Back-compat alias for internal callers. -_normalize_plan = normalize_plan - - def plan_is_active(plan_id: str, expires_at: float | None, *, now: float | None = None) -> bool: """Paid plan is active only while plan_expires_at is in the future.""" pid = normalize_plan(plan_id) @@ -234,9 +165,6 @@ def plan_is_active(plan_id: str, expires_at: float | None, *, now: float | None return float(expires_at) > t -_plan_active = plan_is_active - - def get_user_plan(user_id: str) -> str: """Effective membership plan (expired paid → free).""" snap = get_wallet(user_id) @@ -303,7 +231,6 @@ def consume_free_daily_quota(user_id: str, *, limit: int = FREE_DAILY_LIMIT) -> bal = UserBalance( user_id=uid, tokens=0, - image_credits=0, plan_id="free", plan_expires_at=None, updated_at=now, @@ -341,7 +268,7 @@ def spend_tokens( from app.core.db import engine from app.models import UserBalance - ensure_unified_credits_migration() + init_wallet_db() uid = (user_id or "").strip() amt = int(amount) if not uid: @@ -364,7 +291,6 @@ def spend_tokens( if int(row.tokens) < amt: raise ValueError("insufficient_tokens") row.tokens = next_bal - row.image_credits = 0 row.updated_at = now session.add(row) else: @@ -372,7 +298,6 @@ def spend_tokens( UserBalance( user_id=uid, tokens=next_bal, - image_credits=0, plan_id="free", updated_at=now, ) @@ -397,7 +322,7 @@ def credit_tokens(user_id: str, amount: int, detail: str = "") -> int: from app.core.db import engine from app.models import UserBalance - ensure_unified_credits_migration() + init_wallet_db() uid = (user_id or "").strip() amt = int(amount) if not uid: @@ -414,7 +339,6 @@ def credit_tokens(user_id: str, amount: int, detail: str = "") -> int: next_bal = prev + amt if row: row.tokens = next_bal - row.image_credits = 0 row.updated_at = now session.add(row) else: @@ -422,7 +346,6 @@ def credit_tokens(user_id: str, amount: int, detail: str = "") -> int: UserBalance( user_id=uid, tokens=next_bal, - image_credits=0, plan_id="free", updated_at=now, ) @@ -439,23 +362,8 @@ def credit_tokens(user_id: str, amount: int, detail: str = "") -> int: return next_bal -def get_user_image_credits(user_id: str) -> int: - """Alias of unified 积分 (legacy name).""" - return get_user_tokens(user_id) - - -def spend_image_credits(user_id: str, amount: int, detail: str = "") -> int: - """Alias: deduct unified 积分 (maps insufficient_image_credits → same raise).""" - try: - return spend_tokens(user_id, amount, detail=detail or "AI image") - except ValueError as e: - if str(e) == "insufficient_tokens": - raise ValueError("insufficient_image_credits") from e - raise - - def list_ledger(user_id: str, limit: int = 100) -> list[dict[str, Any]]: - """Legacy helper — returns a flat list (used after redeem).""" + """Return a flat ledger list (used after redeem).""" page = list_ledger_page(user_id, page=1, page_size=limit, kind="all") return page["items"] diff --git a/apps/api/app/services/wallet/lifecycle.py b/apps/api/app/services/wallet/lifecycle.py index 093407bc..78ce3a67 100644 --- a/apps/api/app/services/wallet/lifecycle.py +++ b/apps/api/app/services/wallet/lifecycle.py @@ -2,8 +2,6 @@ Wraps wallet spend/credit at the **credit** layer (design holds). Emits Billing Protocol event shapes. Commercial packs / margin stay private. - -Stripe-shaped aliases: authorize(=reserve), capture(=charge). """ from __future__ import annotations @@ -118,21 +116,6 @@ def reserve_task_credits( return {"billingEvent": ev.model_dump(), "taskCost": task.model_dump(), "reserved": n} -def authorize_task_credits( - *, - user_id: str, - credits: int, - task_id: str = "", - detail: str = "", -) -> dict[str, Any]: - """Stripe-shaped alias for ``reserve_task_credits``.""" - out = reserve_task_credits( - user_id=user_id, credits=credits, task_id=task_id, detail=detail - ) - out["lifecycleStage"] = "authorize" - return out - - def settle_task_credits( *, user_id: str, @@ -207,33 +190,3 @@ def settle_task_credits( "released": released, "settledAt": time.time(), } - - -def capture_task_credits( - *, - user_id: str, - reserved: int | None = None, - actual: int | None = None, - hold: int | None = None, - capture: int | None = None, - task_id: str = "", - detail: str = "", - pricing_version_ids: list[str] | None = None, - usage_event_ids: list[str] | None = None, - mutate_wallet: bool = True, -) -> dict[str, Any]: - """Stripe-shaped alias for ``settle_task_credits`` (capture + release).""" - reserved_n = int(reserved if reserved is not None else (hold or 0)) - actual_n = int(actual if actual is not None else (capture or 0)) - out = settle_task_credits( - user_id=user_id, - reserved=reserved_n, - actual=actual_n, - task_id=task_id, - detail=detail, - pricing_version_ids=pricing_version_ids, - usage_event_ids=usage_event_ids, - mutate_wallet=mutate_wallet, - ) - out["lifecycleStage"] = "capture" - return out diff --git a/apps/api/scripts/gen_card_keys.py b/apps/api/scripts/gen_card_keys.py index d8cdf397..01efd6f6 100644 --- a/apps/api/scripts/gen_card_keys.py +++ b/apps/api/scripts/gen_card_keys.py @@ -41,8 +41,8 @@ def main() -> int: "--kind", type=str, default="credit", - choices=("credit", "token", "plan"), - help="credit = 积分 top-up (token is legacy alias); plan = membership + credits", + choices=("credit", "plan"), + help="credit = 积分 top-up; plan = membership + credits", ) parser.add_argument( "--plan-id", @@ -54,7 +54,7 @@ def main() -> int: "--tokens", type=int, default=0, - help="Credits per key (required for token; optional for plan — uses catalog default)", + help="Credits per key (required for credit; optional for plan — uses catalog default)", ) parser.add_argument( "--expires-days", @@ -73,7 +73,7 @@ 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 in ("credit", "token") and args.tokens <= 0: + if args.kind == "credit" and args.tokens <= 0: print("error: --tokens 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"): diff --git a/apps/api/scripts/gen_oss_prompt_packs.py b/apps/api/scripts/gen_oss_prompt_packs.py index ea0d424a..2f0172e8 100644 --- a/apps/api/scripts/gen_oss_prompt_packs.py +++ b/apps/api/scripts/gen_oss_prompt_packs.py @@ -124,7 +124,7 @@ ), "agent.prompt.react_system": ( "ReAct system (OSS)", - ["legacy"], + ["decide"], """You are a design-canvas agent. Process: brief (goal/size) → plan (steps) → act (tools) → self-check (hierarchy/margins). Think briefly in thought; prefer concrete canvas ops over long essays.""", diff --git a/apps/api/seeds/agents/profiles/design.canvas.yaml b/apps/api/seeds/agents/profiles/design.canvas.yaml index 8b560161..127e6088 100644 --- a/apps/api/seeds/agents/profiles/design.canvas.yaml +++ b/apps/api/seeds/agents/profiles/design.canvas.yaml @@ -1,6 +1,6 @@ # Agent Profile — design canvas (live default). # Kernel reads this for Voice (stage→pack) and Policy (routing/runtime → KV overlay). -# Topology/contracts/capabilities are declared for forward-compat (P2+). +# Topology/contracts/capabilities are declared for later phases (P2+). # # Boundary (hard): # Agent kernel = control loop, tool scheduling, canvas R/W, max rounds / reflect, diff --git a/apps/api/seeds/canvas_actions_seed.json b/apps/api/seeds/canvas_actions_seed.json index 4a0fadfe..ffd53565 100644 --- a/apps/api/seeds/canvas_actions_seed.json +++ b/apps/api/seeds/canvas_actions_seed.json @@ -82,6 +82,92 @@ "_rev": "shape-filltype-native-2" } }, + { + "op_key": "create_path", + "kind": "create", + "label": "Create path", + "sort_order": 22, + "model_hint": "Add a path/pen polyline as a shape node. Args: x,y,width,height, points=[[x,y],...] (>=2), closed?, stroke?, borderWidth?. For freehand calligraphy use create_shape shapeType=pencil instead.", + "args_schema": { + "x": "number", + "y": "number", + "width": "number", + "height": "number", + "points": "number[][]", + "closed": "boolean?", + "stroke": "string?", + "borderWidth": "number?", + "fill": "string?", + "name": "string?" + } + }, + { + "op_key": "edit_path_points", + "kind": "mutate", + "label": "Edit path points", + "sort_order": 23, + "model_hint": "Replace path/pen/pencil geometry on an existing node. Args: nodeId, points=[[x,y],...] (>=2), closed?.", + "args_schema": { + "nodeId": "string", + "points": "number[][]", + "closed": "boolean?" + } + }, + { + "op_key": "append_path_points", + "kind": "mutate", + "label": "Append path points", + "sort_order": 24, + "model_hint": "Append points to an existing path/pen/pencil node (continue a stroke). Args: nodeId, points=[[x,y],...] (>=1).", + "args_schema": { + "nodeId": "string", + "points": "number[][]", + "closed": "boolean?" + } + }, + { + "op_key": "simplify_path", + "kind": "mutate", + "label": "Simplify path", + "sort_order": 25, + "model_hint": "Reduce path/pen/pencil vertices (Ramer–Douglas–Peucker). Args: nodeId, tolerance? (px, default 2).", + "args_schema": { + "nodeId": "string", + "tolerance": "number?" + } + }, + { + "op_key": "apply_brush_preset", + "kind": "mutate", + "label": "Apply brush preset", + "sort_order": 26, + "model_hint": "Set pencil/path stroke preset. Args: nodeIds, preset=ink|pencil|marker|calligraphy|brush.", + "args_schema": { + "nodeIds": "string[]", + "preset": "ink|pencil|marker|calligraphy|brush" + } + }, + { + "op_key": "smooth_path", + "kind": "mutate", + "label": "Smooth path", + "sort_order": 27, + "model_hint": "Chaikin-smooth a path/pen/pencil. Args: nodeId, iterations? (1-4, default 1).", + "args_schema": { + "nodeId": "string", + "iterations": "number?" + } + }, + { + "op_key": "close_path", + "kind": "mutate", + "label": "Close path", + "sort_order": 28, + "model_hint": "Close an open path/pen/pencil (writes Z). Args: nodeId. Needs at least 3 points.", + "args_schema": { + "nodeId": "string" + } + }, { "op_key": "create_text", "kind": "create", @@ -197,6 +283,42 @@ "_rev": "must-create-frame-3" } }, + { + "op_key": "duplicate_frame", + "kind": "frame", + "label": "Duplicate frame", + "sort_order": 65, + "model_hint": "Clone an artboard (size/background). Args: frameId, dx?, dy?, name?, includeChildren? (default false; true copies bound nodes).", + "args_schema": { + "frameId": "string", + "dx": "number?", + "dy": "number?", + "name": "string?", + "includeChildren": "boolean?" + } + }, + { + "op_key": "reorder_frames", + "kind": "frame", + "label": "Reorder frames", + "sort_order": 66, + "model_hint": "Z-order artboards in the world stack. Args: frameIds, action=front|back|forward|backward.", + "args_schema": { + "frameIds": "string[]", + "action": "front|back|forward|backward" + } + }, + { + "op_key": "fit_frame_to_content", + "kind": "frame", + "label": "Fit frame to content", + "sort_order": 67, + "model_hint": "Resize/move an artboard to wrap its bound children. Args: frameId, padding? (px, default 24).", + "args_schema": { + "frameId": "string", + "padding": "number?" + } + }, { "op_key": "delete_nodes", "kind": "delete", @@ -207,27 +329,73 @@ "nodeIds": "string[]" } }, + { + "op_key": "hide_nodes", + "kind": "mutate", + "label": "Hide nodes", + "sort_order": 72, + "model_hint": "Hide or show scene nodes. Args: nodeIds, hidden? (default true).", + "args_schema": { + "nodeIds": "string[]", + "hidden": "boolean?" + } + }, { "op_key": "update_frame", "kind": "frame", "label": "Update frame", "sort_order": 80, - "model_hint": "Update frame size/name/background/lock. Args: frameId|id (must match FOCUS_FRAME_ID when set), width?, height?, name?, backgroundColor?, locked? (boolean — prevent moving/resizing the artboard). When FOCUS_FRAME_ID is present, always use that id — never retarget by name.", + "model_hint": "Update frame size/name/background/lock/clip. Args: frameId (must match FOCUS_FRAME_ID when set), width?, height?, name?, backgroundColor?, locked?, hidden?, clipContent?. When FOCUS_FRAME_ID is present, always use that id — never retarget by name.", "args_schema": { "frameId": "string", "width": "number?", "height": "number?", "name": "string?", "backgroundColor": "string?", + "locked": "boolean?", + "hidden": "boolean?", + "clipContent": "boolean?" + } + }, + { + "op_key": "lock_frames", + "kind": "frame", + "label": "Lock frames", + "sort_order": 81, + "model_hint": "Lock or unlock artboards (prevent move/resize). Args: frameIds, locked? (default true).", + "args_schema": { + "frameIds": "string[]", "locked": "boolean?" } }, + { + "op_key": "hide_frames", + "kind": "frame", + "label": "Hide frames", + "sort_order": 82, + "model_hint": "Hide or show artboards. Args: frameIds, hidden? (default true).", + "args_schema": { + "frameIds": "string[]", + "hidden": "boolean?" + } + }, + { + "op_key": "clip_frames", + "kind": "frame", + "label": "Clip frames", + "sort_order": 83, + "model_hint": "Clip artboard contents to the frame rect. Args: frameIds, clipContent? (default true).", + "args_schema": { + "frameIds": "string[]", + "clipContent": "boolean?" + } + }, { "op_key": "delete_frame", "kind": "frame", "label": "Delete frame", "sort_order": 90, - "model_hint": "Delete a frame. Args: frameId|id from SCENE_FRAMES. Destructive — first turn must ask confirmation via choice_ui (mode=confirm, apply+dismiss) or legacy reply+choices; emit this op only after user confirms. Never put ids in reply.", + "model_hint": "Delete a frame. Args: frameId|id from SCENE_FRAMES. Destructive — first turn must ask confirmation via choice_ui (mode=confirm, apply+dismiss); emit this op only after user confirms. Never put ids in reply.", "args_schema": { "frameId": "string" } @@ -309,6 +477,38 @@ "flipY": "boolean?" } }, + { + "op_key": "rotate_nodes", + "kind": "arrange", + "label": "Rotate nodes", + "sort_order": 165, + "model_hint": "Set absolute rotation in degrees. Args: nodeIds, rotation.", + "args_schema": { + "nodeIds": "string[]", + "rotation": "number" + } + }, + { + "op_key": "bind_nodes_to_frame", + "kind": "arrange", + "label": "Bind nodes to frame", + "sort_order": 166, + "model_hint": "Bind scene nodes to an artboard (attrs.frameId). Args: nodeIds, frameId.", + "args_schema": { + "nodeIds": "string[]", + "frameId": "string" + } + }, + { + "op_key": "unbind_nodes", + "kind": "arrange", + "label": "Unbind nodes", + "sort_order": 167, + "model_hint": "Clear artboard binding on nodes. Args: nodeIds.", + "args_schema": { + "nodeIds": "string[]" + } + }, { "op_key": "boolean_op", "kind": "arrange", @@ -349,6 +549,26 @@ "zoom": "number?" } }, + { + "op_key": "set_active_tool", + "kind": "canvas", + "label": "Active tool", + "sort_order": 191, + "model_hint": "Switch the editor tool. Args: tool=select|pan|frame|text|shape|image|pen|pencil. Prefer document ops (create_path/create_shape) over leaving the user in a drawing tool.", + "args_schema": { + "tool": "select|pan|frame|text|shape|image|pen|pencil" + } + }, + { + "op_key": "set_grid", + "kind": "canvas", + "label": "Grid snap", + "sort_order": 192, + "model_hint": "Toggle canvas grid snap. Args: enabled (boolean).", + "args_schema": { + "enabled": "boolean" + } + }, { "op_key": "image_process", "kind": "image", @@ -518,9 +738,115 @@ }, "update_frame": { "must_contain": [ - "locked" + "locked", + "hidden", + "clipContent" + ], + "stale_if_contains": [ + "\"clip\"", + "clipped" + ] + }, + "create_path": { + "must_contain": [ + "points" + ], + "stale_if_contains": [ + "points|path", + "SVG d" + ] + }, + "edit_path_points": { + "must_contain": [ + "points" + ], + "stale_if_contains": [ + "points|path" + ] + }, + "apply_brush_preset": { + "must_contain": [ + "nodeIds", + "preset" + ], + "stale_if_contains": [ + "brushPreset", + "nodeId" + ] + }, + "duplicate_frame": { + "must_contain": [ + "includeChildren" + ], + "stale_if_contains": [ + "copyChildren" + ] + }, + "lock_frames": { + "must_contain": [ + "frameIds" + ], + "stale_if_contains": [ + "frameIds|frameId" + ] + }, + "hide_frames": { + "must_contain": [ + "frameIds", + "hidden" ], "stale_if_contains": [] + }, + "clip_frames": { + "must_contain": [ + "clipContent" + ], + "stale_if_contains": [ + "clipped", + "\"clip\"" + ] + }, + "hide_nodes": { + "must_contain": [ + "nodeIds" + ], + "stale_if_contains": [ + "nodeId" + ] + }, + "rotate_nodes": { + "must_contain": [ + "rotation" + ], + "stale_if_contains": [ + "delta", + "angle" + ] + }, + "bind_nodes_to_frame": { + "must_contain": [ + "nodeIds", + "frameId" + ], + "stale_if_contains": [] + }, + "set_active_tool": { + "must_contain": [ + "tool" + ], + "stale_if_contains": [ + "Aliases", + "hand→pan", + "brush→pencil" + ] + }, + "set_grid": { + "must_contain": [ + "enabled" + ], + "stale_if_contains": [ + "action" + ] } } } diff --git a/apps/api/seeds/design_prompt_packs/_index.json b/apps/api/seeds/design_prompt_packs/_index.json index b37d9192..a49b3ed4 100644 --- a/apps/api/seeds/design_prompt_packs/_index.json +++ b/apps/api/seeds/design_prompt_packs/_index.json @@ -172,9 +172,9 @@ "group": "agent_prompt", "type": "system", "usedBy": [ - "legacy" + "decide" ], - "file": "stages/legacy.md" + "file": "stages/decide.md" }, { "kind": "agent.prompt.chat_fallback", @@ -286,9 +286,9 @@ "group": "agent_prompt", "type": "system", "usedBy": [ - "legacy" + "decide" ], - "file": "stages/legacy.md" + "file": "stages/decide.md" }, { "kind": "agent.prompt.paint_retry", @@ -344,7 +344,7 @@ "usedBy": [ "orchestrator" ], - "file": "stages/legacy.md" + "file": "stages/decide.md" }, { "kind": "agent.prompt.pending_skills", @@ -401,9 +401,9 @@ "group": "agent_prompt", "type": "system", "usedBy": [ - "legacy" + "decide" ], - "file": "stages/legacy.md" + "file": "stages/decide.md" }, { "kind": "agent.prompt.prompt_pack_inject_header", @@ -429,7 +429,7 @@ "group": "agent_prompt", "type": "system", "usedBy": [ - "legacy" + "decide" ], "file": "stages/decide.md" }, diff --git a/apps/api/seeds/design_prompt_packs/stages/decide.md b/apps/api/seeds/design_prompt_packs/stages/decide.md index e3cc8fbf..90cc6ee5 100644 --- a/apps/api/seeds/design_prompt_packs/stages/decide.md +++ b/apps/api/seeds/design_prompt_packs/stages/decide.md @@ -152,3 +152,58 @@ Agent mode: decide and finish the task yourself; do not ask the user. - Do not reply "preparing to add…" with empty tool_ops. - Do not invent tool names or skill_key; use catalog name/op_key / skill_key. - No markdown fences; reply is shown by the frontend alone. + + +# Identity +- You are the Recombyn design-canvas Agent. +- User-visible replies: match the user's language; keep them short and professional. + +# Instructions +- Tool loop: state intent briefly, then emit canvas tools. +- Local edits use ops from TOOL_DETAILS / Tools catalog; follow SKILL_DETAILS when skills are loaded. +- Never delete_nodes unless the user explicitly asks to delete. +- Do not invent tool names; finish with a short summary in the user's language. + +# Examples +- "Make the title blue" → recolor only that text; do not reflow the whole board. +- "Make a poster" → need_skills by catalog when_to_use, then tool_ops; ask if critical copy is missing. +- "Match this reference style" → need_skills by catalog when_to_use, then ops. + + +# Identity +- You plan canvas work for the design Agent (plan only — no tool_ops). + +# Instructions +Return ONE JSON object: {"plan":["...","..."]} +- 3–5 short steps (each ≤16 words). +- Concrete canvas actions only (frame / title / color / image / polish …). +- Name the medium when useful (vector shell / gen image ×N / canvas title); if the user forbids image gen, do not schedule it. +- No tool_ops, no schema talk, no markdown. + +# Examples +- {"plan":["Create vertical frame","Gen hero visual","Write title/subtitle on canvas","Align and polish"]} +- {"plan":["Create web frame","Vector nav shell","Gen hero image","Write title + CTA"]} +- When image gen is forbidden: {"plan":["Create frame","Vector shell + icons","Write copy on canvas","Align and polish"]} + + +# Identity +- You are a server-side tools Agent (not the canvas editor). + +# Instructions +- Use only backend-executable tools such as generate_image. +- Canvas node edits are handled elsewhere; do not pretend you changed the canvas. + +# Examples +- User wants artwork → call generate_image. +- User wants to move a layer → say this node does not edit the canvas. + + +# Identity +- You perform local layer edits on the canvas via tool_ops. + +# Instructions +- Return JSON with an ops array; change only related nodes; do not redesign the whole board. +- Do not invent node ids that are not in SCENE. + +# Examples +- Input: "Make the title red" → ops only update that text fill. diff --git a/apps/api/seeds/design_prompt_packs/stages/legacy.md b/apps/api/seeds/design_prompt_packs/stages/legacy.md deleted file mode 100644 index 8dd12794..00000000 --- a/apps/api/seeds/design_prompt_packs/stages/legacy.md +++ /dev/null @@ -1,56 +0,0 @@ -` (not by ## headings). --> - - -# Identity -- You are the Recombyn design-canvas Agent. -- User-visible replies: match the user's language; keep them short and professional. - -# Instructions -- Tool loop: state intent briefly, then emit canvas tools. -- Local edits use ops from TOOL_DETAILS / Tools catalog; follow SKILL_DETAILS when skills are loaded. -- Never delete_nodes unless the user explicitly asks to delete. -- Do not invent tool names; finish with a short summary in the user's language. - -# Examples -- "Make the title blue" → recolor only that text; do not reflow the whole board. -- "Make a poster" → need_skills by catalog when_to_use, then tool_ops; ask if critical copy is missing. -- "Match this reference style" → need_skills by catalog when_to_use, then ops. - - -# Identity -- You plan canvas work for the design Agent (plan only — no tool_ops). - -# Instructions -Return ONE JSON object: {"plan":["...","..."]} -- 3–5 short steps (each ≤16 words). -- Concrete canvas actions only (frame / title / color / image / polish …). -- Name the medium when useful (vector shell / gen image ×N / canvas title); if the user forbids image gen, do not schedule it. -- No tool_ops, no schema talk, no markdown. - -# Examples -- {"plan":["Create vertical frame","Gen hero visual","Write title/subtitle on canvas","Align and polish"]} -- {"plan":["Create web frame","Vector nav shell","Gen hero image","Write title + CTA"]} -- When image gen is forbidden: {"plan":["Create frame","Vector shell + icons","Write copy on canvas","Align and polish"]} - - -# Identity -- You are a server-side tools Agent (not the canvas editor). - -# Instructions -- Use only backend-executable tools such as generate_image. -- Canvas node edits are handled elsewhere; do not pretend you changed the canvas. - -# Examples -- User wants artwork → call generate_image. -- User wants to move a layer → say this node does not edit the canvas. - - -# Identity -- You perform local layer edits on the canvas via tool_ops. - -# Instructions -- Return JSON with an ops array; change only related nodes; do not redesign the whole board. -- Do not invent node ids that are not in SCENE. - -# Examples -- Input: "Make the title red" → ops only update that text fill. diff --git a/apps/api/seeds/design_skills/README.md b/apps/api/seeds/design_skills/README.md index 01b45edb..6bd9271c 100644 --- a/apps/api/seeds/design_skills/README.md +++ b/apps/api/seeds/design_skills/README.md @@ -1,4 +1,4 @@ -# Legacy path +# Unused seed path Shipped Design Agent skills live under repo-root `skills/foundation` and `skills/domains`. -This directory is kept for backward-compatible empty mounts. +This directory is empty and is not scanned. diff --git a/apps/api/seeds/stage_rule_defaults.json b/apps/api/seeds/stage_rule_defaults.json index 66e8c1af..30b69d48 100644 --- a/apps/api/seeds/stage_rule_defaults.json +++ b/apps/api/seeds/stage_rule_defaults.json @@ -24,7 +24,6 @@ "agent.attach.place_hint": "User attached {n} image(s) (indices 0..{max_index}). Finished poster/design with baked-in text → STYLE only: do NOT create_image(attachmentIndex) full-bleed (double text). Prefer create_image genPrompt for clean bg/subject. Hero/main title: use create_text+fontFamily only if Available fonts ~≥90% match the ref lettering; else genPrompt + letteringText (transparent bg). Do not map 书法感→catalog calligraphy font. attachmentIndex only for raw photo/product cutouts." }, "descriptions": { - "legacy.agent_zero_v3": "Legacy wipe marker v3: rules/skills/flows removed", "agent.react.short_plan": "Short plan (extra ReAct round; default off)", "agent.react.dual_sample": "Dual sampling (default off)", "agent.react.defer_tools": "On-demand tools/skills via need_* (default on)", diff --git a/apps/api/tests/design_engine/test_design_governance.py b/apps/api/tests/design_engine/test_design_governance.py index 6e592921..b9536c7e 100644 --- a/apps/api/tests/design_engine/test_design_governance.py +++ b/apps/api/tests/design_engine/test_design_governance.py @@ -188,7 +188,7 @@ def test_skip_governance_on_empty_intent(): assert should_skip_design_governance(rt) is True -def test_skip_governance_on_legacy_create_edit(): +def test_skip_governance_on_create_edit_intents(): rt = _rt() rt.classified_intent = "edit" rt.flags = {"intent": "create"} diff --git a/apps/api/tests/design_engine/test_intelligence_client.py b/apps/api/tests/design_engine/test_intelligence_client.py index 444d3b98..91076e7e 100644 --- a/apps/api/tests/design_engine/test_intelligence_client.py +++ b/apps/api/tests/design_engine/test_intelligence_client.py @@ -91,7 +91,7 @@ def test_remote_empty_dict_not_usable(): assert remote_result_usable("research", {"summary": "ok", "provider": "x"}) -def test_stable_client_surface_aliases(): +def test_stable_client_surface_uses_canonical_methods(): import asyncio reset_design_intelligence_client() @@ -100,15 +100,14 @@ def test_stable_client_surface_aliases(): async def _run(): proposed = await client.propose_candidates(rt) - via_alias = await client.candidates(rt) gov = await client.govern(rt) - return proposed, via_alias, gov + return proposed, gov - proposed, via_alias, gov = asyncio.run(_run()) + proposed, gov = asyncio.run(_run()) assert rt.apply_ops == [] assert isinstance(gov, dict) assert gov.get("status") in ("pass", "fail") - _ = proposed, via_alias + _ = proposed def test_remote_provider_falls_back_on_empty_post(monkeypatch): diff --git a/apps/api/tests/design_engine/test_protocol_package.py b/apps/api/tests/design_engine/test_protocol_package.py index a053e336..a9269b1c 100644 --- a/apps/api/tests/design_engine/test_protocol_package.py +++ b/apps/api/tests/design_engine/test_protocol_package.py @@ -35,8 +35,6 @@ def test_protocol_methods_cover_client_surface(): - from recombyn_protocol import INTELLIGENCE_METHOD_ALIASES - for name in ( "analyze_reference", "research", @@ -51,8 +49,6 @@ def test_protocol_methods_cover_client_surface(): "write_principle", ): assert name in INTELLIGENCE_METHODS - assert INTELLIGENCE_METHOD_ALIASES["gate_governance"] == "govern" - assert INTELLIGENCE_METHOD_ALIASES["candidates"] == "propose_candidates" def test_state_reexports_protocol_types(): @@ -105,16 +101,16 @@ def test_flow_and_review_schemas_roundtrip(): ] == 0.8 -def test_paint_tool_op_normalizes_parameters(): +def test_paint_tool_op_uses_name_and_args(): from recombyn_protocol import DecideTurnSchema, PaintOpsSchema, PaintToolOp op = PaintToolOp.model_validate( - {"tool": "create_text", "parameters": {"text": "Hi", "x": 1}} + {"name": "create_text", "args": {"text": "Hi", "x": 1}} ) assert op.name == "create_text" assert op.args["text"] == "Hi" batch = PaintOpsSchema.model_validate( - {"ops": [{"name": "create_shape", "args": {"shapeType": "rect"}}]} + {"tool_ops": [{"name": "create_shape", "args": {"shapeType": "rect"}}]} ) assert batch.tool_ops[0].name == "create_shape" decide = DecideTurnSchema(intent="create", design_brief={"purpose": "poster"}) diff --git a/apps/api/tests/design_engine/test_repair_plan.py b/apps/api/tests/design_engine/test_repair_plan.py index 34cf35d9..f0980353 100644 --- a/apps/api/tests/design_engine/test_repair_plan.py +++ b/apps/api/tests/design_engine/test_repair_plan.py @@ -64,10 +64,10 @@ def test_spec_issue_compiles_update_node_on_living_title(): issues = _issues_as_dicts( [ { - "severity": "high", - "type": "hierarchy", + "severity": "major", + "area": "hierarchy", "target": "title", - "problem": "标题抢夺 Hero 注意力", + "issue": "标题抢夺 Hero 注意力", "action": "reduce_size", "patch": {"fontSize": 72}, } @@ -194,7 +194,7 @@ def test_prose_only_issues_compile_empty(): assert ops == [] -def test_parse_preserves_repair_fields_via_aliases(): +def test_parse_preserves_repair_fields(): parsed = _parse_review_structured( { "pass": False, @@ -210,10 +210,10 @@ def test_parse_preserves_repair_fields_via_aliases(): }, "issues": [ { - "severity": "high", - "type": "hierarchy", + "severity": "major", + "area": "hierarchy", "target": "title", - "problem": "标题抢夺 Hero 注意力", + "issue": "标题抢夺 Hero 注意力", "action": "reduce_size", "patch": {"fontSize": 72}, } diff --git a/apps/api/tests/design_engine/test_skill_pack_compatibility.py b/apps/api/tests/design_engine/test_skill_pack_compatibility.py index 77a952e4..62ba2cf2 100644 --- a/apps/api/tests/design_engine/test_skill_pack_compatibility.py +++ b/apps/api/tests/design_engine/test_skill_pack_compatibility.py @@ -1,14 +1,14 @@ -"""PR0 — Skill pack V3 must remain loadable / backward compatible.""" +"""PR0 — Skill pack V3 must remain loadable.""" from __future__ import annotations from app.services.design.prompts.skill_store.pack_io import _load_file_skills from app.services.design.prompts.skill_store.runtime import expand_skill_extends -def test_legacy_and_v3_packs_load(): +def test_surface_and_v3_packs_load(): items = _load_file_skills() by_key = {str(i.get("skill_key") or ""): i for i in items} - # Legacy surfaces still present + # Surface skills still present for key in ("poster_craft", "landing_page", "dashboard_ui", "image_gen"): assert key in by_key, f"missing surface skill {key}" assert str(by_key[key].get("prompt_positive") or "").strip() diff --git a/apps/api/tests/integration_tests/test_design_canvas_crud.py b/apps/api/tests/integration_tests/test_design_canvas_crud.py index c7094a28..57162a94 100644 --- a/apps/api/tests/integration_tests/test_design_canvas_crud.py +++ b/apps/api/tests/integration_tests/test_design_canvas_crud.py @@ -9,7 +9,7 @@ import pytest from app.services.design.readpath.catalog import ensure_design_catalog -from app.services.design.runtime.agent_controller import PaintOpsSchema +from app.services.design.runtime.graph.state import PaintOpsSchema from app.services.design.runtime.models_route import IntentClassifyDecision from tests.design_harness import collect_design_events, events_by_type @@ -177,7 +177,7 @@ def _first_ops(events: list[dict[str, Any]]) -> list[dict[str, Any]]: def _op_names(ops: list[dict[str, Any]]) -> list[str]: - return [str(o.get("name") or o.get("op_key") or "") for o in ops] + return [str(o.get("name") or "") for o in ops] def _propose_ask_ids( diff --git a/apps/api/tests/integration_tests/test_design_golden_paths.py b/apps/api/tests/integration_tests/test_design_golden_paths.py index 987a7e89..29710a5e 100644 --- a/apps/api/tests/integration_tests/test_design_golden_paths.py +++ b/apps/api/tests/integration_tests/test_design_golden_paths.py @@ -8,7 +8,7 @@ import pytest -from app.services.design.runtime.agent_controller import PaintOpsSchema +from app.services.design.runtime.graph.state import PaintOpsSchema from app.services.design.readpath.catalog import ensure_design_catalog from app.services.design.runtime.models_route import IntentClassifyDecision from tests.design_harness import collect_design_events, events_by_type 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 d6e830ba..a2ca8bef 100644 --- a/apps/api/tests/unit_tests/test_agent_controller_parse.py +++ b/apps/api/tests/unit_tests/test_agent_controller_parse.py @@ -2,17 +2,18 @@ from __future__ import annotations -from app.services.design.runtime.agent_controller import ( +from app.services.design.runtime.graph.state import ( AgentRunState, AgentTurnSchema, PaintOpsSchema, PaintToolOp, +) +from app.services.design.runtime.graph.support import ( _ask_propose_user_text, _chat_fallback_text, _ensure_propose_choice_ui, _lc_design_needs_canvas_ops, _normalize_choice_ui, - _normalize_ops_payload, _parse_agent_turn, _turn_from_structured, ) @@ -27,23 +28,25 @@ def test_parse_chat_turn(): assert t["done"] is True -def test_normalize_op_key(): - ops = _normalize_ops_payload( - [{"op_key": "create_text", "args": {"text": "Hi"}}] - ) - assert ops[0]["name"] == "create_text" - - -def test_paint_tool_op_coalesces_flat_and_ops_alias(): +def test_paint_tool_op_requires_name_and_args(): op = PaintToolOp.model_validate( - {"name": "create_shape", "type": "rect", "x": 10, "y": 20, "width": 40, "height": 30} + { + "name": "create_shape", + "args": { + "shapeType": "rect", + "x": 10, + "y": 20, + "width": 40, + "height": 30, + }, + } ) assert op.name == "create_shape" assert op.args.get("shapeType") == "rect" assert op.args.get("x") == 10 painted = PaintOpsSchema.model_validate( { - "ops": [{"name": "create_text", "args": {"text": "Hi", "x": 1, "y": 2}}], + "tool_ops": [{"name": "create_text", "args": {"text": "Hi", "x": 1, "y": 2}}], "intent": "create", } ) @@ -64,7 +67,7 @@ def test_parse_choice_ui_actions(): t = _parse_agent_turn( """ {"intent":"create","reply":"将添加浅灰矩形", - "tool_ops":[{"op_key":"create_shape","args":{"shapeType":"rect"}}], + "tool_ops":[{"name":"create_shape","args":{"shapeType":"rect"}}], "choice_ui":{"mode":"buttons","options":[ {"label":"就这样添加","action":"apply"}, {"label":"我想改颜色","action":"reply"}, @@ -79,29 +82,11 @@ def test_parse_choice_ui_actions(): assert t["apply_choice"] == "就这样添加" -def test_parse_flattened_top_level_mode_options(): - """Models often emit mode/options at JSON root instead of nested choice_ui.""" - t = _parse_agent_turn( - """ - {"intent":"ask","reply":"请问行业?","tool_ops":[],"done":false, - "mode":"single","options":[ - {"label":"科技/SaaS","action":"reply"}, - {"label":"电商/零售","action":"reply"} - ]} - """ - ) - ui = t["choice_ui"] - assert ui is not None - assert ui["mode"] == "single" - assert [o["label"] for o in ui["options"]] == ["科技/SaaS", "电商/零售"] - assert all(o["action"] == "reply" for o in ui["options"]) - - -def test_legacy_choices_map_apply_choice(): +def test_fallback_choices_map_apply_choice(): ui = _normalize_choice_ui( None, - legacy_choices=["改颜色", "确认添加", "取消"], - legacy_apply="确认添加", + fallback_choices=["改颜色", "确认添加", "取消"], + fallback_apply="确认添加", ) assert ui is not None by_label = {o["label"]: o["action"] for o in ui["options"]} @@ -123,8 +108,8 @@ def test_propose_adds_apply_slot_without_inventing_copy(): def test_choice_ui_text_mode_without_options(): ui = _normalize_choice_ui( {"mode": "text", "placeholder": "品牌、主色、文案…"}, - legacy_choices=[], - legacy_apply="", + fallback_choices=[], + fallback_apply="", ) assert ui is not None assert ui["mode"] == "text" @@ -188,7 +173,7 @@ def test_lc_design_needs_canvas_ops_blocks_narrate_only(): def test_should_route_to_paint(): - from app.services.design.runtime.agent_controller import _should_route_to_paint + from app.services.design.runtime.graph.support import _should_route_to_paint assert _should_route_to_paint( classified="create", turn_intent="chat", has_clarify=False @@ -224,7 +209,7 @@ def test_turn_from_structured_keeps_reply_and_ops(): reply="好的,我在狗旁边加一个矩形。", tool_ops=[ { - "op_key": "create_shape", + "name": "create_shape", "args": {"shapeType": "rect", "x": 100, "y": 250, "width": 200, "height": 150}, } ], @@ -281,13 +266,14 @@ def test_heuristic_user_intent_gate(): ) assert target.intent == "canvas_op" assert target.paint_lane == "edit" - assert normalize_user_intent("edit") == "canvas_op" - assert normalize_user_intent("create") == "canvas_op" - assert normalize_intent_decision("create", "", raw_grade="basic") == ( + assert normalize_user_intent("canvas_op") == "canvas_op" + assert normalize_user_intent("design") == "design" + assert normalize_user_intent("edit") == "chat" + assert normalize_intent_decision("canvas_op", "edit") == ( "canvas_op", - "create", + "edit", ) - assert normalize_intent_decision("create", "", raw_grade="design") == ( + assert normalize_intent_decision("design", "create") == ( "design", "create", ) @@ -323,8 +309,7 @@ def test_paint_tool_keys_structural_not_shape_specific(): """canvas_op create: shape+text+image — no create_frame / update.""" from types import SimpleNamespace - from app.services.design.runtime.agent_controller import ( - AgentRunState, + from app.services.design.runtime.graph.support import ( _is_lean_paint_turn, _paint_tool_keys_for_turn, ) @@ -359,8 +344,7 @@ def test_design_intent_not_lean_even_if_short_prompt(): """Short Chinese design briefs stay design — lean is canvas_op-only (LLM-owned).""" from types import SimpleNamespace - from app.services.design.runtime.agent_controller import ( - AgentRunState, + from app.services.design.runtime.graph.support import ( _is_lean_paint_turn, _paint_tool_keys_for_turn, ) @@ -423,8 +407,7 @@ def test_lean_paint_user_uses_digest_not_full_scene_dump(): def test_paint_tool_keys_basic_edit_has_update(): from types import SimpleNamespace - from app.services.design.runtime.agent_controller import ( - AgentRunState, + from app.services.design.runtime.graph.support import ( _is_lean_paint_turn, _paint_tool_keys_for_turn, ) @@ -451,7 +434,7 @@ def test_paint_tool_keys_basic_edit_has_update(): def test_paint_tool_keys_empty_canvas_includes_frame(): from types import SimpleNamespace - from app.services.design.runtime.agent_controller import AgentRunState, _paint_tool_keys_for_turn + from app.services.design.runtime.graph.support import _paint_tool_keys_for_turn from app.services.design.runtime.decision_log import DesignRunDecision st = AgentRunState(trace_id="t", task_id="task", goal="new") @@ -477,7 +460,7 @@ def test_paint_tool_keys_design_create_includes_frame_when_focus_exists(): """Ambient FOCUS must not block a new plate for design/create.""" from types import SimpleNamespace - from app.services.design.runtime.agent_controller import AgentRunState, _paint_tool_keys_for_turn + from app.services.design.runtime.graph.support import _paint_tool_keys_for_turn from app.services.design.runtime.decision_log import DesignRunDecision st = AgentRunState(trace_id="t", task_id="task", goal="login") @@ -497,7 +480,7 @@ def test_paint_tool_keys_design_create_includes_frame_when_focus_exists(): def test_lc_design_needs_canvas_ops_fine_intents(): - from app.services.design.runtime.agent_controller import ( + from app.services.design.runtime.graph.support import ( _is_canvas_work_intent, _lc_design_needs_canvas_ops, ) @@ -519,8 +502,7 @@ def test_lc_design_needs_canvas_ops_fine_intents(): def test_paint_tool_keys_with_images_includes_create_image(): from types import SimpleNamespace - from app.services.design.runtime.agent_controller import ( - AgentRunState, + from app.services.design.runtime.graph.support import ( _is_lean_paint_turn, _paint_tool_keys_for_turn, ) @@ -541,7 +523,7 @@ def test_paint_tool_keys_with_images_includes_create_image(): def test_derive_suggested_place_world_empty_viewport_centers(): - from app.services.design.runtime.agent_controller import _derive_suggested_place_world + from app.services.design.runtime.graph.support import _derive_suggested_place_world spw = _derive_suggested_place_world( {"viewport": {"x": 5000, "y": 2000, "w": 1200, "h": 800}}, @@ -554,7 +536,7 @@ def test_derive_suggested_place_world_empty_viewport_centers(): def test_derive_suggested_place_world_aligns_beside_content(): - from app.services.design.runtime.agent_controller import _derive_suggested_place_world + from app.services.design.runtime.graph.support import _derive_suggested_place_world # One free-canvas node in the left of the viewport → prefer slot to its right. spw = _derive_suggested_place_world( @@ -570,7 +552,7 @@ def test_derive_suggested_place_world_aligns_beside_content(): def test_format_spatial_placement_emits_no_invented_slots(): - from app.services.design.runtime.agent_controller import _format_spatial_placement + from app.services.design.runtime.graph.support import _format_spatial_placement text = _format_spatial_placement( { @@ -588,7 +570,7 @@ def test_format_spatial_placement_emits_no_invented_slots(): def test_placement_errors_for_offscreen_free_creates(): from types import SimpleNamespace - from app.services.design.runtime.agent_controller import ( + from app.services.design.runtime.graph.support import ( _placement_errors_for_free_creates, ) @@ -625,7 +607,7 @@ def test_placement_errors_for_offscreen_free_creates(): def test_placement_errors_skip_framed_creates(): from types import SimpleNamespace - from app.services.design.runtime.agent_controller import _placement_errors_for_free_creates + from app.services.design.runtime.graph.support import _placement_errors_for_free_creates rt = SimpleNamespace( spatial_summary={"viewport": {"x": 4800, "y": 1200, "w": 1400, "h": 900}}, @@ -643,7 +625,7 @@ def test_placement_errors_skip_framed_creates(): def test_scene_digest_includes_frame_world_xy(): - from app.services.design.runtime.agent_controller import _scene_digest + from app.services.design.runtime.graph.support import _scene_digest text = _scene_digest( [], diff --git a/apps/api/tests/unit_tests/test_agent_identity_system.py b/apps/api/tests/unit_tests/test_agent_identity_system.py index 34690669..8bfb1d8c 100644 --- a/apps/api/tests/unit_tests/test_agent_identity_system.py +++ b/apps/api/tests/unit_tests/test_agent_identity_system.py @@ -1,4 +1,4 @@ -from app.services.design.runtime.agent_controller import _resolve_agent_persona +from app.services.design.runtime.graph.support import _resolve_agent_persona def test_resolve_agent_persona_auto_and_locked(): diff --git a/apps/api/tests/unit_tests/test_agent_p1.py b/apps/api/tests/unit_tests/test_agent_p1.py index 70777980..3226689b 100644 --- a/apps/api/tests/unit_tests/test_agent_p1.py +++ b/apps/api/tests/unit_tests/test_agent_p1.py @@ -2,7 +2,7 @@ from __future__ import annotations -from app.services.design.runtime.agent_controller import AgentRunState +from app.services.design.runtime.graph.state import AgentRunState def test_run_state_execution_log(): diff --git a/apps/api/tests/unit_tests/test_agent_p2.py b/apps/api/tests/unit_tests/test_agent_p2.py index 07aa13e8..b8de1c26 100644 --- a/apps/api/tests/unit_tests/test_agent_p2.py +++ b/apps/api/tests/unit_tests/test_agent_p2.py @@ -2,7 +2,7 @@ from __future__ import annotations -from app.services.design.runtime.agent_controller import _parse_agent_turn +from app.services.design.runtime.graph.support import _parse_agent_turn from app.services.design.ops.tool_ops_contract import ( format_canvas_tools_catalog, format_canvas_tools_details, diff --git a/apps/api/tests/unit_tests/test_flow_conditional_edges.py b/apps/api/tests/unit_tests/test_flow_conditional_edges.py index e13972cc..1e72474d 100644 --- a/apps/api/tests/unit_tests/test_flow_conditional_edges.py +++ b/apps/api/tests/unit_tests/test_flow_conditional_edges.py @@ -6,13 +6,9 @@ from langgraph.types import Command -from app.services.design.runtime.agent_controller import ( - AgentRunState, - AgentRuntime, +from app.services.design.runtime.graph.build import ( _bind_design_hold_fns, _build_lc_design_graph, - _bump, - _commit, _design_refund_hold_fn, _design_settle_hold_fn, _design_thread_id, @@ -20,6 +16,8 @@ _unbind_design_hold_fns, invalidate_agent_graph_cache, ) +from app.services.design.runtime.graph.state import AgentRunState, AgentRuntime +from app.services.design.runtime.graph.support import _bump, _commit from app.services.design.runtime.decision_log import DesignRunDecision from app.services.design.runtime.flow_runtime import choose_outgoing_edges, eval_edge_condition @@ -128,8 +126,8 @@ def refund(*_a, **_k): serde = JsonPlusSerializer( pickle_fallback=False, allowed_msgpack_modules=[ - ("app.services.design.runtime.agent_controller", "AgentRuntime"), - ("app.services.design.runtime.agent_controller", "AgentRunState"), + ("app.services.design.runtime.graph.state", "AgentRuntime"), + ("app.services.design.runtime.graph.state", "AgentRunState"), ("app.services.design.runtime.decision_log", "DesignRunDecision"), ], ) diff --git a/apps/api/tests/unit_tests/test_langchain_chat.py b/apps/api/tests/unit_tests/test_langchain_chat.py index 4f931bd7..e22dbb9f 100644 --- a/apps/api/tests/unit_tests/test_langchain_chat.py +++ b/apps/api/tests/unit_tests/test_langchain_chat.py @@ -96,11 +96,11 @@ def __init__(self): } -def test_compat_chat_preserves_reasoning_delta(): - from app.services.llm import LlmEndpoint, _compat_chat_openai_cls +def test_patched_chat_preserves_reasoning_delta(): + from app.services.llm import LlmEndpoint, _patched_chat_openai_cls from langchain_core.messages import AIMessageChunk - cls = _compat_chat_openai_cls() + cls = _patched_chat_openai_cls() llm = cls( model="deepseek-chat", api_key="sk-test", @@ -136,7 +136,7 @@ def test_compat_chat_preserves_reasoning_delta(): def test_build_chat_model_uses_init_chat_model(): - from app.services.llm import LlmEndpoint, build_chat_model, _compat_chat_openai_cls + from app.services.llm import LlmEndpoint, build_chat_model, _patched_chat_openai_cls ep = LlmEndpoint( base_url="https://example.invalid/v1", @@ -152,5 +152,5 @@ def test_build_chat_model_uses_init_chat_model(): ) # RunnableBinding when callbacks on; bare model when with_usage_callback=False bare = getattr(llm, "bound", llm) - assert isinstance(bare, _compat_chat_openai_cls()) + assert isinstance(bare, _patched_chat_openai_cls()) assert getattr(bare, "_recombyn_catalog_id", None) == "deepseek" diff --git a/apps/api/tests/unit_tests/test_model_route_lanes.py b/apps/api/tests/unit_tests/test_model_route_lanes.py index bda5373a..162c96a7 100644 --- a/apps/api/tests/unit_tests/test_model_route_lanes.py +++ b/apps/api/tests/unit_tests/test_model_route_lanes.py @@ -13,18 +13,19 @@ ) -def test_normalize_legacy_aliases(): - assert normalize_lane("simple") == "fast" - assert normalize_lane("medium") == "standard" - assert normalize_lane("complex") == "reasoning" +def test_normalize_known_lanes(): + assert normalize_lane("fast") == "fast" + assert normalize_lane("standard") == "standard" + assert normalize_lane("reasoning") == "reasoning" assert normalize_lane("vision") == "vision" + assert normalize_lane("unknown") == "standard" -def test_parse_legacy_threshold_map(): +def test_parse_threshold_map(): lanes = parse_model_lanes( { "precheck.model_threshold": ( - "simple->a;medium->b;complex->c;else->b" + "fast->a;standard->b;reasoning->c;else->b" ) } ) @@ -97,10 +98,10 @@ def test_resolve_review_follows_design_model_when_no_lock(): assert reason == "review_follow_design" -def test_user_overrides_accept_legacy_and_new(): +def test_user_overrides_canonical_lanes(): rules = apply_user_route_overrides( {}, - {"simple": "m1", "standard": "m2", "vision": "m3"}, + {"fast": "m1", "standard": "m2", "vision": "m3"}, ) lanes = parse_model_lanes(rules) assert lanes["fast"] == "m1" diff --git a/apps/api/tests/unit_tests/test_skill_store.py b/apps/api/tests/unit_tests/test_skill_store.py index 423d37e6..7d0c468d 100644 --- a/apps/api/tests/unit_tests/test_skill_store.py +++ b/apps/api/tests/unit_tests/test_skill_store.py @@ -7,7 +7,6 @@ NS_EXT, NS_USER, SOURCE_ADMIN, - SOURCE_SEED, _apply_mutex, _load_file_skills, _rule_matches, @@ -195,14 +194,13 @@ def test_parse_pack_version_semver(): def test_source_constants(): - assert SOURCE_SEED == "seed" assert SOURCE_ADMIN == "admin" def test_namespace_split_and_qualify(monkeypatch): - assert split_namespace_key("core.legacy_key") == (NS_CORE, "legacy_key") + assert split_namespace_key("core.sample_key") == (NS_CORE, "sample_key") assert split_namespace_key("user:my_brand") == (NS_USER, "my_brand") - assert qualify_skill_key(NS_CORE, "legacy_key") == "legacy_key" + assert qualify_skill_key(NS_CORE, "sample_key") == "sample_key" assert qualify_skill_key(NS_USER, "my_brand") == "user.my_brand" assert resolve_storage_skill_key("poster_craft") == "poster_craft" # Patch the runtime module binding (resolve_storage_skill_key calls it in-file). @@ -274,7 +272,7 @@ def test_hot_reload_signature_stable(): def test_file_pack_sync_overwrites_body_from_disk(): - """SOURCE_FILE skills follow seeds/design_skills on ensure (file wins).""" + """SOURCE_FILE skills follow disk packs on ensure (file wins).""" from sqlmodel import Session from app.core import db as core_db @@ -302,49 +300,6 @@ def test_file_pack_sync_overwrites_body_from_disk(): assert "Workflow" in got or "Layer order" in got or "poster" in got.lower() -def test_obsolete_seed_skills_pruned(): - """Legacy SOURCE_SEED rows are deleted on ensure (file packs only).""" - from sqlmodel import Session - - from app.core import db as core_db - from app.models import DesignSkill - - with Session(core_db.engine) as session: - existing = crud.get_design_skill_by_key( - session=session, skill_key="design_methodology" - ) - if existing is None: - session.add( - DesignSkill( - skill_key="design_methodology", - name="legacy", - category="create", - prompt_positive="obsolete body", - source=SOURCE_SEED, - namespace=NS_CORE, - enabled=1, - version=1, - created_at=0.0, - updated_at=0.0, - ) - ) - session.commit() - else: - existing.source = SOURCE_SEED - existing.namespace = NS_CORE - existing.prompt_positive = "obsolete body" - session.add(existing) - session.commit() - - reset_skills_ready_for_tests() - ensure_design_skills(force=True) - - with Session(core_db.engine) as session: - row = crud.get_design_skill_by_key( - session=session, skill_key="design_methodology" - ) - assert row is None - def test_agent_skills_frontmatter_split_and_meta(): from app.services.design.prompts.skill_store import ( diff --git a/apps/api/tests/unit_tests/test_skill_v3_contracts.py b/apps/api/tests/unit_tests/test_skill_v3_contracts.py index dcfe29a1..63049f01 100644 --- a/apps/api/tests/unit_tests/test_skill_v3_contracts.py +++ b/apps/api/tests/unit_tests/test_skill_v3_contracts.py @@ -57,11 +57,9 @@ def test_design_brief_p1_not_required(): assert not brief.get("tokens") -def test_design_brief_legacy_prose_still_parses(): +def test_design_brief_plain_prose_rejected(): brief = parse_design_brief("tall festival poster, warm night stage") - assert brief is not None - assert brief.get("_legacy_prose") is True - assert design_brief_p0_missing(brief) == [] + assert brief is None def test_review_runtime_owns_total(): diff --git a/apps/api/tests/unit_tests/test_streaming_tool_ops.py b/apps/api/tests/unit_tests/test_streaming_tool_ops.py index 723b0cca..f9a781d8 100644 --- a/apps/api/tests/unit_tests/test_streaming_tool_ops.py +++ b/apps/api/tests/unit_tests/test_streaming_tool_ops.py @@ -10,8 +10,8 @@ def test_extract_streaming_complete_ops_from_partial_array(): partial = ( - '{"ops":[' - '{"name":"create_shape","args":{"type":"rect","x":0,"y":0,"width":10,"height":10,"fill":"#fff"}},' + '{"tool_ops":[' + '{"name":"create_shape","args":{"shapeType":"rect","x":0,"y":0,"width":10,"height":10,"fill":"#fff"}},' '{"name":"create_text","args":{"text":"hi","x":1,"y":2,"fontSize":12}}' ) ops, seen = extract_streaming_tool_ops(partial) @@ -24,8 +24,8 @@ def test_extract_streaming_complete_ops_from_partial_array(): def test_extract_streaming_ignores_incomplete_trailing_object(): partial = ( - '{"ops":[' - '{"name":"create_shape","args":{"type":"rect","x":0,"y":0,"width":10,"height":10,"fill":"#fff"}},' + '{"tool_ops":[' + '{"name":"create_shape","args":{"shapeType":"rect","x":0,"y":0,"width":10,"height":10,"fill":"#fff"}},' '{"name":"create_text","args":{"text":"hi"' ) ops, _seen = extract_streaming_tool_ops(partial) 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 59b1ba59..1b098c2b 100644 --- a/apps/api/tests/unit_tests/test_tool_ops_contract.py +++ b/apps/api/tests/unit_tests/test_tool_ops_contract.py @@ -15,7 +15,7 @@ def test_schema_version(): def test_valid_update_node(): - raw = '{"ops":[{"name":"update_node","args":{"nodeId":"n1","cornerRadius":8}}]}' + raw = '{"tool_ops":[{"name":"update_node","args":{"nodeId":"n1","cornerRadius":8}}]}' ops, errs = extract_and_validate_tool_ops( raw, scene_nodes=[{"id": "n1", "type": "rect", "w": 100, "h": 100}], @@ -28,14 +28,14 @@ def test_valid_update_node(): def test_rejects_unknown_tool(): - raw = '{"ops":[{"name":"explode_canvas","args":{}}]}' + raw = '{"tool_ops":[{"name":"explode_canvas","args":{}}]}' ops, errs = extract_and_validate_tool_ops(raw) assert not ops assert any("tool_not_allowed" in e for e in errs) def test_rejects_unknown_node_id(): - raw = '{"ops":[{"name":"update_node","args":{"nodeId":"ghost","fill":"#f00"}}]}' + raw = '{"tool_ops":[{"name":"update_node","args":{"nodeId":"ghost","fill":"#f00"}}]}' ops, errs = extract_and_validate_tool_ops( raw, scene_nodes=[{"id": "n1"}], @@ -57,9 +57,9 @@ def test_dedupe_by_op_id(): assert len(ops) == 1 -def test_delete_accepts_node_ids_alias(): +def test_delete_nodes_uses_nodeIds(): raw_ops = [ - {"name": "delete_nodes", "args": {"node_ids": ["n1"]}}, + {"name": "delete_nodes", "args": {"nodeIds": ["n1"]}}, ] ops, errs = normalize_agent_tool_ops( raw_ops, @@ -74,11 +74,11 @@ def test_delete_accepts_node_ids_alias(): def test_delete_plus_create_rejected_prefer_update_shape(): """Morph via delete+create is invalid — tell model to use update_node (no silent rewrite).""" raw_ops = [ - {"name": "delete_nodes", "args": {"node_ids": ["green1"]}}, + {"name": "delete_nodes", "args": {"nodeIds": ["green1"]}}, { "name": "create_shape", "args": { - "type": "ellipse", + "shapeType": "ellipse", "x": 10, "y": 20, "width": 100, @@ -218,14 +218,14 @@ def test_format_op_error_shape(): def test_rejects_unknown_tool_uses_code_format(): - raw = '{"ops":[{"name":"explode_canvas","args":{}}]}' + raw = '{"tool_ops":[{"name":"explode_canvas","args":{}}]}' ops, errs = extract_and_validate_tool_ops(raw) assert not ops assert any("code=tool_not_allowed" in e for e in errs) def test_update_node_accepts_shape_type(): - raw = '{"ops":[{"name":"update_node","args":{"nodeId":"n1","shapeType":"circle"}}]}' + raw = '{"tool_ops":[{"name":"update_node","args":{"nodeId":"n1","shapeType":"circle"}}]}' ops, errs = extract_and_validate_tool_ops( raw, scene_nodes=[{"id": "n1", "type": "rect", "w": 100, "h": 100}], @@ -234,37 +234,6 @@ def test_update_node_accepts_shape_type(): assert ops[0]["args"]["shapeType"] == "circle" -def test_accepts_parameters_envelope_as_args(): - """Models often emit OpenAI-style parameters; normalize to args.""" - raw_ops = [ - { - "name": "create_shape", - "parameters": { - "shapeType": "rect", - "x": 0, - "y": 0, - "width": 100, - "height": 80, - "fill": "#fff", - }, - }, - { - "name": "create_text", - "arguments": {"text": "Hi", "x": 10, "y": 20, "fontSize": 16}, - }, - { - "name": "create_image", - "parameters": {"genPrompt": "avatar", "x": 0, "y": 0, "width": 64, "height": 64}, - }, - ] - ops, errs = normalize_agent_tool_ops(raw_ops) - assert not errs - assert len(ops) == 3 - assert ops[0]["args"]["shapeType"] == "rect" - assert ops[1]["args"]["text"] == "Hi" - assert ops[2]["args"]["genPrompt"] == "avatar" - - def test_create_shape_next_to_images_is_not_rewritten_to_update(): """Large create_shape must not rewrite onto image nodes (looks like no-op).""" raw_ops = [ diff --git a/apps/api/tests/unit_tests/test_verify_flow.py b/apps/api/tests/unit_tests/test_verify_flow.py index 235eddf4..a5129e23 100644 --- a/apps/api/tests/unit_tests/test_verify_flow.py +++ b/apps/api/tests/unit_tests/test_verify_flow.py @@ -2,7 +2,7 @@ """Verify helpers that remain on the live code-path (no published-graph runtime).""" from __future__ import annotations -from app.services.design.runtime.agent_controller import ( +from app.services.design.runtime.graph.support import ( _ops_patch_too_broad, _structure_verify_issues, ) diff --git a/apps/collab/server.mjs b/apps/collab/server.mjs index 78f16183..22b4d880 100644 --- a/apps/collab/server.mjs +++ b/apps/collab/server.mjs @@ -49,13 +49,8 @@ async function maybeStartOtel() { : undefined, }); sdk.start(); - console.info('[collab] OpenTelemetry enabled', { service, endpoint: endpoint || 'noop' }); return sdk; - } catch (err) { - console.warn( - '[collab] OTel enabled but packages missing — npm i @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources @opentelemetry/semantic-conventions', - err?.message || err - ); + } catch { return null; } } @@ -215,7 +210,7 @@ function messageListener(conn, doc, message, readOnly) { break; } } catch (err) { - console.error('[collab] message error', err); + closeConn(doc, conn); } } @@ -292,8 +287,7 @@ server.on('upgrade', (req, socket, head) => { wss.handleUpgrade(req, socket, head, (ws) => { wss.emit('connection', ws, req, claims); }); - } catch (err) { - console.error('[collab] upgrade error', err); + } catch { socket.destroy(); } }); @@ -301,17 +295,10 @@ server.on('upgrade', (req, socket, head) => { wss.on('connection', (ws, req, claims) => { const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`); const docName = decodeURIComponent(url.pathname.replace(/^\//, '').split('/')[0] || ''); - console.info('[collab] join', { - room: docName, - userId: claims.userId, - role: claims.role, - }); setupWSConnection(ws, req, { docName, readOnly: claims.role === 'view', }); }); -server.listen(PORT, HOST, () => { - console.info(`[collab] listening ws://${HOST}:${PORT}`); -}); +server.listen(PORT, HOST); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 6d67505a..03c96533 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -39,6 +39,14 @@ function applySessionUser( ); } +async function runQuietly(task: () => Promise): Promise { + try { + await task(); + } catch { + /* ignore */ + } +} + function App() { const dispatch = useDispatch(); @@ -60,14 +68,12 @@ function App() { async function prefetchWallet() { if (!getToken()) return; - try { + await runQuietly(async () => { await queryClient.prefetchQuery({ ...apiQuery.walletWalletMe.queryOptions(), staleTime: 30_000, }); - } catch { - /* ignore */ - } + }); } async function refreshMe() { @@ -117,14 +123,12 @@ function App() { } async function prefetchBillingFlag() { - try { + await runQuietly(async () => { await queryClient.prefetchQuery({ ...apiQuery.authAuthConfig.queryOptions(), staleTime: 60_000, }); - } catch { - /* keep default off */ - } + }); } async function boot() { diff --git a/apps/web/src/components/base/segmented/index.tsx b/apps/web/src/components/base/segmented/index.tsx index 317fa71b..a86edb99 100644 --- a/apps/web/src/components/base/segmented/index.tsx +++ b/apps/web/src/components/base/segmented/index.tsx @@ -56,14 +56,14 @@ const TRACK_PAD: Record<'xs' | 'sm' | 'md', string> = { md: 'p-[3px]', }; -/** @deprecated Prefer `segmentedTrackClass('xl')` — kept for StylePanelChrome default. */ +/** Track class default for callers that use `xl`. */ export const SEGMENTED_TRACK = cn(SEGMENTED_TRACK_BASE, TRACK_RADIUS.xl, TRACK_PAD.md); /** Shared chip chrome without radius. */ export const SEGMENTED_CHIP_BASE = 'relative z-[1] flex shrink-0 items-center justify-center gap-1.5 whitespace-nowrap font-medium leading-none transition-colors duration-200 outline-none focus-visible:outline-none'; -/** @deprecated Prefer `segmentedChipClass('xl')`. */ +/** Chip class default for callers that use `xl`. */ export const SEGMENTED_CHIP = cn(SEGMENTED_CHIP_BASE, CHIP_RADIUS.xl, 'h-7'); /** Active chip fill lives on the sliding thumb — keep text/shadow tokens here for callers. */ @@ -118,7 +118,7 @@ function SegmentedControlInner({ // Enable slide only after the first layout pass (avoid animating from 0,0). const id = window.requestAnimationFrame(() => setThumbReady(true)); const track = trackRef.current; - if (!track || typeof ResizeObserver === 'undefined') { + if (!track) { return () => window.cancelAnimationFrame(id); } const ro = new ResizeObserver(() => measureThumb()); diff --git a/apps/web/src/components/base/tabs/index.tsx b/apps/web/src/components/base/tabs/index.tsx index 9018b564..a7f863fa 100644 --- a/apps/web/src/components/base/tabs/index.tsx +++ b/apps/web/src/components/base/tabs/index.tsx @@ -20,7 +20,7 @@ export interface TabsProps { onChange?: (index: number) => void; className?: string; TabListClass?: string; - /** @deprecated Unused — chips come from SegmentedControl. */ + /** Unused — chips come from SegmentedControl. */ TabClass?: string; TabPanelsClass?: string; /** Passed to SegmentedControl — default soft rect (`xl`). */ diff --git a/apps/web/src/components/base/tooltip/index.tsx b/apps/web/src/components/base/tooltip/index.tsx index a24f5f5e..1bef82cf 100644 --- a/apps/web/src/components/base/tooltip/index.tsx +++ b/apps/web/src/components/base/tooltip/index.tsx @@ -22,7 +22,7 @@ import { tooltipManager } from './TooltipManager'; export type TooltipProps = { /** Preferred content prop (alias of title). */ tip?: ReactNode; - /** @deprecated Prefer `tip`. */ + /** Alias of `tip`. */ title?: ReactNode; placement?: Placement; trigger?: 'hover' | 'click'; diff --git a/apps/web/src/components/editor/canvas/SvgCanvas.tsx b/apps/web/src/components/editor/canvas/SvgCanvas.tsx index 24a21d6c..3a281041 100644 --- a/apps/web/src/components/editor/canvas/SvgCanvas.tsx +++ b/apps/web/src/components/editor/canvas/SvgCanvas.tsx @@ -161,7 +161,9 @@ import { getDocumentGridSize, snapCoordToGrid, } from '@/components/rcb'; -import ImageProcessOverlay from '@/components/editor/nodes/ImageNode/ImageProcessOverlay'; +import ImageProcessOverlay, { + type ProcessGeomOverride, +} from '@/components/editor/nodes/ImageNode/ImageProcessOverlay'; import ImageGeneratorOverlay from '@/components/editor/nodes/ImageGeneratorNode/ImageGeneratorOverlay'; import VideoGeneratorOverlay from '@/components/editor/nodes/VideoGeneratorNode/VideoGeneratorOverlay'; import LottieGeneratorOverlay from '@/components/editor/nodes/LottieGeneratorNode/LottieGeneratorOverlay'; @@ -221,8 +223,18 @@ type SvgCanvasProps = { * to cover the camera frustum — do not slide the origin with pan/zoom. */ viewRect?: { x: number; y: number; width: number; height: number } | null; + /** Live geometry for process overlays while an artboard drag is repainting. */ + frameGeometryOverrides?: Record | null; }; +function mergeProcessGeometryOverrides( + frameOverrides: Record | null, + liveOverrides: Record | null +) { + if (!frameOverrides && !liveOverrides) return null; + return { ...frameOverrides, ...liveOverrides }; +} + function ctxMenuCanReplace(opts: { readOnly: boolean; document: SceneDocument | null | undefined; @@ -276,6 +288,7 @@ function SvgCanvas({ embedded = false, stageEl = null, viewRect = null, + frameGeometryOverrides = null, }: SvgCanvasProps) { const dispatch = useDispatch(); const { t } = useTranslation(); @@ -431,25 +444,6 @@ function SvgCanvas({ // Do not overwrite that live document with the previous Redux snapshot while // a transform is active, otherwise cleared frame bindings reappear. if (!geometryTransformingRef.current) { - const previous = documentRef.current; - const changedBindingIds = Object.keys(document?.deltaSetLike || {}).filter((id) => { - const before = previous?.deltaSetLike?.[id]?.attrs?.frameId; - const after = document?.deltaSetLike?.[id]?.attrs?.frameId; - return String(before || '') !== String(after || ''); - }); - if (changedBindingIds.length) { - console.warn('[frame-binding-redux-sync]', JSON.stringify({ - changedBindingIds, - previous: changedBindingIds.map((id) => ({ - nodeId: id, - frameId: previous?.deltaSetLike?.[id]?.attrs?.frameId, - })), - incoming: changedBindingIds.map((id) => ({ - nodeId: id, - frameId: document?.deltaSetLike?.[id]?.attrs?.frameId, - })), - }, null, 2)); - } documentRef.current = document; } selectedIdsRef.current = ctxMenuSeedNodeIds(selectedNodeIds || [], selectedNodeId); @@ -1972,7 +1966,10 @@ function SvgCanvas({ portal before selection so the selected outline and its controls stay on top. */} {/* Scene-space HTML overlays (selection / draw previews). Origin matches SVG. */} {/* Above frame/node stackOrder so preview select/hover strokes aren't covered. */} diff --git a/apps/web/src/components/editor/canvas/canvasSession.ts b/apps/web/src/components/editor/canvas/canvasSession.ts index 0084381c..29db1853 100644 --- a/apps/web/src/components/editor/canvas/canvasSession.ts +++ b/apps/web/src/components/editor/canvas/canvasSession.ts @@ -5,6 +5,7 @@ import type { Dispatch } from '@reduxjs/toolkit'; import { addNodeToDocument, patchDeltaSetLike, + reconcileStackOrder, updateNodesInDocument, } from '@/components/rcb/scene/document/sceneDocument'; import { @@ -302,16 +303,8 @@ function applyNodeFrameBindings( const order = Array.isArray(next?.stackOrder) ? next.stackOrder.map(String) : []; const remaining = order.filter((key) => !detachedKeys.has(key)); next = { ...next, stackOrder: [...remaining, ...detachedIds.map((id) => `node:${id}`)] }; - console.warn('[frame-binding-detached]', JSON.stringify({ - nodeIds: detachedIds, - nodes: detachedIds.map((id) => ({ - nodeId: id, - frameId: next.deltaSetLike?.[id]?.attrs?.frameId, - frameOrder: next.deltaSetLike?.[id]?.attrs?.frameOrder, - })), - stackTail: next.stackOrder?.slice(-detachedIds.length), - }, null, 2)); } + reconcileStackOrder(next); return next; } @@ -748,14 +741,6 @@ export function createCanvasSession(deps: CanvasSessionDeps): CanvasSession { // Persist detachment immediately so the next render cannot restore the // old Redux snapshot and make the artboard drag the node again. deps.dispatch(setDocumentFromCanvas(next)); - console.warn('[frame-binding-persist]', JSON.stringify({ - nodeIds: [...detachedNodeIds], - nodes: [...detachedNodeIds].map((id) => ({ - nodeId: id, - frameId: next.deltaSetLike?.[id]?.attrs?.frameId, - frameOrder: next.deltaSetLike?.[id]?.attrs?.frameOrder, - })), - }, null, 2)); detachedNodeIds.clear(); } } diff --git a/apps/web/src/components/editor/chrome/EditorToolStrip.tsx b/apps/web/src/components/editor/chrome/EditorToolStrip.tsx index f1d8a2a7..f86b0ec9 100644 --- a/apps/web/src/components/editor/chrome/EditorToolStrip.tsx +++ b/apps/web/src/components/editor/chrome/EditorToolStrip.tsx @@ -87,7 +87,7 @@ function layoutGeneratorPlateInView(opts: { stageEl: HTMLElement; natural: { width: number; height: number }; fit?: { minRatio?: number; maxRatio?: number }; -}): { x: number; y: number; width: number; height: number; debug: Record } { +}): { x: number; y: number; width: number; height: number } { const view = opts.stageEl.getBoundingClientRect(); const zoom = Math.max(0.05, opts.camera.zoom || 1); const center = rcbScreenToScene( @@ -107,32 +107,11 @@ function layoutGeneratorPlateInView(opts: { fit: opts.fit, }); const origin = sceneToDocumentCoords(opts.document, laid.left, laid.top); - const debug = { - zoom, - viewW: view.width, - viewH: view.height, - sceneViewW: view.width / zoom, - sceneViewH: view.height / zoom, - geomW: laid.width, - geomH: laid.height, - visualL: laid.visual.left, - visualT: laid.visual.top, - visualW: laid.visual.width, - visualH: laid.visual.height, - x: origin.x, - y: origin.y, - gridSize, - }; - if (typeof window !== 'undefined' && (window as any).__RCB_GENERATOR_PLACE_DEBUG__) { - // eslint-disable-next-line no-console - console.log('[rcb:generator-place]', debug); - } return { x: origin.x, y: origin.y, width: laid.width, height: laid.height, - debug, }; } diff --git a/apps/web/src/components/editor/chrome/PenStrokeToolbar.tsx b/apps/web/src/components/editor/chrome/PenStrokeToolbar.tsx index a0c82a04..3a51c4e9 100644 --- a/apps/web/src/components/editor/chrome/PenStrokeToolbar.tsx +++ b/apps/web/src/components/editor/chrome/PenStrokeToolbar.tsx @@ -566,22 +566,18 @@ function PenStrokeToolbar({ {t('editor.unitPx')} - {!isPencil ? ( - <> - - - - - - ) : null} + + + + ); diff --git a/apps/web/src/components/editor/nodes/ImageNode/ImageToolbarMoreDownload.tsx b/apps/web/src/components/editor/nodes/ImageNode/ImageToolbarMoreDownload.tsx index 4dc898c0..13d7d747 100644 --- a/apps/web/src/components/editor/nodes/ImageNode/ImageToolbarMoreDownload.tsx +++ b/apps/web/src/components/editor/nodes/ImageNode/ImageToolbarMoreDownload.tsx @@ -26,64 +26,33 @@ export type ImageMoreAction = | 'crop' | 'flipRotate'; -function moreItem(key: ImageMoreAction, icon: ReactNode, label: string): MenuItemType { +export type ToolbarMoreItem = { + key: string; + icon: ReactNode; + label: string; +}; + +function moreItem(key: string, icon: ReactNode, label: string): MenuItemType { return { key, label: imageMoreRow(icon, label) }; } -/** Image toolbar “More” menu: tools that dock to the right of the node. */ -function ImageToolbarMoreDownload({ +/** Shared “…” overflow used by image and element selection toolbars. */ +export function ToolbarMoreMenu({ + items, onAction, - showCornerRadius = true, + triggerClassName, }: { - onAction: (key: ImageMoreAction) => void; - showCornerRadius?: boolean; + items: ToolbarMoreItem[]; + onAction: (key: string) => void; + triggerClassName?: string; }): ReactNode { const { t } = useTranslation(); const [open, setOpen] = useState(false); - const items: MenuItemType[] = useMemo(() => { - const list: MenuItemType[] = [ - moreItem( - 'expand', - , - t('editor.imageToolbar.expand') - ), - moreItem( - 'adjust', - , - t('editor.imageToolbar.adjust') - ), - moreItem( - 'blendMode', - , - t('editor.imageToolbar.blendMode') - ), - moreItem('effects', , t('editor.imageToolbar.effects')), - ]; - if (showCornerRadius) { - list.push( - moreItem( - 'cornerRadius', - , - t('editor.imageToolbar.cornerRadius') - ) - ); - } - list.push( - moreItem( - 'opacity', - , - t('editor.imageToolbar.opacity') - ), - moreItem('crop', , t('editor.imageToolbar.crop')), - moreItem( - 'flipRotate', - , - t('editor.imageToolbar.flipRotate') - ) - ); - return list; - }, [t, showCornerRadius]); - + const menuItems: MenuItemType[] = useMemo( + () => items.map((item) => moreItem(item.key, item.icon, item.label)), + [items] + ); + if (!items.length) return null; return ( { - onAction(key as ImageMoreAction); + onAction(key); setOpen(false); }} popupClassName="min-w-[11.5rem]" @@ -105,7 +74,7 @@ function ImageToolbarMoreDownload({ @@ -114,4 +83,66 @@ function ImageToolbarMoreDownload({ ); } +/** Image toolbar “More” menu: tools that dock to the right of the node. */ +function ImageToolbarMoreDownload({ + onAction, + showCornerRadius = true, +}: { + onAction: (key: ImageMoreAction) => void; + showCornerRadius?: boolean; +}): ReactNode { + const { t } = useTranslation(); + const items: ToolbarMoreItem[] = useMemo(() => { + const list: ToolbarMoreItem[] = [ + { + key: 'expand', + icon: , + label: t('editor.imageToolbar.expand'), + }, + { + key: 'adjust', + icon: , + label: t('editor.imageToolbar.adjust'), + }, + { + key: 'blendMode', + icon: , + label: t('editor.imageToolbar.blendMode'), + }, + { + key: 'effects', + icon: , + label: t('editor.imageToolbar.effects'), + }, + ]; + if (showCornerRadius) { + list.push({ + key: 'cornerRadius', + icon: , + label: t('editor.imageToolbar.cornerRadius'), + }); + } + list.push( + { + key: 'opacity', + icon: , + label: t('editor.imageToolbar.opacity'), + }, + { + key: 'crop', + icon: , + label: t('editor.imageToolbar.crop'), + }, + { + key: 'flipRotate', + icon: , + label: t('editor.imageToolbar.flipRotate'), + } + ); + return list; + }, [t, showCornerRadius]); + + return onAction(key as ImageMoreAction)} />; +} + export default memo(ImageToolbarMoreDownload); diff --git a/apps/web/src/components/editor/nodes/ImageNode/mark/MarkSessionHost.tsx b/apps/web/src/components/editor/nodes/ImageNode/mark/MarkSessionHost.tsx index c493800c..67baa4e5 100644 --- a/apps/web/src/components/editor/nodes/ImageNode/mark/MarkSessionHost.tsx +++ b/apps/web/src/components/editor/nodes/ImageNode/mark/MarkSessionHost.tsx @@ -272,14 +272,11 @@ function MarkSessionHost({ document }: { document: SceneDocument }): ReactNode { selected: false, })); setRegions(next); - if (res.warnings?.length) { - console.info('[mark] detect warnings', res.warnings); - } } catch (err: unknown) { if (ac.signal.aborted || gen !== detectGenRef.current) return; const msg = getHttpErrorMessage(err, ''); if (msg && !/unsupported kind|detectRegions/i.test(msg)) { - console.info('[mark] detect failed', msg); + console.warn('[mark] detect failed', msg); } } finally { if (gen === detectGenRef.current) setDetecting(false); @@ -342,10 +339,7 @@ function MarkSessionHost({ document }: { document: SceneDocument }): ReactNode { box.height, region, uploadKey - ).catch((err: unknown) => { - console.info('[mark] crop failed', getHttpErrorMessage(err, '')); - return undefined; - }); + ).catch(() => undefined); // Pop-in, then fly — wait for thumb (capped) so the chip looks real mid-flight. const [thumb] = await Promise.all([ diff --git a/apps/web/src/components/editor/nodes/ImageNode/toolPanels/ImageToolPanelHost.tsx b/apps/web/src/components/editor/nodes/ImageNode/toolPanels/ImageToolPanelHost.tsx index 51c297f4..b8adbcbe 100644 --- a/apps/web/src/components/editor/nodes/ImageNode/toolPanels/ImageToolPanelHost.tsx +++ b/apps/web/src/components/editor/nodes/ImageNode/toolPanels/ImageToolPanelHost.tsx @@ -11,9 +11,11 @@ import { startImageProcess, type ImageToolPanelKind, isImageToolExternalSessionKind, + isNodeLayerToolPanelKind, } from '@/store/modules/editor'; import { buildNodeAdjustFilterCss } from '@/components/rcb/scene/document/sceneFill'; import { nodeLeftTop } from '@/components/rcb/scene/paint/sceneToSvg'; +import { toolbarBoxForSelection } from '@/components/rcb/selection/selectionLogic'; import { RcbOverlayPortal, useRcbCamera, @@ -107,18 +109,31 @@ function panelStyleRight( }; } +function isLineOrArrow(node: SceneNodeInput): boolean { + const t = String(node?.attrs?.shapeType || ''); + return t === 'line' || t === 'arrow'; +} + function nodeBox( document: SceneDocument, node: SceneNodeInput ): { left: number; top: number; width: number; height: number } | null { if (!node) return null; const { left, top } = nodeLeftTop(document, node); - return { + const box = { left, top, width: Math.max(1, Number(node.width) || 1), height: Math.max(1, Number(node.height) || 1), }; + // Line/arrow store a fat hit AABB. Dock blend/effects to the shaft AABB + // (same as the selection toolbar) so the panel sits at the visual top-right. + return ( + toolbarBoxForSelection(box, { + lineChrome: isLineOrArrow(node), + node, + }) || box + ); } /** Host for image tool panels positioned relative to the source image. */ @@ -137,11 +152,9 @@ function ImageToolPanelHost({ document }: { document: SceneDocument }): ReactNod const [brushSize, setBrushSize] = useState(96); const [hasStrokes, setHasStrokes] = useState(false); const [eraseBusy, setEraseBusy] = useState(false); - const [opacityPct, setOpacityPct] = useState(100); const maskRef = useRef(null); const adjustHistoryPushedRef = useRef(false); const adjustBaselineRef = useRef<{ cssFilter: string; adjustValues: unknown } | null>(null); - const opacityBaselineRef = useRef(1); const liveHistoryPushedRef = useRef(false); useEffect(() => { @@ -156,7 +169,13 @@ function ImageToolPanelHost({ document }: { document: SceneDocument }): ReactNod // Crop / expand / flipRotate / media quick-edit are owned outside this host. if (isImageToolExternalSessionKind(panel.kind)) return; const node = document?.deltaSetLike?.[panel.nodeId]; - if (!node || node.key !== 'image') dispatch(closeImageToolPanel()); + if (!node) { + dispatch(closeImageToolPanel()); + return; + } + if (!isNodeLayerToolPanelKind(panel.kind) && node.key !== 'image') { + dispatch(closeImageToolPanel()); + } }, [document, panel, dispatch]); useEffect(() => { @@ -174,16 +193,6 @@ function ImageToolPanelHost({ document }: { document: SceneDocument }): ReactNod // eslint-disable-next-line react-hooks/exhaustive-deps }, [panel?.kind, panel?.nodeId]); - useEffect(() => { - if (panel?.kind !== 'opacity' || !panel.nodeId) return; - const node = document?.deltaSetLike?.[panel.nodeId]; - const base = parseLayerOpacity(node?.attrs?.opacity, 1); - opacityBaselineRef.current = base; - setOpacityPct(layerOpacityToPct(base)); - // Only when opening / switching the opacity target. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [panel?.kind, panel?.nodeId]); - // Snapshot adjust attrs once when the panel opens (for cancel restore). useEffect(() => { if (panel?.kind !== 'adjust' || !panel.nodeId) { @@ -202,7 +211,9 @@ function ImageToolPanelHost({ document }: { document: SceneDocument }): ReactNod }, [panel?.kind, panel?.nodeId]); useEffect(() => { - if (panel?.kind !== 'effects' && panel?.kind !== 'blendMode') return; + if (panel?.kind !== 'effects' && panel?.kind !== 'blendMode' && panel?.kind !== 'opacity') { + return; + } liveHistoryPushedRef.current = false; }, [panel?.kind, panel?.nodeId]); @@ -278,23 +289,6 @@ function ImageToolPanelHost({ document }: { document: SceneDocument }): ReactNod ); }; - const writeOpacity = (pct: number, mode: 'preview' | 'commit') => { - const node = document?.deltaSetLike?.[panel!.nodeId]; - const next01 = Math.min(1, Math.max(0, Math.round(pct) / 100)); - dispatch( - patchDocumentNode({ - nodeId: panel!.nodeId, - skipHistory: mode === 'preview', - patch: { - attrs: { - ...(node?.attrs || {}), - opacity: next01, - }, - }, - }) - ); - }; - const writeAttrPatch = (patch: Record, mode: 'preview' | 'commit') => { const node = document?.deltaSetLike?.[panel.nodeId]; if (mode === 'preview' && !liveHistoryPushedRef.current) { @@ -317,41 +311,20 @@ function ImageToolPanelHost({ document }: { document: SceneDocument }): ReactNod let body: ReactNode = null; switch (panel.kind) { - case 'opacity': + case 'opacity': { + const node = document?.deltaSetLike?.[panel.nodeId]; body = ( { - setOpacityPct(v); - writeOpacity(v, 'preview'); - }} - onReset={() => { - setOpacityPct(100); - writeOpacity(100, 'preview'); - }} - onCancel={() => { - const node = document?.deltaSetLike?.[panel.nodeId]; - dispatch( - patchDocumentNode({ - nodeId: panel.nodeId, - skipHistory: true, - patch: { - attrs: { - ...(node?.attrs || {}), - opacity: opacityBaselineRef.current, - }, - }, - }) - ); - close(); - }} - onConfirm={() => { - writeOpacity(opacityPct, 'commit'); - close(); - }} + opacityPct={layerOpacityToPct(parseLayerOpacity(node?.attrs?.opacity, 1))} + onOpacityPctChange={(v) => + writeAttrPatch({ opacity: Math.min(1, Math.max(0, Math.round(v) / 100)) }, 'preview') + } + onReset={() => writeAttrPatch({ opacity: 1 }, 'preview')} + onClose={close} /> ); break; + } case 'eraser': body = ( void; onReset: () => void; - onCancel: () => void; - onConfirm: () => void; + onClose: () => void; }) { const { t } = useTranslation(); const safe = Math.min(100, Math.max(0, Math.round(opacityPct))); @@ -27,19 +22,12 @@ function OpacityToolPanel({ } - footer={ - - } >
void }) { function resolveLottiePlateFill(raw: string): string { const s = String(raw || '').trim(); - // Default / legacy transparent → theme surface plate (not black). + // Default transparent → theme surface plate (not black). if (!s || s === 'transparent') return resolveThemeSurfaceFill(''); return resolveThemeSurfaceFill(s); } diff --git a/apps/web/src/components/editor/nodes/ShapeNode/ShapeSelectionToolbar.tsx b/apps/web/src/components/editor/nodes/ShapeNode/ShapeSelectionToolbar.tsx index 4488bcb9..922aad68 100644 --- a/apps/web/src/components/editor/nodes/ShapeNode/ShapeSelectionToolbar.tsx +++ b/apps/web/src/components/editor/nodes/ShapeNode/ShapeSelectionToolbar.tsx @@ -61,20 +61,12 @@ import { strokeEndpointsFromBox, strokeNodeFromEndpoints, } from '@/components/rcb/scene/document/sceneShapes'; -import { - buildOutlinePathAsync, - canOutlineNode, - outlineNodePatch, - requestEnterPathEdit, -} from '@/components/rcb/scene/paint/outlineToPath'; import { nodeLeftTop, previewSvgNodeGeometry, } from '@/components/rcb/scene/paint/sceneToSvg'; import { sceneToDocumentCoords } from '@/components/rcb/scene/paint/svgToScene'; import { getSharedNodeEls } from '@/components/rcb/shapes/shapeHostRegistry'; -import { TbVectorBezier } from 'react-icons/tb'; -import { message } from '@/components/base'; import type { SceneDocument, SceneNode, SceneNodeInput } from '@/components/rcb/sceneNode'; function readAspectLocked(attrs: Record | undefined): boolean { @@ -441,44 +433,10 @@ function ShapeSelectionToolbar({ ); }; - const applyOutline = async () => { - const hide = message.loading('轮廓化中…', 0); - try { - const outline = await buildOutlinePathAsync(node); - if (!outline?.pathD) { - message.error('轮廓化失败'); - return; - } - const patch = outlineNodePatch(node, outline); - dispatch( - patchDocumentNode({ - nodeId, - patch: { - key: 'shape', - x: patch.x, - y: patch.y, - width: patch.width, - height: patch.height, - attrs: patch.attrs, - }, - }) - ); - const st = String(node?.attrs?.shapeType || node?.key || ''); - const fromStrokeOutline = - st === 'pen' || st === 'pencil' || st === 'line' || st === 'arrow'; - requestEnterPathEdit(nodeId, outline.pathD, { fromStrokeOutline }); - message.success('已轮廓化'); - } finally { - hide(); - } - }; - const openStyle = (kind: 'fill' | 'stroke' | 'radius') => { dispatch(openShapeStylePanel({ kind, nodeIds: [nodeId] })); }; - const showOutline = canOutlineNode(node); - return ( <> {canFill ? ( @@ -671,20 +629,6 @@ function ShapeSelectionToolbar({ ) : null} - {showOutline ? ( - - - - ) : null} - {hideExport ? null : } ); diff --git a/apps/web/src/components/editor/nodes/ShapeNode/ShapeStylePanelHost.tsx b/apps/web/src/components/editor/nodes/ShapeNode/ShapeStylePanelHost.tsx index 319c4a03..b42e9f66 100644 --- a/apps/web/src/components/editor/nodes/ShapeNode/ShapeStylePanelHost.tsx +++ b/apps/web/src/components/editor/nodes/ShapeNode/ShapeStylePanelHost.tsx @@ -512,7 +512,7 @@ function ShapeStylePanelHost({ document }: { document: SceneDocument }): ReactNo radiusBL: Math.max(0, Math.round(next.bl) || 0), radiusLinked: next.linked ? 'true' : 'false', radiusVertices: serializeRadiusVertices(vertices), - // Keep legacy aliases in sync for inventory / import paths. + // Keep radius aliases in sync for inventory / import paths. radius: Math.max( 0, Math.round(Math.max(next.tl, next.tr, next.br, next.bl) || 0) diff --git a/apps/web/src/components/editor/nodes/VideoNode/VideoJsPlayer.tsx b/apps/web/src/components/editor/nodes/VideoNode/VideoJsPlayer.tsx index ee435368..caa1cb5d 100644 --- a/apps/web/src/components/editor/nodes/VideoNode/VideoJsPlayer.tsx +++ b/apps/web/src/components/editor/nodes/VideoNode/VideoJsPlayer.tsx @@ -266,9 +266,9 @@ function VideoJsPlayer({ setBarScale(chrome.visible ? videoPlaybackBarScale(rect.width) * chrome.fit : 0); }; sync(); - const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(sync) : null; - ro?.observe(el); - return () => ro?.disconnect(); + const ro = new ResizeObserver(sync); + ro.observe(el); + return () => ro.disconnect(); }, [controlsMode, playable]); const videoStyle = useMemo((): CSSProperties => { diff --git a/apps/web/src/components/editor/nodes/VideoNode/VideoPlaybackBar.tsx b/apps/web/src/components/editor/nodes/VideoNode/VideoPlaybackBar.tsx index d6de17c9..03f0211f 100644 --- a/apps/web/src/components/editor/nodes/VideoNode/VideoPlaybackBar.tsx +++ b/apps/web/src/components/editor/nodes/VideoNode/VideoPlaybackBar.tsx @@ -275,7 +275,7 @@ function VideoPlaybackBar({ const [scrubRatio, setScrubRatio] = useState(null); const [paused, setPaused] = useState(true); const [current, setCurrent] = useState(0); - // Only used when attrs.duration is missing (legacy nodes). + // Only used when attrs.duration is missing. const [fallbackDuration, setFallbackDuration] = useState(0); const [muted, setMuted] = useState(true); const [volume, setVolume] = useState(1); @@ -315,7 +315,7 @@ function VideoPlaybackBar({ media.on('loadedmetadata', syncMeta); media.on('volumechange', syncMeta); - // attrs.duration missing — read / probe once (legacy nodes only). + // attrs.duration missing — read / probe once. if (!(known > 0)) { const live = media.getDuration(); if (live > 0) { diff --git a/apps/web/src/components/editor/page/EditorBottomHud.tsx b/apps/web/src/components/editor/page/EditorBottomHud.tsx index d9b2126d..ef7d825e 100644 --- a/apps/web/src/components/editor/page/EditorBottomHud.tsx +++ b/apps/web/src/components/editor/page/EditorBottomHud.tsx @@ -84,6 +84,242 @@ function bottomHudCollidesWithTools(opts: { return hudRight + BOTTOM_HUD_TOOLS_GAP_PX > toolsLeft; } +/** + * Opt-in canvas FPS meter (rAF sampler). + * Toggle: zoom menu → FPS meter, or `window.__RCB_FPS_HUD__ = true` then + * `window.dispatchEvent(new Event('rcb-fps-hud'))`. + * Console: `window.__fpsHud.live()` / `.slice(name, t0, t1)`. + * Persists in localStorage. Default OFF. + */ +const FPS_HUD_STORAGE_KEY = 'recombyn-editor-fps-hud'; +const FPS_HUD_EVENT = 'rcb-fps-hud'; + +type FpsFrameStats = { + n: number; + fps: number; + min: number; + median: number; + p95: number; + max: number; + mean: number; + dropped22: number; + dropped33: number; +}; + +type FpsSlice = { + name: string; + wallMs: number; + frame: FpsFrameStats; + longTasks: number; + longMaxMs: number; +}; + +type FpsLive = FpsFrameStats & { + sampleCount: number; + longTasks: number; + longMaxMs: number; +}; + +type FpsHudApi = { + live: () => FpsLive; + slice: (name: string, t0: number, t1: number) => FpsSlice; + now: () => number; + enable: () => void; + disable: () => void; +}; + +declare global { + interface Window { + __RCB_FPS_HUD__?: boolean; + __fpsHud?: FpsHudApi; + } +} + +function emptyFpsStats(): FpsFrameStats { + return { + n: 0, + fps: 0, + min: 0, + median: 0, + p95: 0, + max: 0, + mean: 0, + dropped22: 0, + dropped33: 0, + }; +} + +function fpsFrameStats(arr: number[]): FpsFrameStats { + if (!arr.length) return emptyFpsStats(); + const s = [...arr].sort((a, b) => a - b); + const q = (p: number) => s[Math.min(s.length - 1, Math.floor(p * (s.length - 1)))]; + const mean = s.reduce((a, b) => a + b, 0) / s.length; + return { + n: s.length, + fps: +(1000 / mean).toFixed(1), + min: +s[0].toFixed(2), + median: +q(0.5).toFixed(2), + p95: +q(0.95).toFixed(2), + max: +s[s.length - 1].toFixed(2), + mean: +mean.toFixed(2), + dropped22: s.filter((x) => x > 22).length, + dropped33: s.filter((x) => x > 33).length, + }; +} + +function readFpsHudEnabled(): boolean { + if (typeof window === 'undefined') return false; + if (window.__RCB_FPS_HUD__ === true) return true; + if (window.__RCB_FPS_HUD__ === false) return false; + try { + return localStorage.getItem(FPS_HUD_STORAGE_KEY) === '1'; + } catch { + return false; + } +} + +function writeFpsHudEnabled(on: boolean) { + if (typeof window === 'undefined') return; + window.__RCB_FPS_HUD__ = on; + try { + if (on) localStorage.setItem(FPS_HUD_STORAGE_KEY, '1'); + else localStorage.removeItem(FPS_HUD_STORAGE_KEY); + } catch { + /* ignore quota / private mode */ + } + window.dispatchEvent(new Event(FPS_HUD_EVENT)); +} + +function startFpsSampler() { + const samples: Array<{ t: number; dt: number }> = []; + const longTasks: Array<{ t: number; dur: number }> = []; + let last = 0; + let raf = 0; + let running = true; + + const longObs = new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + longTasks.push({ t: entry.startTime, dur: entry.duration }); + } + }); + try { + longObs.observe({ type: 'longtask', buffered: true }); + } catch { + /* longtask not available */ + } + + function loop(now: number) { + if (!running) return; + if (last) { + samples.push({ t: now, dt: now - last }); + if (samples.length > 8000) samples.splice(0, samples.length - 4000); + } + last = now; + raf = requestAnimationFrame(loop); + } + raf = requestAnimationFrame(loop); + + return { + live(): FpsLive { + const recent = samples.slice(-120); + const t0 = recent[0]?.t ?? 0; + const t1 = recent[recent.length - 1]?.t ?? 0; + const longs = longTasks.filter((x) => x.t >= t0 && x.t <= t1); + return { + sampleCount: samples.length, + ...fpsFrameStats(recent.map((s) => s.dt)), + longTasks: longs.length, + longMaxMs: longs.length ? +Math.max(...longs.map((x) => x.dur)).toFixed(2) : 0, + }; + }, + slice(name: string, t0: number, t1: number): FpsSlice { + const dts = samples.filter((s) => s.t >= t0 && s.t <= t1).map((s) => s.dt); + const longs = longTasks.filter((x) => x.t >= t0 && x.t <= t1); + return { + name, + wallMs: +(t1 - t0).toFixed(2), + frame: fpsFrameStats(dts), + longTasks: longs.length, + longMaxMs: longs.length ? +Math.max(...longs.map((x) => x.dur)).toFixed(2) : 0, + }; + }, + now() { + return performance.now(); + }, + stop() { + running = false; + cancelAnimationFrame(raf); + longObs.disconnect(); + }, + }; +} + +function bindFpsHudWindowApi(sampler: ReturnType) { + window.__fpsHud = { + live: () => sampler.live(), + slice: (name, t0, t1) => sampler.slice(name, t0, t1), + now: () => sampler.now(), + enable: () => writeFpsHudEnabled(true), + disable: () => writeFpsHudEnabled(false), + }; +} + +function emptyFpsLive(): FpsLive { + return { sampleCount: 0, longTasks: 0, longMaxMs: 0, ...emptyFpsStats() }; +} + +function FpsHudOverlay() { + const { t } = useTranslation(); + const [live, setLive] = useState(emptyFpsLive); + + useEffect(() => { + const sampler = startFpsSampler(); + bindFpsHudWindowApi(sampler); + const id = window.setInterval(() => { + setLive(sampler.live()); + }, 250); + return () => { + window.clearInterval(id); + sampler.stop(); + if (window.__fpsHud) { + window.__fpsHud = { + ...window.__fpsHud, + live: () => emptyFpsLive(), + slice: (name, t0, t1) => ({ + name, + wallMs: +(t1 - t0).toFixed(2), + frame: emptyFpsStats(), + longTasks: 0, + longMaxMs: 0, + }), + }; + } + }; + }, []); + + const fpsLabel = live.n ? String(live.fps) : '—'; + + return ( +
+
+
+ FPS + {fpsLabel} +
+
+ {live.median.toFixed(1)}ms · p95 {live.p95.toFixed(1)} +
+
+ drop {live.dropped22} · long {live.longTasks} +
+
+
+ ); +} + function HudBtn({ tip, active, @@ -242,9 +478,33 @@ function EditorBottomHud({ const { t } = useTranslation(); const dispatch = useDispatch(); const [zoomMenuOpen, setZoomMenuOpen] = useState(false); + const [fpsHudOn, setFpsHudOn] = useState(readFpsHudEnabled); const bottomHudRef = useRef(null); const [stackBottomHud, setStackBottomHud] = useState(false); + useEffect(() => { + const sync = () => setFpsHudOn(readFpsHudEnabled()); + window.addEventListener(FPS_HUD_EVENT, sync); + if (!window.__fpsHud) { + window.__fpsHud = { + live: () => emptyFpsLive(), + slice: (name, t0, t1) => ({ + name, + wallMs: +(t1 - t0).toFixed(2), + frame: emptyFpsStats(), + longTasks: 0, + longMaxMs: 0, + }), + now: () => performance.now(), + enable: () => writeFpsHudEnabled(true), + disable: () => writeFpsHudEnabled(false), + }; + } + return () => { + window.removeEventListener(FPS_HUD_EVENT, sync); + }; + }, []); + useEffect(() => { const stage = stageEl; const hud = bottomHudRef.current; @@ -308,17 +568,28 @@ function EditorBottomHud({ key: p.key, label: , })), + { key: 'fps-divider', type: 'divider', label: '' }, + { + key: 'fps', + label: , + }, ], [t] ); - const zoomSelectedKeys = useMemo( - () => zoomMenuSelectedKeys({ zoom: camera.zoom, fitActive: zoomFitActive }), - [camera.zoom, zoomFitActive] - ); + const zoomSelectedKeys = useMemo(() => { + const keys = zoomMenuSelectedKeys({ zoom: camera.zoom, fitActive: zoomFitActive }); + if (fpsHudOn) keys.push('fps'); + return keys; + }, [camera.zoom, zoomFitActive, fpsHudOn]); const onZoomMenuClick = useCallback( (key: string) => { + if (key === 'fps') { + writeFpsHudEnabled(!readFpsHudEnabled()); + setZoomMenuOpen(false); + return; + } if (key === 'fit') onFitView(); else if (key === 'in') onZoomIn(); else if (key === 'out') onZoomOut(); @@ -332,32 +603,34 @@ function EditorBottomHud({ ); return ( -
- {minimapOpen ? ( - - ) : null} - {shortcutsOpen ? ( - setShortcutsOpen(false)} /> - ) : null} - + {fpsHudOn ? : null} +
+ {minimapOpen ? ( + + ) : null} + {shortcutsOpen ? ( + setShortcutsOpen(false)} /> + ) : null} + {!isDevMode ? ( <> {useCompactTooling ? ( @@ -485,8 +758,9 @@ function EditorBottomHud({ - -
+
+
+ ); } diff --git a/apps/web/src/components/editor/page/EditorStageWorld.tsx b/apps/web/src/components/editor/page/EditorStageWorld.tsx index 2d73e9c2..2ae11d9d 100644 --- a/apps/web/src/components/editor/page/EditorStageWorld.tsx +++ b/apps/web/src/components/editor/page/EditorStageWorld.tsx @@ -405,6 +405,9 @@ function EditorStageWorld({ ); const [movingFrameId, setMovingFrameId] = useState(null); const [frameSmartGuides, setFrameSmartGuides] = useState([]); + const [frameProcessGeometry, setFrameProcessGeometry] = useState< + Record + >({}); const [selectionTransforming, setSelectionTransforming] = useState(false); const frameDragRef = useRef<{ frames: Array<{ @@ -520,13 +523,32 @@ function EditorStageWorld({ nodeId, patch: { x: x + dx, y: y + dy }, })); + const processGeometry: Record< + string, + { left: number; top: number; width: number; height: number; angle?: number } + > = {}; + for (const origin of origins) { + const node = document.deltaSetLike?.[origin.nodeId]; + if (!node) continue; + processGeometry[origin.nodeId] = { + left: origin.x + dx, + top: origin.y + dy, + width: origin.width, + height: origin.height, + angle: Number(node.attrs?.angle) || 0, + }; + } + setFrameProcessGeometry(processGeometry); const previewFrames = frames.map((item) => { const moved = movedFrames.find((entry) => entry.id === item.id); if (!moved) return item; return { ...item, x: moved.startX + dx, y: moved.startY + dy }; }); const previewDocument = { ...document, frames: previewFrames }; - const nodeEls = getSharedNodeEls(); + const sharedNodeEls = getSharedNodeEls(); + const nodeEls = sharedNodeEls instanceof Map + ? sharedNodeEls + : new Map(); for (const origin of origins) { const node = document.deltaSetLike?.[origin.nodeId]; const el = nodeEls.get(origin.nodeId); @@ -548,7 +570,7 @@ function EditorStageWorld({ } // Re-evaluate clipping for every mounted node against the preview frame // position. Otherwise overflow appears only after pointer-up/remount. - for (const [nodeId, el] of nodeEls) { + for (const [nodeId, el] of nodeEls.entries()) { const node = document.deltaSetLike?.[nodeId]; if (!node || !el.ownerSVGElement) continue; const moved = childPatches.find((patch) => patch.nodeId === nodeId)?.patch; @@ -602,23 +624,8 @@ function EditorStageWorld({ if (movedFrames.length) { frameMoveDocumentRef.current = document; setFrameSmartGuides([]); + setFrameProcessGeometry({}); const boundNodeIds = nodeIdsBoundToFrames(document, frameIds); - console.warn('[frame-move-start]', JSON.stringify({ - frameIds, - boundNodeIds, - nodes: boundNodeIds.map((nodeId) => { - const node = document.deltaSetLike?.[nodeId]; - return { - nodeId, - frameId: node?.attrs?.frameId, - frameOrder: node?.attrs?.frameOrder, - x: node?.x, - y: node?.y, - width: node?.width, - height: node?.height, - }; - }), - }, null, 2)); const childOrigins = boundNodeIds .map((nodeId) => { const node = document.deltaSetLike?.[nodeId]; @@ -654,10 +661,6 @@ function EditorStageWorld({ if (frameIds.length) { const liveDocument = frameMoveDocumentRef.current || document; const next = bindUnownedNodesToFrames(liveDocument, frameIds); - console.warn('[frame-bind-on-drop]', JSON.stringify({ - frameIds, - boundNodeIds: nodeIdsBoundToFrames(next, frameIds), - }, null, 2)); if (next !== liveDocument) { dispatch(setDocumentFromCanvas(next)); } @@ -665,6 +668,7 @@ function EditorStageWorld({ frameDragRef.current = null; frameMoveDocumentRef.current = document; setFrameSmartGuides([]); + setFrameProcessGeometry({}); setMovingFrameId(null); }, [dispatch, document]); @@ -765,6 +769,7 @@ function EditorStageWorld({ onTransformingChange={setSelectionTransforming} embedded stageEl={stageEl} + frameGeometryOverrides={frameProcessGeometry} onOpenAgent={onOpenAgent} onAddToChat={onAddToChat} /> diff --git a/apps/web/src/components/editor/panels/AgentDock.tsx b/apps/web/src/components/editor/panels/AgentDock.tsx index 5d95bd69..faa33a1b 100644 --- a/apps/web/src/components/editor/panels/AgentDock.tsx +++ b/apps/web/src/components/editor/panels/AgentDock.tsx @@ -2429,11 +2429,7 @@ function AgentDock({ canvasUi, }); if (docNow) { - try { - checkpointsRef.current.set(userMsg.id, cloneDocument(docNow) ?? docNow); - } catch { - /* ignore snapshot failure */ - } + checkpointsRef.current.set(userMsg.id, cloneDocument(docNow) ?? docNow); } const cwd = await prepareCodingCliWorkspaceDesktop({ projectId: chatScopeId || '__none__', @@ -2680,11 +2676,7 @@ function AgentDock({ nodesPainted: false, }; if (docNow) { - try { - checkpointsRef.current.set(userMsg.id, cloneDocument(docNow) ?? docNow); - } catch { - /* ignore snapshot failure */ - } + checkpointsRef.current.set(userMsg.id, cloneDocument(docNow) ?? docNow); } dispatch(setAgentBusy(true)); @@ -2713,13 +2705,6 @@ function AgentDock({ const sendScene = null; // Design agent: always Smart — LLM create_frame picks WxH (no CLIENT_SIZE_LOCK). const sendCanvasSize = 'auto'; - console.info('[AgentDock] design send (react p0)', { - scene: sendScene, - canvasSize: sendCanvasSize, - chip: chipNorm, - nodes: sceneNodes.length, - frames: sceneFrames.length, - }); const onDesignEvent = createDesignAgentEventRouter({ t, assistantId, diff --git a/apps/web/src/components/editor/panels/agent/__tests__/aiOperationQueue.test.ts b/apps/web/src/components/editor/panels/agent/__tests__/aiOperationQueue.test.ts index e2515fb4..dfda73b6 100644 --- a/apps/web/src/components/editor/panels/agent/__tests__/aiOperationQueue.test.ts +++ b/apps/web/src/components/editor/panels/agent/__tests__/aiOperationQueue.test.ts @@ -106,13 +106,13 @@ describe('AIOperationQueue', () => { expect(aiQueueAckStatus(q)).toBe('rollback'); }); - it('legacy tool_ops without begin still enqueue (implicit open)', () => { + it('implicit-open tool_ops without begin still enqueue', () => { const q = createAiOperationQueue(); - expect(aiQueueEnqueue(q, [op('legacy')])).toBe(true); + expect(aiQueueEnqueue(q, [op('implicit')])).toBe(true); expect(q.status).toBe('open'); aiQueueBindTransaction(q, 'tx_late'); expect(q.transactionId).toBe('tx_late'); - expect(aiQueueTakeChunk(q)?.[0]?.op_id).toBe('legacy'); + expect(aiQueueTakeChunk(q)?.[0]?.op_id).toBe('implicit'); }); it('commit racing ahead of drain does not drop pending chunks', () => { @@ -142,8 +142,8 @@ describe('PR9 AI Overlay', () => { it('maps the last tool op onto ephemeral overlay fields', () => { const overlay = overlayFromToolOps({ ops: [ - { name: 'create_shape', args: { id: 'bg' } }, - { name: 'update_node', args: { id: 'hero', w: 400 } }, + { name: 'create_shape', args: { nodeId: 'bg' } }, + { name: 'update_node', args: { nodeId: 'hero', w: 400 } }, ], frameId: 'frame_1', transactionId: 'tx_01', diff --git a/apps/web/src/components/editor/panels/agent/__tests__/designTools.canvasOps.test.ts b/apps/web/src/components/editor/panels/agent/__tests__/designTools.canvasOps.test.ts new file mode 100644 index 00000000..c893d27c --- /dev/null +++ b/apps/web/src/components/editor/panels/agent/__tests__/designTools.canvasOps.test.ts @@ -0,0 +1,352 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createShapeNode } from '@/components/rcb/scene/document/nodeFactories'; +import { addNodeToDocument, createEmptyDocument } from '@/components/rcb/scene/document/sceneDocument'; +import { executeDesignTool, type DesignToolContext } from '../designTools'; + +function createHarness() { + let doc = createEmptyDocument({ width: 1440, height: 900 }); + let frameSeq = 1; + const dispatch = vi.fn((action: { type?: string; payload?: any }) => { + const type = String(action?.type || ''); + const payload = action?.payload; + if (type.endsWith('/addArtboardFrame') || type.includes('addArtboardFrame')) { + const id = `frame_${frameSeq++}`; + doc = { + ...doc, + frames: [ + ...(doc.frames || []), + { + id, + name: String(payload?.name || 'Frame'), + x: Number(payload?.x) || 0, + y: Number(payload?.y) || 0, + width: Math.max(40, Number(payload?.width) || 390), + height: Math.max(40, Number(payload?.height) || 844), + backgroundColor: String(payload?.backgroundColor || 'transparent'), + clipContent: Boolean(payload?.clipContent), + locked: Boolean(payload?.locked), + hidden: Boolean(payload?.hidden), + }, + ], + stackOrder: [...(doc.stackOrder || []), `frame:${id}`], + }; + return; + } + if (type.endsWith('/setDocument') || type.includes('setDocument')) { + if (payload && typeof payload === 'object') doc = payload; + return; + } + if (type.endsWith('/setDocumentFromCanvas') || type.includes('setDocumentFromCanvas')) { + if (payload && typeof payload === 'object') doc = payload; + return; + } + if (type.endsWith('/updateArtboardFrames')) { + const patches = Array.isArray(payload?.patches) ? payload.patches : []; + const byId = new Map>( + patches.map((item: { id?: string; patch?: Record }) => { + const nextPatch = + item?.patch && typeof item.patch === 'object' && !Array.isArray(item.patch) + ? item.patch + : {}; + return [String(item?.id || ''), nextPatch]; + }) + ); + doc = { + ...doc, + frames: (doc.frames || []).map((frame) => { + const patch = byId.get(String(frame?.id || '')); + if (!patch) return frame; + return { ...frame, ...patch }; + }), + }; + return; + } + if (type.endsWith('/updateArtboardFrame')) { + const id = String(payload?.id || ''); + const patch = + payload?.patch && typeof payload.patch === 'object' ? payload.patch : {}; + doc = { + ...doc, + frames: (doc.frames || []).map((frame) => { + if (String(frame?.id || '') !== id) return frame; + return { ...frame, ...patch }; + }), + }; + return; + } + if (type.endsWith('/patchDocumentNode') || type.includes('patchDocumentNode')) { + const nodeId = String(payload?.nodeId || ''); + const patch = payload?.patch || {}; + const prev = doc.deltaSetLike?.[nodeId]; + if (!prev) return; + doc = { + ...doc, + deltaSetLike: { + ...(doc.deltaSetLike || {}), + [nodeId]: { + ...prev, + ...patch, + attrs: { + ...(prev.attrs || {}), + ...((patch as { attrs?: Record }).attrs || {}), + }, + }, + }, + }; + } + }); + const ctx = { + dispatch, + getDocument: () => doc, + skipHistory: true, + allowDestructive: true, + targetFrameId: null, + } as DesignToolContext; + return { + ctx, + dispatch, + getDoc: () => doc, + setDoc: (next: typeof doc) => { + doc = next; + }, + }; +} + +describe('design tools canvas ops', () => { + it('create_path builds a path shape from points', () => { + const h = createHarness(); + const res = executeDesignTool( + 'create_path', + JSON.stringify({ + x: 10, + y: 10, + width: 120, + height: 80, + points: [ + [10, 10], + [80, 20], + [120, 90], + ], + closed: true, + stroke: '#333', + }), + h.ctx + ); + expect(res.status).toBe('success'); + const nodeId = String(res.artifacts?.nodeId || ''); + expect(nodeId).toBeTruthy(); + const node = h.getDoc().deltaSetLike?.[nodeId]; + expect(String(node?.attrs?.shapeType || '')).toBe('path'); + expect(String(node?.attrs?.path || '')).toContain('M 10 10'); + expect(String(node?.attrs?.path || '')).toContain('Z'); + }); + + it('edit_path_points rewrites existing shape path', () => { + const h = createHarness(); + const created = createShapeNode({ + x: 0, + y: 0, + width: 100, + height: 100, + shapeType: 'path', + path: 'M 0 0 L 10 10', + closed: false, + }); + h.setDoc(addNodeToDocument(h.getDoc(), created.id, created.node)); + const res = executeDesignTool( + 'edit_path_points', + JSON.stringify({ + nodeId: created.id, + points: [ + { x: 0, y: 0 }, + { x: 40, y: 20 }, + { x: 80, y: 40 }, + ], + closed: false, + }), + h.ctx + ); + expect(res.status).toBe('success'); + const node = h.getDoc().deltaSetLike?.[created.id]; + expect(String(node?.attrs?.path || '')).toContain('M 0 0'); + expect(String(node?.attrs?.path || '')).toContain('L 80 40'); + }); + + it('duplicate_frame creates a copied frame', () => { + const h = createHarness(); + const create = executeDesignTool( + 'create_frame', + JSON.stringify({ name: 'Board A', x: 0, y: 0, width: 300, height: 200 }), + h.ctx + ); + const sourceId = String(create.artifacts?.frameId || ''); + const dup = executeDesignTool( + 'duplicate_frame', + JSON.stringify({ frameId: sourceId, dx: 60, dy: 30 }), + h.ctx + ); + expect(dup.status).toBe('success'); + expect(h.getDoc().frames.length).toBe(2); + const copiedId = String(dup.artifacts?.frameId || ''); + expect(copiedId).toBeTruthy(); + expect(copiedId).not.toBe(sourceId); + }); + + it('reorder_frames moves frame key to front', () => { + const h = createHarness(); + const f1 = executeDesignTool('create_frame', JSON.stringify({ name: 'A' }), h.ctx); + const f2 = executeDesignTool('create_frame', JSON.stringify({ name: 'B' }), h.ctx); + const f1Id = String(f1.artifacts?.frameId || ''); + const f2Id = String(f2.artifacts?.frameId || ''); + const res = executeDesignTool( + 'reorder_frames', + JSON.stringify({ frameIds: [f1Id], action: 'front' }), + h.ctx + ); + expect(res.status).toBe('success'); + const stack = (h.getDoc().stackOrder || []).filter((key) => key.startsWith('frame:')); + expect(stack[stack.length - 1]).toBe(`frame:${f1Id}`); + expect(stack[0]).toBe(`frame:${f2Id}`); + }); + + it('append_path_points continues an existing path', () => { + const h = createHarness(); + const created = createShapeNode({ + x: 0, + y: 0, + width: 100, + height: 100, + shapeType: 'pen', + path: 'M 0 0 L 10 10', + closed: false, + }); + h.setDoc(addNodeToDocument(h.getDoc(), created.id, created.node)); + const res = executeDesignTool( + 'append_path_points', + JSON.stringify({ + nodeId: created.id, + points: [{ x: 40, y: 20 }], + }), + h.ctx + ); + expect(res.status).toBe('success'); + expect(String(h.getDoc().deltaSetLike?.[created.id]?.attrs?.path || '')).toContain('L 40 20'); + }); + + it('simplify_path reduces vertices', () => { + const h = createHarness(); + const created = createShapeNode({ + x: 0, + y: 0, + width: 200, + height: 20, + shapeType: 'path', + path: 'M 0 0 L 10 0.1 L 20 0 L 30 0.2 L 100 0', + closed: false, + }); + h.setDoc(addNodeToDocument(h.getDoc(), created.id, created.node)); + const res = executeDesignTool( + 'simplify_path', + JSON.stringify({ nodeId: created.id, tolerance: 1 }), + h.ctx + ); + expect(res.status).toBe('success'); + const path = String(h.getDoc().deltaSetLike?.[created.id]?.attrs?.path || ''); + expect(path.split('L').length).toBeLessThan(5); + expect(path).toContain('M 0 0'); + expect(path).toContain('L 100 0'); + }); + + it('lock_frames locks matching artboards', () => { + const h = createHarness(); + const create = executeDesignTool( + 'create_frame', + JSON.stringify({ name: 'Board', x: 0, y: 0, width: 200, height: 200 }), + h.ctx + ); + const frameId = String(create.artifacts?.frameId || ''); + const res = executeDesignTool( + 'lock_frames', + JSON.stringify({ frameIds: [frameId] }), + h.ctx + ); + expect(res.status).toBe('success'); + expect(h.getDoc().frames.find((f) => f.id === frameId)?.locked).toBe(true); + }); + + it('set_active_tool dispatches pencil', () => { + const h = createHarness(); + const res = executeDesignTool( + 'set_active_tool', + JSON.stringify({ tool: 'pencil' }), + h.ctx + ); + expect(res.status).toBe('success'); + expect(res.artifacts?.tool).toBe('pencil'); + const types = h.dispatch.mock.calls.map((call) => String(call[0]?.type || '')); + expect(types.some((type) => type.includes('setActiveTool'))).toBe(true); + }); + + it('smooth_path adds Chaikin midpoints', () => { + const h = createHarness(); + const created = createShapeNode({ + x: 0, + y: 0, + width: 100, + height: 100, + shapeType: 'path', + path: 'M 0 0 L 50 80 L 100 0', + closed: false, + }); + h.setDoc(addNodeToDocument(h.getDoc(), created.id, created.node)); + const before = String(h.getDoc().deltaSetLike?.[created.id]?.attrs?.path || ''); + const res = executeDesignTool( + 'smooth_path', + JSON.stringify({ nodeId: created.id, iterations: 1 }), + h.ctx + ); + expect(res.status).toBe('success'); + const after = String(h.getDoc().deltaSetLike?.[created.id]?.attrs?.path || ''); + expect(after.split('L').length).toBeGreaterThan(before.split('L').length); + }); + + it('hide_frames hides matching artboards', () => { + const h = createHarness(); + const create = executeDesignTool( + 'create_frame', + JSON.stringify({ name: 'Board', x: 0, y: 0, width: 200, height: 200 }), + h.ctx + ); + const frameId = String(create.artifacts?.frameId || ''); + const res = executeDesignTool('hide_frames', JSON.stringify({ frameIds: [frameId] }), h.ctx); + expect(res.status).toBe('success'); + expect(h.getDoc().frames.find((f) => f.id === frameId)?.hidden).toBe(true); + }); + + it('hide_nodes sets attrs.hidden', () => { + const h = createHarness(); + const created = createShapeNode({ + x: 0, + y: 0, + width: 40, + height: 40, + shapeType: 'rect', + }); + h.setDoc(addNodeToDocument(h.getDoc(), created.id, created.node)); + const res = executeDesignTool( + 'hide_nodes', + JSON.stringify({ nodeIds: [created.id] }), + h.ctx + ); + expect(res.status).toBe('success'); + expect(String(h.getDoc().deltaSetLike?.[created.id]?.attrs?.hidden)).toBe('true'); + }); + + it('set_grid dispatches grid on', () => { + const h = createHarness(); + const res = executeDesignTool('set_grid', JSON.stringify({ enabled: true }), h.ctx); + expect(res.status).toBe('success'); + const types = h.dispatch.mock.calls.map((call) => String(call[0]?.type || '')); + expect(types.some((type) => type.includes('setGridMode'))).toBe(true); + }); +}); diff --git a/apps/web/src/components/editor/panels/agent/__tests__/sceneMutation.test.ts b/apps/web/src/components/editor/panels/agent/__tests__/sceneMutation.test.ts index d6180d15..9d8ffca8 100644 --- a/apps/web/src/components/editor/panels/agent/__tests__/sceneMutation.test.ts +++ b/apps/web/src/components/editor/panels/agent/__tests__/sceneMutation.test.ts @@ -66,12 +66,12 @@ describe('Scene Mutation Pipeline', () => { currentRevision: 42, }); expect(ok.ok).toBe(true); - const legacy = sceneMutationRevision({ + const prior = sceneMutationRevision({ source: 'ai', baseRevision: 0, currentRevision: 5, }); - expect(legacy.ok).toBe(true); + expect(prior.ok).toBe(true); }); it('gateSceneMutation runs validate → permission → revision in order', () => { @@ -176,7 +176,7 @@ describe('PR8 revision rebase / reject', () => { it('rejects delete_frame of a still-living artboard', () => { const out = rebaseSceneMutationOps( - [{ name: 'delete_frame', op_id: 'df', args: { id: 'f1' } }], + [{ name: 'delete_frame', op_id: 'df', args: { frameId: 'f1' } }], sceneDoc([], ['f1']) ); expect(out.action).toBe('reject'); diff --git a/apps/web/src/components/editor/panels/agent/__tests__/toolOpsContract.extract.test.ts b/apps/web/src/components/editor/panels/agent/__tests__/toolOpsContract.extract.test.ts index 563292fe..4316612e 100644 --- a/apps/web/src/components/editor/panels/agent/__tests__/toolOpsContract.extract.test.ts +++ b/apps/web/src/components/editor/panels/agent/__tests__/toolOpsContract.extract.test.ts @@ -2,13 +2,13 @@ import { describe, expect, it } from 'vitest'; import { extractToolOpsFromText, setAllowedCanvasToolKeys } from '../toolOpsContract'; describe('extractToolOpsFromText', () => { - it('parses fenced ops JSON', () => { + it('parses fenced tool_ops JSON', () => { setAllowedCanvasToolKeys([]); const text = [ 'Sure, here is a plate.', '```json', JSON.stringify({ - ops: [ + tool_ops: [ { name: 'create_shape', args: { shapeType: 'rect', x: 10, y: 20, width: 100, height: 40 }, @@ -23,20 +23,9 @@ describe('extractToolOpsFromText', () => { expect(ops[0]?.args.shapeType).toBe('rect'); }); - it('accepts tool/parameters aliases', () => { - setAllowedCanvasToolKeys(['update_node']); - const text = JSON.stringify({ - tools: [{ tool: 'update_node', parameters: { nodeId: 'n1', fill: '#111' } }], - }); - const ops = extractToolOpsFromText(`\`\`\`\n${text}\n\`\`\``); - expect(ops).toEqual([ - { name: 'update_node', args: { nodeId: 'n1', fill: '#111' } }, - ]); - }); - - it('drops disallowed tools when catalog is loaded', () => { + it('ignores disallowed tools when catalog is loaded', () => { setAllowedCanvasToolKeys(['create_text']); - const text = '```json\n{"ops":[{"name":"delete_nodes","args":{"nodeIds":["n1"]}}]}\n```'; + const text = '```json\n{"tool_ops":[{"name":"delete_nodes","args":{"nodeIds":["n1"]}}]}\n```'; expect(extractToolOpsFromText(text)).toEqual([]); }); }); diff --git a/apps/web/src/components/editor/panels/agent/agentSceneContext.ts b/apps/web/src/components/editor/panels/agent/agentSceneContext.ts index 213c3185..720b5134 100644 --- a/apps/web/src/components/editor/panels/agent/agentSceneContext.ts +++ b/apps/web/src/components/editor/panels/agent/agentSceneContext.ts @@ -397,7 +397,7 @@ export type SpatialSummary = { empty_rects: SpatialBox[]; /** World-space slots for create_frame (same size as focus plate). */ new_frame_slots: SpatialBox[]; - /** @deprecated Not set — host must not invent place WxH for the model. */ + /** Not set — host must not invent place WxH for the model. */ suggested_place?: SpatialBox; /** Raw camera viewport in world coords (sensor only). */ viewport?: SpatialBox; diff --git a/apps/web/src/components/editor/panels/agent/codingCli.ts b/apps/web/src/components/editor/panels/agent/codingCli.ts index 04736ed5..f8f6a8bd 100644 --- a/apps/web/src/components/editor/panels/agent/codingCli.ts +++ b/apps/web/src/components/editor/panels/agent/codingCli.ts @@ -73,10 +73,10 @@ You are editing a Recombyn design canvas. Always read \`scene.json\` in this wor When the user asks for design changes, end your reply with ONE JSON fence that the editor will apply: \`\`\`json -{ "ops": [ { "name": "create_shape", "args": { "shapeType": "rect", "x": 40, "y": 40, "width": 200, "height": 120, "fill": "#ffffff" } } ] } +{ "tool_ops": [ { "name": "create_shape", "args": { "shapeType": "rect", "x": 40, "y": 40, "width": 200, "height": 120, "fill": "#ffffff" } } ] } \`\`\` -Allowed \`name\` values (subset): create_frame, create_shape, create_text, create_image, create_svg, update_node, update_frame, delete_nodes, delete_frame, align_nodes, distribute_nodes, reorder_nodes, duplicate_nodes, set_canvas_background, set_viewport. +Allowed \`name\` values (subset): create_frame, duplicate_frame, reorder_frames, fit_frame_to_content, lock_frames, hide_frames, clip_frames, create_shape, create_path, create_text, create_image, create_svg, update_node, edit_path_points, append_path_points, simplify_path, smooth_path, close_path, apply_brush_preset, update_frame, hide_nodes, delete_nodes, delete_frame, align_nodes, distribute_nodes, reorder_nodes, duplicate_nodes, rotate_nodes, bind_nodes_to_frame, unbind_nodes, set_canvas_background, set_viewport, set_active_tool, set_grid. Hard rules: - Prefer \`update_node\` with existing \`nodeId\` from scene.json over recreating. @@ -168,7 +168,7 @@ export function buildCodingCliEnrichedPrompt(opts: { 'User request (only this part is from the user):', opts.userPrompt.trim(), '', - 'When done, emit a final ```json fence with { "ops": [...] } so the editor can paint the canvas.', + 'When done, emit a final ```json fence with { "tool_ops": [...] } so the editor can paint the canvas.', ].join('\n'), ].join('\n\n'); } diff --git a/apps/web/src/components/editor/panels/agent/composer/AgentComposerShell.tsx b/apps/web/src/components/editor/panels/agent/composer/AgentComposerShell.tsx index 751f7bf7..7e6e472d 100644 --- a/apps/web/src/components/editor/panels/agent/composer/AgentComposerShell.tsx +++ b/apps/web/src/components/editor/panels/agent/composer/AgentComposerShell.tsx @@ -282,7 +282,7 @@ type Props = { onOpenChange?: (open: boolean) => void; /** Dropdown placement when using `panel`. @default top-start */ panelPlacement?: Placement; - /** @deprecated Prefer `panel` + `onOpenChange` (legacy floating-ui refs). */ + /** Prefer `panel` + `onOpenChange` (floating-ui refs). */ ref?: (node: HTMLElement | null) => void; onClick?: () => void; getReferenceProps?: (userProps?: Record) => Record; diff --git a/apps/web/src/components/editor/panels/agent/customLlmProviders.ts b/apps/web/src/components/editor/panels/agent/customLlmProviders.ts index 1730a57f..a3496708 100644 --- a/apps/web/src/components/editor/panels/agent/customLlmProviders.ts +++ b/apps/web/src/components/editor/panels/agent/customLlmProviders.ts @@ -1,4 +1,4 @@ -/** Custom LLM provider prefs (OpenAI-compatible). API keys never stored as plaintext. */ +/** Custom LLM provider prefs (OpenAI-style). API keys never stored as plaintext. */ import type { LlmModel, ModelReferenceType } from '@/service/chat'; import { apiClient, apiQuery, queryClient } from '@/service/client'; @@ -180,7 +180,7 @@ export async function encryptApiKeyLocal(plaintext: string): Promise { export async function decryptApiKeyLocal(cipher: string): Promise { const raw = String(cipher || ''); - if (!raw.startsWith('enc:v1:')) return raw; // legacy plaintext migrate path + if (!raw.startsWith('enc:v1:')) return ''; try { const key = await getOrCreateDeviceKey(); const packed = b64ToBytes(raw.slice('enc:v1:'.length)); @@ -381,7 +381,7 @@ export async function removeCustomLlmProvider(id: string): Promise { /** Single-flight 鈥?Account Agent mounts RoutePrefs + panel both used to call this. */ let _hydrateProvidersInflight: Promise | null = null; -/** Pull server vault + migrate legacy plaintext local keys. */ +/** Pull server vault and hydrate local encrypted providers. */ export async function hydrateCustomLlmProviders(): Promise { if (_hydrateProvidersInflight) return _hydrateProvidersInflight; @@ -402,7 +402,7 @@ async function hydrateCustomLlmProvidersBody(): Promise { const token = getToken(); let local = readLocalRaw(); - // Migrate legacy plaintext 鈫?ciphertext (or server). + // Persist encrypted/provider-backed keys only. const migrated: CustomLlmProvider[] = []; for (const p of local) { const plain = String(p.apiKey || '').trim(); diff --git a/apps/web/src/components/editor/panels/agent/designAgentEventRouter.ts b/apps/web/src/components/editor/panels/agent/designAgentEventRouter.ts index a7aa3362..c46c4d0a 100644 --- a/apps/web/src/components/editor/panels/agent/designAgentEventRouter.ts +++ b/apps/web/src/components/editor/panels/agent/designAgentEventRouter.ts @@ -349,10 +349,6 @@ export function createDesignAgentEventRouter(opts: { const scheduleAnalysisDeltaFlush = () => { if (analysisFrame != null) return; - if (typeof requestAnimationFrame !== 'function') { - flushAnalysisDelta(); - return; - } analysisFrame = requestAnimationFrame(() => flushAnalysisDelta()); }; diff --git a/apps/web/src/components/editor/panels/agent/designTools.ts b/apps/web/src/components/editor/panels/agent/designTools.ts index 74329669..937859a1 100644 --- a/apps/web/src/components/editor/panels/agent/designTools.ts +++ b/apps/web/src/components/editor/panels/agent/designTools.ts @@ -12,15 +12,19 @@ import { removeArtboardFrames, setCanvasMeta, setDocument, + setActiveTool, + setGridMode, setDocumentFromCanvas, startImageProcess, updateArtboardFrame, + updateArtboardFrames, type ArtboardFrame, } from '@/store/modules/editor'; import { exportFabricImage } from '@/components/rcb/scene/paint/exportImage'; import { addNodeToDocument, cloneSceneValue, + reconcileStackOrder, removeNodesFromDocument, reorderNodesInDocument } from '@/components/rcb/scene/document/sceneDocument'; @@ -289,7 +293,7 @@ export function rebaseSceneMutationOps( }; if (name === 'delete_frame') { - const fid = mutationArgIds(args, ['frameId', 'id'])[0] || ''; + const fid = mutationArgIds(args, ['frameId'])[0] || ''; if (fid && sceneHasFrame(doc, fid)) { return { action: 'reject', @@ -303,7 +307,7 @@ export function rebaseSceneMutationOps( } if (name === 'delete_nodes') { - const ids = mutationArgIds(args, ['nodeIds', 'ids', 'nodeId', 'id']); + const ids = mutationArgIds(args, ['nodeIds']); const live = ids.filter((id) => sceneHasNode(doc, id)); if (live.length) { return { @@ -318,7 +322,7 @@ export function rebaseSceneMutationOps( } if (name.startsWith('create_')) { - if (name === 'create_frame' || name === 'create_page') { + if (name === 'create_frame') { kept.push(op); continue; } @@ -332,7 +336,7 @@ export function rebaseSceneMutationOps( } if (name === 'update_frame') { - const fid = mutationArgIds(args, ['frameId', 'id'])[0] || ''; + const fid = mutationArgIds(args, ['frameId'])[0] || ''; if (fid && sceneHasFrame(doc, fid)) { kept.push(op); continue; @@ -341,7 +345,7 @@ export function rebaseSceneMutationOps( continue; } - const targetIds = mutationArgIds(args, ['nodeIds', 'ids', 'nodeId', 'id']); + const targetIds = mutationArgIds(args, ['nodeIds', 'nodeId']); if (!targetIds.length) { kept.push(op); continue; @@ -357,7 +361,6 @@ export function rebaseSceneMutationOps( } const nextArgs = { ...args }; if (Array.isArray(args.nodeIds)) nextArgs.nodeIds = liveIds; - else if (Array.isArray(args.ids)) nextArgs.ids = liveIds; else nextArgs.nodeId = liveIds[0]; kept.push({ ...op, args: nextArgs }); } @@ -532,7 +535,7 @@ function resolveFrameOpId( ctx: DesignToolContext ): string { const focus = String(ctx.targetFrameId || '').trim(); - const fromArgs = String(args.frameId ?? args.id ?? '').trim(); + const fromArgs = String(args.frameId || '').trim(); // Honor model frameId when present — do not silently retarget to focus. if (fromArgs) return fromArgs; return focus; @@ -592,7 +595,7 @@ export const UNAVAILABLE_CAPABILITIES: Array<{ { id: 'hand_tool', label: 'Hand / select tool', - hint: 'Not wired for Agent. Use the bottom tool strip or Space to pan.', + hint: 'Use set_active_tool tool=pan|select. Space still pans in the editor.', }, { id: 'tour', @@ -720,8 +723,19 @@ export const DESIGN_TOOL_NAMES = [ 'list_capabilities', 'ask_user', 'create_frame', + 'duplicate_frame', + 'reorder_frames', + 'fit_frame_to_content', + 'lock_frames', + 'hide_frames', + 'clip_frames', 'update_frame', 'create_shape', + 'create_path', + 'append_path_points', + 'simplify_path', + 'smooth_path', + 'close_path', 'create_text', 'outline_text', 'create_image', @@ -737,17 +751,242 @@ export const DESIGN_TOOL_NAMES = [ 'ungroup_nodes', 'duplicate_nodes', 'flip_nodes', + 'rotate_nodes', + 'bind_nodes_to_frame', + 'unbind_nodes', 'set_viewport', + 'set_active_tool', + 'set_grid', 'set_canvas_background', 'image_process', 'export_canvas', + 'edit_path_points', + 'apply_brush_preset', 'set_agent_mode', 'toggle_editor_panel', + 'hide_nodes', 'delete_nodes', 'delete_frame', 'finish', ] as const; +type ScenePoint = { x: number; y: number }; + +function coerceScenePoint(raw: unknown): ScenePoint | null { + if (!raw) return null; + if (Array.isArray(raw)) { + const x = Number(raw[0]); + const y = Number(raw[1]); + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + return { x, y }; + } + if (typeof raw !== 'object') return null; + const row = raw as Record; + const x = Number(row.x); + const y = Number(row.y); + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + return { x, y }; +} + +function readScenePoints(raw: unknown): ScenePoint[] { + if (!Array.isArray(raw)) return []; + return raw.map((entry) => coerceScenePoint(entry)).filter((entry): entry is ScenePoint => Boolean(entry)); +} + +function pointsToPath(points: ScenePoint[], closed: boolean): string { + if (!points.length) return ''; + const [first, ...rest] = points; + const chunks = [`M ${first.x} ${first.y}`]; + for (const p of rest) chunks.push(`L ${p.x} ${p.y}`); + if (closed && points.length > 2) chunks.push('Z'); + return chunks.join(' '); +} + +const PATH_SHAPE_TYPES = new Set(['path', 'pen', 'pencil']); + +function isEditablePathNode(node: SceneNode | undefined | null): boolean { + if (!node || node.key !== 'shape') return false; + return PATH_SHAPE_TYPES.has(String(node.attrs?.shapeType || '').toLowerCase()); +} + +function parsePathPoints(path: string): { points: ScenePoint[]; closed: boolean } { + const raw = String(path || '').trim(); + const closed = /z\s*$/i.test(raw); + const tokens = raw.replace(/,/g, ' ').match(/[MmLlHhVvZz]|-?\d*\.?\d+(?:e[-+]?\d+)?/g) || []; + const points: ScenePoint[] = []; + let cmd = 'L'; + let i = 0; + let lastX = 0; + let lastY = 0; + while (i < tokens.length) { + const token = tokens[i]; + if (/^[MmLlHhVvZz]$/.test(token)) { + cmd = token.toUpperCase(); + i += 1; + continue; + } + const n = Number(token); + if (!Number.isFinite(n)) { + i += 1; + continue; + } + if (cmd === 'H') { + lastX = n; + points.push({ x: lastX, y: lastY }); + i += 1; + continue; + } + if (cmd === 'V') { + lastY = n; + points.push({ x: lastX, y: lastY }); + i += 1; + continue; + } + const y = Number(tokens[i + 1]); + if (!Number.isFinite(y)) { + i += 1; + continue; + } + lastX = n; + lastY = y; + if (cmd === 'M' || cmd === 'L') points.push({ x: lastX, y: lastY }); + if (cmd === 'M') cmd = 'L'; + i += 2; + } + return { points, closed }; +} + +function pointSegDist(p: ScenePoint, a: ScenePoint, b: ScenePoint): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + if (dx === 0 && dy === 0) return Math.hypot(p.x - a.x, p.y - a.y); + const t = Math.max( + 0, + Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy)) + ); + return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy)); +} + +function simplifyPolyline(points: ScenePoint[], tolerance: number): ScenePoint[] { + if (points.length <= 2) return points; + const keep = Array.from({ length: points.length }, () => false); + keep[0] = true; + keep[points.length - 1] = true; + const stack: Array<[number, number]> = [[0, points.length - 1]]; + while (stack.length) { + const [start, end] = stack.pop()!; + let maxD = -1; + let maxI = -1; + for (let i = start + 1; i < end; i += 1) { + const d = pointSegDist(points[i], points[start], points[end]); + if (d > maxD) { + maxD = d; + maxI = i; + } + } + if (maxD > tolerance && maxI > start) { + keep[maxI] = true; + stack.push([start, maxI], [maxI, end]); + } + } + return points.filter((_, i) => keep[i]); +} + +function lerpPoint(a: ScenePoint, b: ScenePoint, t: number): ScenePoint { + return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; +} + +function smoothPolyline( + points: ScenePoint[], + iterations: number, + closed: boolean +): ScenePoint[] { + if (points.length < 3) return points; + let next = points; + const rounds = Math.max(1, Math.min(4, Math.round(iterations))); + for (let r = 0; r < rounds; r += 1) { + const out: ScenePoint[] = []; + const n = next.length; + if (closed) { + for (let i = 0; i < n; i += 1) { + const a = next[i]; + const b = next[(i + 1) % n]; + out.push(lerpPoint(a, b, 0.25), lerpPoint(a, b, 0.75)); + } + } else { + out.push(next[0]); + for (let i = 0; i < n - 1; i += 1) { + out.push(lerpPoint(next[i], next[i + 1], 0.25), lerpPoint(next[i], next[i + 1], 0.75)); + } + out.push(next[n - 1]); + } + next = out; + } + return next; +} + +function resolveEditablePathNode( + doc: SceneDocument, + nodeId: string +): { node: SceneNode } | { error: AgentToolResult } { + const node = doc.deltaSetLike?.[nodeId]; + if (!node) { + return { error: { status: 'error', summary: `Node not found: ${nodeId}` } }; + } + if (!isEditablePathNode(node)) { + const kind = String(node.attrs?.shapeType || node.key || 'node'); + return { + error: { + status: 'error', + summary: `Node ${nodeId} is ${kind}; expected path/pen/pencil`, + }, + }; + } + return { node }; +} + +function parseFrameOpIds(args: Record, ctx: DesignToolContext): string[] { + if (Array.isArray(args.frameIds)) { + return [...new Set(args.frameIds.map((id) => String(id || '').trim()).filter(Boolean))]; + } + const focus = String(ctx.targetFrameId || '').trim(); + return focus ? [focus] : []; +} + +function reorderKeysWithAction( + keys: string[], + selected: Set, + action: 'front' | 'back' | 'forward' | 'backward' +): string[] { + const untouched = keys.filter((key) => !selected.has(key)); + const picked = keys.filter((key) => selected.has(key)); + if (!picked.length) return keys; + if (action === 'front') return [...untouched, ...picked]; + if (action === 'back') return [...picked, ...untouched]; + if (action === 'forward') { + const next = [...keys]; + for (let i = next.length - 2; i >= 0; i -= 1) { + const cur = next[i]; + const after = next[i + 1]; + if (selected.has(cur) && !selected.has(after)) { + next[i] = after; + next[i + 1] = cur; + } + } + return next; + } + const next = [...keys]; + for (let i = 1; i < next.length; i += 1) { + const cur = next[i]; + const before = next[i - 1]; + if (selected.has(cur) && !selected.has(before)) { + next[i] = before; + next[i - 1] = cur; + } + } + return next; +} + function parseArgs(raw: string): Record { try { const v = JSON.parse(raw || '{}'); @@ -1965,6 +2204,34 @@ function execCreateShape( }; } +function execCreatePath( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const points = readScenePoints(args.points); + const closed = truthy(args.closed); + if (points.length < 2) { + return { + status: 'error', + summary: 'create_path requires points (>=2)', + next_actions: ['Pass points as [[x,y], ...]'], + }; + } + return execCreateShape( + { + ...args, + shapeType: 'path', + path: pointsToPath(points, closed), + closed, + }, + ctx, + doc, + pushHistory + ); +} + function execCreateText( args: Record, ctx: DesignToolContext, @@ -2350,6 +2617,234 @@ function execUpdateNode( }; } +function execEditPathPoints( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const nodeId = String(args.nodeId || '').trim(); + if (!nodeId) return { status: 'error', summary: 'nodeId required' }; + const resolved = resolveEditablePathNode(doc, nodeId); + if ('error' in resolved) return resolved.error; + const points = readScenePoints(args.points); + if (points.length < 2) { + return { status: 'error', summary: 'edit_path_points requires points (>=2)' }; + } + const closed = + args.closed != null ? truthy(args.closed) : truthy(resolved.node.attrs?.closed); + return execUpdateNode( + { + nodeId, + path: pointsToPath(points, closed), + closed, + }, + ctx, + doc, + pushHistory + ); +} + +function execAppendPathPoints( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const nodeId = String(args.nodeId || '').trim(); + if (!nodeId) return { status: 'error', summary: 'nodeId required' }; + const resolved = resolveEditablePathNode(doc, nodeId); + if ('error' in resolved) return resolved.error; + const extra = readScenePoints(args.points); + if (extra.length < 1) { + return { status: 'error', summary: 'append_path_points requires args.points (>=1)' }; + } + const current = parsePathPoints(String(resolved.node.attrs?.path || '')); + const closed = + args.closed != null ? truthy(args.closed) : current.closed || truthy(resolved.node.attrs?.closed); + const next = [...current.points, ...extra]; + if (next.length < 2) { + return { status: 'error', summary: 'append_path_points needs at least 2 total points' }; + } + return execUpdateNode( + { + nodeId, + path: pointsToPath(next, closed), + closed, + }, + ctx, + doc, + pushHistory + ); +} + +function execSimplifyPath( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const nodeId = String(args.nodeId || '').trim(); + if (!nodeId) return { status: 'error', summary: 'nodeId required' }; + const resolved = resolveEditablePathNode(doc, nodeId); + if ('error' in resolved) return resolved.error; + const current = parsePathPoints(String(resolved.node.attrs?.path || '')); + if (current.points.length < 3) { + return { + status: 'warning', + summary: `Path ${nodeId} already has ${current.points.length} point(s)`, + artifacts: { nodeId, pointCount: current.points.length }, + }; + } + const tolerance = Math.max(0.25, num(args.tolerance, 2)); + const simplified = simplifyPolyline(current.points, tolerance); + const closed = current.closed || truthy(resolved.node.attrs?.closed); + if (simplified.length < 2) { + return { status: 'error', summary: `simplify_path collapsed ${nodeId}` }; + } + return execUpdateNode( + { + nodeId, + path: pointsToPath(simplified, closed), + closed, + }, + ctx, + doc, + pushHistory + ); +} + +function execSmoothPath( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const nodeId = String(args.nodeId || '').trim(); + if (!nodeId) return { status: 'error', summary: 'nodeId required' }; + const resolved = resolveEditablePathNode(doc, nodeId); + if ('error' in resolved) return resolved.error; + const current = parsePathPoints(String(resolved.node.attrs?.path || '')); + if (current.points.length < 3) { + return { + status: 'warning', + summary: `Path ${nodeId} needs at least 3 points to smooth`, + artifacts: { nodeId, pointCount: current.points.length }, + }; + } + const closed = current.closed || truthy(resolved.node.attrs?.closed); + const iterations = Math.max(1, Math.min(4, Math.round(num(args.iterations, 1)))); + const smoothed = smoothPolyline(current.points, iterations, closed); + return execUpdateNode( + { + nodeId, + path: pointsToPath(smoothed, closed), + closed, + }, + ctx, + doc, + pushHistory + ); +} + +function execClosePath( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const nodeId = String(args.nodeId || '').trim(); + if (!nodeId) return { status: 'error', summary: 'nodeId required' }; + const resolved = resolveEditablePathNode(doc, nodeId); + if ('error' in resolved) return resolved.error; + const current = parsePathPoints(String(resolved.node.attrs?.path || '')); + if (current.points.length < 3) { + return { + status: 'error', + summary: `close_path needs at least 3 points (${nodeId})`, + }; + } + if (current.closed || truthy(resolved.node.attrs?.closed)) { + return { + status: 'warning', + summary: `Path ${nodeId} is already closed`, + artifacts: { nodeId }, + }; + } + return execUpdateNode( + { + nodeId, + path: pointsToPath(current.points, true), + closed: true, + }, + ctx, + doc, + pushHistory + ); +} + +const BRUSH_PRESET_MAP: Record< + string, + { brushStyle: string; borderWidth: number; pressureEnabled: boolean } +> = { + ink: { brushStyle: 'vector-ink', borderWidth: 2, pressureEnabled: true }, + pencil: { brushStyle: 'vector-pencil', borderWidth: 2, pressureEnabled: true }, + marker: { brushStyle: 'vector-marker', borderWidth: 6, pressureEnabled: false }, + calligraphy: { brushStyle: 'vector-calligraphy', borderWidth: 4, pressureEnabled: true }, + brush: { brushStyle: 'vector-brush', borderWidth: 5, pressureEnabled: true }, +}; + +function execApplyBrushPreset( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const preset = String(args.preset || '').trim().toLowerCase(); + const spec = BRUSH_PRESET_MAP[preset]; + if (!spec) { + return { + status: 'error', + summary: `Unknown brush preset: ${preset || '(empty)'}`, + next_actions: [`Use one of: ${Object.keys(BRUSH_PRESET_MAP).join('|')}`], + }; + } + const ids = parseNodeIds(args); + if (!ids.length) return { status: 'error', summary: 'nodeIds required' }; + const done: string[] = []; + for (const nodeId of ids) { + const node = doc.deltaSetLike?.[nodeId]; + if (!node || node.key !== 'shape') continue; + const shapeType = String(node.attrs?.shapeType || '').toLowerCase(); + const editable = shapeType === 'path' || shapeType === 'pen' || shapeType === 'pencil'; + if (!editable) continue; + const result = execUpdateNode( + { + nodeId, + brushStyle: spec.brushStyle, + borderWidth: spec.borderWidth, + pressureEnabled: spec.pressureEnabled, + }, + ctx, + doc, + pushHistory + ); + if (result.status !== 'error') done.push(nodeId); + } + if (!done.length) { + return { + status: 'error', + summary: 'No editable path/pen/pencil nodes found for apply_brush_preset', + artifacts: { requestedNodeIds: ids }, + }; + } + return { + status: 'success', + summary: `Applied preset ${preset} to ${done.length} node(s)`, + artifacts: { nodeIds: done, preset }, + }; +} + function execCreateFrame( args: Record, ctx: DesignToolContext, @@ -2545,6 +3040,47 @@ function execSetViewport( } +function execSetActiveTool( + args: Record, + ctx: DesignToolContext, + _doc: SceneDocument, + _pushHistory: () => void +): AgentToolResult { + const tool = String(args.tool || '').trim().toLowerCase(); + const allowed = new Set(['select', 'pan', 'frame', 'text', 'shape', 'image', 'pen', 'pencil']); + if (!allowed.has(tool)) { + return { + status: 'error', + summary: `Unknown canvas tool: ${tool || '(empty)'}`, + next_actions: [`Use tool one of: ${[...allowed].join('|')}`], + }; + } + ctx.dispatch(setActiveTool(tool)); + return { + status: 'success', + summary: `Active tool set to ${tool}`, + artifacts: { tool }, + }; +} + +function execSetGrid( + args: Record, + ctx: DesignToolContext, + _doc: SceneDocument, + _pushHistory: () => void +): AgentToolResult { + if (args.enabled == null) { + return { status: 'error', summary: 'set_grid requires enabled (boolean)' }; + } + const enabled = truthy(args.enabled); + ctx.dispatch(setGridMode(enabled)); + return { + status: 'success', + summary: enabled ? 'Grid snap on' : 'Grid snap off', + artifacts: { enabled }, + }; +} + function execSetCanvasBackground( args: Record, ctx: DesignToolContext, @@ -3270,6 +3806,113 @@ function execFlipNodes( } +function execRotateNodes( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const ids = parseNodeIds(args); + if (!ids.length) return { status: 'error', summary: 'nodeIds required' }; + if (args.rotation == null) { + return { status: 'error', summary: 'rotate_nodes requires rotation (degrees)' }; + } + const rotation = num(args.rotation, NaN); + if (!Number.isFinite(rotation)) { + return { status: 'error', summary: 'rotate_nodes requires rotation (degrees)' }; + } + const done: string[] = []; + for (const nodeId of ids) { + if (!doc.deltaSetLike?.[nodeId]) continue; + const result = execUpdateNode({ nodeId, rotation }, ctx, doc, pushHistory); + if (result.status !== 'error') done.push(nodeId); + } + if (!done.length) return { status: 'error', summary: 'No matching nodes to rotate' }; + return { + status: 'success', + summary: `Rotated ${done.length} node(s)`, + artifacts: { nodeIds: done, rotation }, + }; +} + +function bindNodesInDocument( + doc: SceneDocument, + nodeIds: string[], + frameId: string | null +): SceneDocument { + const next = cloneSceneValue(doc) as SceneDocument; + let orderCursor = 0; + if (frameId) { + const existing = Object.values(next.deltaSetLike || {}) + .filter((item) => String(item?.attrs?.frameId || '').trim() === frameId) + .map((item) => Number(item?.attrs?.frameOrder)) + .filter(Number.isFinite); + orderCursor = existing.length ? Math.max(...existing) + 1 : 0; + } + const unboundKeys: string[] = []; + for (const nodeId of nodeIds) { + const node = next.deltaSetLike?.[nodeId]; + if (!node) continue; + const attrs = { ...(node.attrs || {}) }; + if (frameId) { + attrs.frameId = frameId; + attrs.frameOrder = orderCursor; + orderCursor += 1; + } else { + delete attrs.frameId; + delete attrs.frameOrder; + unboundKeys.push(`node:${nodeId}`); + } + next.deltaSetLike[nodeId] = { ...node, attrs }; + } + if (unboundKeys.length) { + const order = Array.isArray(next.stackOrder) ? next.stackOrder.map(String) : []; + const keep = order.filter((key) => !unboundKeys.includes(key)); + next.stackOrder = [...keep, ...unboundKeys.filter((key) => !keep.includes(key))]; + } + reconcileStackOrder(next); + return next; +} + +function execBindNodesToFrame( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const frameId = resolveFrameOpId(args, ctx); + if (!frameId) return { status: 'error', summary: 'frameId required' }; + if (!frameById(doc, frameId)) return { status: 'error', summary: `frame not found: ${frameId}` }; + const ids = parseNodeIds(args); + if (!ids.length) return { status: 'error', summary: 'nodeIds required' }; + const next = bindNodesInDocument(doc, ids, frameId); + pushHistory(); + ctx.dispatch(setDocumentFromCanvas(next)); + return { + status: 'success', + summary: `Bound ${ids.length} node(s) to frame ${frameId}`, + artifacts: { nodeIds: ids, frameId }, + }; +} + +function execUnbindNodes( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const ids = parseNodeIds(args); + if (!ids.length) return { status: 'error', summary: 'nodeIds required' }; + const next = bindNodesInDocument(doc, ids, null); + pushHistory(); + ctx.dispatch(setDocumentFromCanvas(next)); + return { + status: 'success', + summary: `Unbound ${ids.length} node(s) from artboards`, + artifacts: { nodeIds: ids }, + }; +} + function execDeleteNodes( args: Record, ctx: DesignToolContext, @@ -3357,6 +4000,239 @@ function execDeleteFrame( } +function execDuplicateFrame( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const frameId = resolveFrameOpId(args, ctx); + if (!frameId) return { status: 'error', summary: 'frameId required' }; + const source = frameById(doc, frameId); + if (!source) return { status: 'error', summary: `frame not found: ${frameId}` }; + const dx = Number.isFinite(Number(args.dx)) ? Number(args.dx) : 48; + const dy = Number.isFinite(Number(args.dy)) ? Number(args.dy) : 48; + const beforeIds = new Set(listFrames(doc).map((f) => String(f.id))); + const copyName = args.name != null ? String(args.name) : `${String(source.name || 'Frame')} Copy`; + ctx.dispatch( + addArtboardFrame({ + name: copyName, + x: Math.round((Number(source.x) || 0) + dx), + y: Math.round((Number(source.y) || 0) + dy), + width: Math.max(40, Number(source.width) || 40), + height: Math.max(40, Number(source.height) || 40), + backgroundColor: source.backgroundColor, + clipContent: source.clipContent, + locked: false, + hidden: false, + activate: false, + }) + ); + const frames = listFrames(ctx.getDocument()); + const created = frames.find((frame) => !beforeIds.has(String(frame.id))) || null; + if (!created?.id) { + return { status: 'error', summary: `duplicate_frame failed for ${frameId}` }; + } + const copyChildren = truthy(args.includeChildren); + const copiedNodeIds: string[] = []; + if (copyChildren) { + const childIds = nodeIdsBoundToFrames(doc, [frameId]); + let nextDoc = ctx.getDocument() || doc; + for (const oldId of childIds) { + const raw = doc.deltaSetLike?.[oldId]; + if (!raw) continue; + const node = cloneSceneValue(raw); + const newId = nanoid(10); + node.id = newId; + node.x = (Number(node.x) || 0) + dx; + node.y = (Number(node.y) || 0) + dy; + node.attrs = { ...(node.attrs || {}), frameId: created.id }; + nextDoc = addNodeToDocument(nextDoc, newId, node); + copiedNodeIds.push(newId); + } + if (copiedNodeIds.length) ctx.dispatch(setDocumentFromCanvas(nextDoc)); + } + return { + status: 'success', + summary: `Duplicated frame ${frameId} -> ${created.id}${ + copiedNodeIds.length ? ` with ${copiedNodeIds.length} node(s)` : '' + }`, + artifacts: { sourceFrameId: frameId, frameId: created.id, nodeIds: copiedNodeIds }, + }; +} + +function execReorderFrames( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const frameIds = Array.isArray(args.frameIds) + ? args.frameIds.map((id) => String(id || '').trim()).filter(Boolean) + : []; + if (!frameIds.length) return { status: 'error', summary: 'frameIds required' }; + const actionRaw = String(args.action || '').trim().toLowerCase(); + const allowed = new Set(['front', 'back', 'forward', 'backward']); + if (!allowed.has(actionRaw)) { + return { status: 'error', summary: `Unknown reorder action: ${actionRaw || '(empty)'}` }; + } + const action = actionRaw as 'front' | 'back' | 'forward' | 'backward'; + + const existing = new Set(listFrames(doc).map((f) => String(f.id))); + const target = frameIds.filter((id) => existing.has(id)); + if (!target.length) return { status: 'error', summary: 'No matching frame ids' }; + + const next = cloneSceneValue(doc) as SceneDocument; + const order = Array.isArray(next.stackOrder) ? next.stackOrder.map(String) : []; + const frameKeys = order.filter((key) => key.startsWith('frame:')); + const nonFrameKeys = order.filter((key) => !key.startsWith('frame:')); + const selectedKeys = new Set(target.map((id) => `frame:${id}`)); + next.stackOrder = [...reorderKeysWithAction(frameKeys, selectedKeys, action), ...nonFrameKeys]; + pushHistory(); + ctx.dispatch(setDocumentFromCanvas(next)); + return { + status: 'success', + summary: `Reordered ${target.length} frame(s) (${action})`, + artifacts: { frameIds: target, action }, + }; +} + +function execFitFrameToContent( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const frameId = resolveFrameOpId(args, ctx); + if (!frameId) return { status: 'error', summary: 'frameId required' }; + const frame = frameById(doc, frameId); + if (!frame) return { status: 'error', summary: `frame not found: ${frameId}` }; + const nodeIds = nodeIdsInsideFrame(doc, frameId); + if (!nodeIds.length) { + return { + status: 'warning', + summary: `Frame ${frameId} has no child nodes`, + artifacts: { frameId, nodeIds: [] }, + }; + } + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + for (const nodeId of nodeIds) { + const node = doc.deltaSetLike?.[nodeId]; + if (!node) continue; + const lt = nodeLeftTop(doc, node); + const left = Number(lt.left) || 0; + const top = Number(lt.top) || 0; + const width = Math.max(1, Number(node.width) || 1); + const height = Math.max(1, Number(node.height) || 1); + minX = Math.min(minX, left); + minY = Math.min(minY, top); + maxX = Math.max(maxX, left + width); + maxY = Math.max(maxY, top + height); + } + if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) { + return { status: 'error', summary: `fit_frame_to_content failed for ${frameId}` }; + } + const padding = Math.max(0, Number(args.padding) || 24); + ctx.dispatch( + updateArtboardFrame({ + id: frameId, + patch: { + x: Math.round(minX - padding), + y: Math.round(minY - padding), + width: Math.max(40, Math.round(maxX - minX + padding * 2)), + height: Math.max(40, Math.round(maxY - minY + padding * 2)), + }, + }) + ); + return { + status: 'success', + summary: `Fitted frame ${frameId} to ${nodeIds.length} node(s)`, + artifacts: { frameId, nodeIds }, + }; +} + +function execSetFrameFlag( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + flag: 'locked' | 'hidden' | 'clipContent', + defaultOn: boolean +): AgentToolResult { + const ids = parseFrameOpIds(args, ctx); + if (!ids.length) return { status: 'error', summary: 'frameIds required' }; + const on = args[flag] == null ? defaultOn : truthy(args[flag]); + const existing = new Set(listFrames(doc).map((f) => String(f.id))); + const patches = ids + .filter((id) => existing.has(id)) + .map((id) => ({ id, patch: { [flag]: on } })); + if (!patches.length) return { status: 'error', summary: 'No matching frame ids' }; + ctx.dispatch(updateArtboardFrames({ patches })); + let verb = 'Updated'; + if (flag === 'locked') verb = on ? 'Locked' : 'Unlocked'; + else if (flag === 'hidden') verb = on ? 'Hid' : 'Showed'; + else verb = on ? 'Clipped' : 'Unclipped'; + return { + status: 'success', + summary: `${verb} ${patches.length} frame(s)`, + artifacts: { frameIds: patches.map((p) => p.id), [flag]: on }, + }; +} + +function execLockFrames( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + _pushHistory: () => void +): AgentToolResult { + return execSetFrameFlag(args, ctx, doc, 'locked', true); +} + +function execHideFrames( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + _pushHistory: () => void +): AgentToolResult { + return execSetFrameFlag(args, ctx, doc, 'hidden', true); +} + +function execClipFrames( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + _pushHistory: () => void +): AgentToolResult { + return execSetFrameFlag(args, ctx, doc, 'clipContent', true); +} + +function execHideNodes( + args: Record, + ctx: DesignToolContext, + doc: SceneDocument, + pushHistory: () => void +): AgentToolResult { + const ids = parseNodeIds(args); + if (!ids.length) return { status: 'error', summary: 'nodeIds required' }; + const hidden = args.hidden == null ? true : truthy(args.hidden); + const done: string[] = []; + for (const nodeId of ids) { + if (!doc.deltaSetLike?.[nodeId]) continue; + const result = execUpdateNode({ nodeId, hidden }, ctx, doc, pushHistory); + if (result.status !== 'error') done.push(nodeId); + } + if (!done.length) { + return { status: 'error', summary: 'No matching scene nodes to hide/show' }; + } + return { + status: 'success', + summary: `${hidden ? 'Hid' : 'Showed'} ${done.length} node(s)`, + artifacts: { nodeIds: done, hidden }, + }; +} + function execUpdateFrame( args: Record, ctx: DesignToolContext, @@ -3373,6 +4249,8 @@ function execUpdateFrame( patch.backgroundColor = String(args.backgroundColor || 'transparent'); } if (args.locked != null) patch.locked = truthy(args.locked); + if (args.hidden != null) patch.hidden = truthy(args.hidden); + if (args.clipContent != null) patch.clipContent = truthy(args.clipContent); ctx.dispatch(updateArtboardFrame({ id, patch })); return { status: 'success', summary: `Updated frame ${id}`, artifacts: { frameId: id } }; @@ -3580,6 +4458,10 @@ export function executeDesignTool( return execListCapabilities(args, ctx, doc, pushHistory); case 'set_viewport': return execSetViewport(args, ctx, doc, pushHistory); + case 'set_active_tool': + return execSetActiveTool(args, ctx, doc, pushHistory); + case 'set_grid': + return execSetGrid(args, ctx, doc, pushHistory); case 'set_canvas_background': return execSetCanvasBackground(args, ctx, doc, pushHistory); case 'set_agent_mode': @@ -3598,6 +4480,16 @@ export function executeDesignTool( return execCreateSvg(args, ctx, doc, pushHistory); case 'create_shape': return execCreateShape(args, ctx, doc, pushHistory); + case 'create_path': + return execCreatePath(args, ctx, doc, pushHistory); + case 'append_path_points': + return execAppendPathPoints(args, ctx, doc, pushHistory); + case 'simplify_path': + return execSimplifyPath(args, ctx, doc, pushHistory); + case 'smooth_path': + return execSmoothPath(args, ctx, doc, pushHistory); + case 'close_path': + return execClosePath(args, ctx, doc, pushHistory); case 'create_image': return execCreateImage(args, ctx, doc, pushHistory); case 'create_text': @@ -3620,10 +4512,30 @@ export function executeDesignTool( return execDuplicateNodes(args, ctx, doc, pushHistory); case 'flip_nodes': return execFlipNodes(args, ctx, doc, pushHistory); + case 'rotate_nodes': + return execRotateNodes(args, ctx, doc, pushHistory); + case 'bind_nodes_to_frame': + return execBindNodesToFrame(args, ctx, doc, pushHistory); + case 'unbind_nodes': + return execUnbindNodes(args, ctx, doc, pushHistory); case 'delete_nodes': return execDeleteNodes(args, ctx, doc, pushHistory); case 'delete_frame': return execDeleteFrame(args, ctx, doc, pushHistory); + case 'duplicate_frame': + return execDuplicateFrame(args, ctx, doc, pushHistory); + case 'reorder_frames': + return execReorderFrames(args, ctx, doc, pushHistory); + case 'fit_frame_to_content': + return execFitFrameToContent(args, ctx, doc, pushHistory); + case 'lock_frames': + return execLockFrames(args, ctx, doc, pushHistory); + case 'hide_frames': + return execHideFrames(args, ctx, doc, pushHistory); + case 'clip_frames': + return execClipFrames(args, ctx, doc, pushHistory); + case 'hide_nodes': + return execHideNodes(args, ctx, doc, pushHistory); case 'update_frame': return execUpdateFrame(args, ctx, doc, pushHistory); case 'create_frame': @@ -3632,6 +4544,10 @@ export function executeDesignTool( return execImageProcess(args, ctx, doc, pushHistory); case 'export_canvas': return execExportCanvas(args, ctx, doc, pushHistory); + case 'edit_path_points': + return execEditPathPoints(args, ctx, doc, pushHistory); + case 'apply_brush_preset': + return execApplyBrushPreset(args, ctx, doc, pushHistory); default: return resolveUnknownToolError(name); } diff --git a/apps/web/src/components/editor/panels/agent/messages/ChatTurnList.tsx b/apps/web/src/components/editor/panels/agent/messages/ChatTurnList.tsx index ba0a3ed5..f0cc110b 100644 --- a/apps/web/src/components/editor/panels/agent/messages/ChatTurnList.tsx +++ b/apps/web/src/components/editor/panels/agent/messages/ChatTurnList.tsx @@ -95,7 +95,7 @@ export type ChatUiMessage = { proposedOps?: Array<{ name?: string; args?: Record; op_id?: string }>; /** Server-bound Ask proposal id (design_task.meta.ask_proposal). */ proposalId?: string; - /** Ask mode: label of the apply option (compat). */ + /** Ask mode: label of the apply option. */ applyChoice?: string; /** Ask interaction UI — mode + options; text = freeform reply. */ choiceUi?: { @@ -1082,7 +1082,7 @@ export type ExploreItem = { tone?: ExploreItemTone; }; -/** Infer warn/error from copy when emitters did not set tone (legacy rows). */ +/** Infer warn/error from copy when emitters did not set tone. */ function inferExploreItemTone(text: string): ExploreItemTone { const s = String(text || '').toLowerCase(); if (!s) return 'ok'; diff --git a/apps/web/src/components/editor/panels/agent/models/AgentModelsPanel.tsx b/apps/web/src/components/editor/panels/agent/models/AgentModelsPanel.tsx index 166300a3..659860a5 100644 --- a/apps/web/src/components/editor/panels/agent/models/AgentModelsPanel.tsx +++ b/apps/web/src/components/editor/panels/agent/models/AgentModelsPanel.tsx @@ -1,5 +1,5 @@ /** - * Account Agent tab: Auto routing prefs + custom OpenAI-compatible providers (Pro). + * Account Agent tab: Auto routing prefs + custom OpenAI-style providers (Pro). */ import { useEffect, useRef, useState, type ReactNode, memo } from 'react'; @@ -367,9 +367,7 @@ function AgentModelsPanel({ if (!modelsQuery.isFetched) return; const res = modelsQuery.data as ChatModelsResponse | undefined; if (res) { - const plat = res.byokPlatforms?.length - ? res.byokPlatforms - : (res.byokPresets as ByokPlatform[] | undefined) ?? []; + const plat = res.byokPlatforms ?? []; setPlatforms( plat.map((p) => ({ ...p, diff --git a/apps/web/src/components/editor/panels/agent/runDesignAgent.ts b/apps/web/src/components/editor/panels/agent/runDesignAgent.ts index 930fbe82..424446d8 100644 --- a/apps/web/src/components/editor/panels/agent/runDesignAgent.ts +++ b/apps/web/src/components/editor/panels/agent/runDesignAgent.ts @@ -219,19 +219,21 @@ export function acknowledgeAppliedDesignCommand( const normalizedTaskId = String(taskId || '').trim(); const normalizedSequence = Number(sequence || 0); if (!normalizedTaskId || normalizedSequence <= 0) return; - void acknowledgeDesignCanvasCommands(normalizedTaskId, normalizedSequence, signal) - .catch((error) => console.warn('[design command ack failed]', { - commandTaskId: normalizedTaskId, - commandSeq: normalizedSequence, - error, - })); + async function ack() { + try { + await acknowledgeDesignCanvasCommands(normalizedTaskId, normalizedSequence, signal); + } catch (error) { + console.warn('[design command ack failed]', { commandTaskId: normalizedTaskId, commandSeq: normalizedSequence, error }); + } + } + ack(); } function overlayArgId(args: Record | undefined): string | null { if (!args) return null; - const scalar = [args.id, args.nodeId, args.node_id].map((value) => String(value || '').trim()).find(Boolean); + const scalar = String(args.nodeId || '').trim(); if (scalar) return scalar; - const ids = args.ids ?? args.nodeIds; + const ids = args.nodeIds; return Array.isArray(ids) && ids.length ? String(ids[ids.length - 1] || '').trim() || null : null; } @@ -280,10 +282,8 @@ function uniqueReceiptNodeIds(values: unknown[]): string[] { } function expectedNodeIds(args: Record): string[] { - const values: unknown[] = [args.id, args.nodeId, args.node_id]; - for (const candidate of [args.ids, args.nodeIds, args.node_ids]) { - if (Array.isArray(candidate)) values.push(...candidate); - } + const values: unknown[] = [args.nodeId]; + if (Array.isArray(args.nodeIds)) values.push(...args.nodeIds); return uniqueReceiptNodeIds(values); } @@ -390,7 +390,7 @@ export async function applyAgentToolOps(opts: { // Host shimmer / @ pin / live plate already bound — never spatialize onto // ambient boards (model world x/y or guessed frameId often hits the old plate). if (fallback) return fallback; - const explicit = String(args.frameId || args.id || '').trim(); + const explicit = String(args.frameId || '').trim(); if (explicit) { const frames = Array.isArray(doc?.frames) ? doc.frames : []; if (frames.some((f) => f && String(f.id) === explicit)) return explicit; @@ -438,12 +438,6 @@ export async function applyAgentToolOps(opts: { const allowedDeletes = allowed.filter((o) => ['delete_frame', 'delete_nodes'].includes(String(o?.name || '').trim()) ); - console.info('[tool_ops delete filter]', { - raw: rawDeletes.length, - allowed: allowedDeletes.length, - dropped: rawDeletes.length - allowedDeletes.length, - rawOps: rawDeletes, - }); } for (let i = 0; i < allowed.length; i++) { if (signal?.aborted) break; @@ -480,20 +474,6 @@ export async function applyAgentToolOps(opts: { ); if (picked) toolCtx.targetFrameId = picked; } - if (name === 'create_shape' && (args.path != null || String(args.type || args.shapeType || '') === 'path')) { - console.info('[tool_ops raw create_shape]', { - i, - name, - type: args.type || args.shapeType, - x: args.x, - y: args.y, - width: args.width, - height: args.height, - fill: args.fill, - stroke: args.stroke, - path: args.path != null ? String(args.path) : '', - }); - } const res = await executeDesignToolAsync(name, JSON.stringify(args), toolCtx); if (name === 'create_frame' && res.status !== 'error') { const fid = String(res.artifacts?.frameId || '').trim(); @@ -502,24 +482,6 @@ export async function applyAgentToolOps(opts: { toolCtx.targetFrameId = fid; } } - if (name === 'delete_frame' || name === 'delete_nodes') { - const docAfter = getDocument(); - const framesAfter = Array.isArray(docAfter?.frames) - ? docAfter.frames.map((f: { id?: string; name?: string }) => ({ - id: f?.id, - name: f?.name, - })) - : []; - console.info('[tool_ops delete]', { - i, - name, - args, - status: res.status, - summary: res.summary, - framesAfter, - artifacts: res.artifacts, - }); - } if (res.status === 'error') { console.warn('[tool_ops error]', { i, name, args, summary: res.summary }); opResults.push({ @@ -543,7 +505,7 @@ export async function applyAgentToolOps(opts: { : []; if (outlined.length) nodeIds.push(...outlined); else { - const nid = String(args.nodeId || args.id || ''); + const nid = String(args.nodeId || ''); if (nid) nodeIds.push(nid); } } else if (name === 'delete_nodes') { @@ -558,9 +520,6 @@ export async function applyAgentToolOps(opts: { } } } - if (deleted > 0) { - console.info('[tool_ops delete done]', { deleted, created, updated }); - } return { created, updated, @@ -1710,14 +1669,7 @@ async function waitSceneInventorySettled( ): Promise { const timeoutMs = Math.max(80, opts?.timeoutMs ?? 480); const needStable = Math.max(1, opts?.stableFrames ?? 2); - const frame = () => - new Promise((resolve) => { - if (typeof requestAnimationFrame === 'function') { - requestAnimationFrame(() => resolve()); - } else { - setTimeout(resolve, 16); - } - }); + const frame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())); const t0 = Date.now(); let prev = sceneInventoryFingerprint(getDocument()); let stable = 0; @@ -2331,13 +2283,6 @@ export async function runDesignAgent(params: RunDesignAgentParams): Promise ['delete_frame', 'delete_nodes'].includes(String(o?.name || '').trim()) ); - if (deleteish.length) { - console.info('[sse tool_ops delete]', deleteish); - } const txId = String(ev.transaction_id || aiQueue.transactionId || '').trim(); if (txId) aiQueueBindTransaction(aiQueue, txId); if (!aiQueueEnqueue(aiQueue, ops)) return; @@ -3202,37 +3135,19 @@ export async function runDesignAgent(params: RunDesignAgentParams): Promise ({ id: f.id, is_empty: f.is_empty })), - emptyRects: spatial.empty_rects.length, - opFailed: opResults.filter((r) => !r.ok).length, - hasPreview: Boolean(previewImage), - transactionId: feedbackTxId || null, - transactionStatus: feedbackTxId ? txStatus : null, - }); - const feedback = { + const feedback: Parameters[1] = { scene_nodes: nodes as Array>, - ...(frames.length - ? { scene_frames: frames as Array> } - : {}), spatial_summary: spatial as unknown as Record, - ...(opResults.length ? { op_results: opResults } : {}), - ...(previewImage ? { preview_image: previewImage } : {}), round, - ...(feedbackTxId - ? { - transaction_id: feedbackTxId, - transaction_status: txStatus, - ...(aiQueue.baseRevision - ? { base_revision: aiQueue.baseRevision } - : {}), - } - : {}), }; + if (frames.length) feedback.scene_frames = frames as Array>; + if (opResults.length) feedback.op_results = opResults; + if (previewImage) feedback.preview_image = previewImage; + if (feedbackTxId) { + feedback.transaction_id = feedbackTxId; + feedback.transaction_status = txStatus; + if (aiQueue.baseRevision) feedback.base_revision = aiQueue.baseRevision; + } const retryDelaysMs = [0, 750, 2_000]; let feedbackSent = false; for (let attempt = 0; attempt < retryDelaysMs.length; attempt += 1) { diff --git a/apps/web/src/components/editor/panels/agent/toolOpsContract.ts b/apps/web/src/components/editor/panels/agent/toolOpsContract.ts index 9b37b224..2f793067 100644 --- a/apps/web/src/components/editor/panels/agent/toolOpsContract.ts +++ b/apps/web/src/components/editor/panels/agent/toolOpsContract.ts @@ -72,14 +72,14 @@ function tryParseJson(text: string): unknown | null { function coerceRawOp(raw: unknown): AgentToolOp | null { if (!raw || typeof raw !== 'object') return null; const row = raw as Record; - const name = String(row.name || row.tool || row.type || row.op || '').trim(); + const name = String(row.name || '').trim(); if (!name) return null; - const argsRaw = row.args ?? row.parameters ?? row.arguments; + const argsRaw = row.args; const args = argsRaw && typeof argsRaw === 'object' && !Array.isArray(argsRaw) ? { ...(argsRaw as Record) } : {}; - const op_id = String(row.op_id || row.opId || args.op_id || '').trim() || undefined; + const op_id = String(row.op_id || args.op_id || '').trim() || undefined; if (op_id) args.op_id = op_id; return { name, args, ...(op_id ? { op_id } : {}) }; } @@ -91,12 +91,11 @@ function coerceOpsPayload(data: unknown): AgentToolOp[] { } if (typeof data !== 'object') return []; const obj = data as Record; - const list = obj.ops ?? obj.tools ?? obj.actions ?? obj.tool_ops; + const list = obj.tool_ops; if (Array.isArray(list)) { return list.map(coerceRawOp).filter((x): x is AgentToolOp => Boolean(x)); } - const single = coerceRawOp(obj); - return single ? [single] : []; + return []; } /** Pull canvas tool_ops from coding-CLI / LLM prose (fenced JSON or embedded object). */ @@ -112,7 +111,7 @@ export function extractToolOpsFromText(text: string): AgentToolOp[] { if (ops.length) return ops; } - const marker = raw.search(/\{\s*"(?:ops|tools|actions|tool_ops)"\s*:/); + const marker = raw.search(/\{\s*"tool_ops"\s*:/); if (marker >= 0) { const slice = raw.slice(marker); const end = slice.lastIndexOf('}'); diff --git a/apps/web/src/components/editor/useProjectCloudSync.ts b/apps/web/src/components/editor/useProjectCloudSync.ts index 13dd0470..4c198948 100644 --- a/apps/web/src/components/editor/useProjectCloudSync.ts +++ b/apps/web/src/components/editor/useProjectCloudSync.ts @@ -454,12 +454,6 @@ export async function syncOwnedDocumentToCloud(opts: { return { status: 'ok', ack: { revision: baseRevision } }; } - if (import.meta.env.DEV) { - console.info('[project-sync] full PUT', { - id, - reason: fullPutReason(baseDoc, baseRevision, delta?.preferFull), - }); - } return pushProjectToCloud({ id, name, document, baseRevision }); } diff --git a/apps/web/src/components/layout/RedeemDialog.tsx b/apps/web/src/components/layout/RedeemDialog.tsx index e4f3fb68..9468e7ae 100644 --- a/apps/web/src/components/layout/RedeemDialog.tsx +++ b/apps/web/src/components/layout/RedeemDialog.tsx @@ -136,7 +136,7 @@ type DialogProps = { onRedeemed?: () => void; }; -/** Standalone redeem dialog (legacy callers). Prefer AccountSettingsDialog. */ +/** Standalone redeem dialog. Prefer AccountSettingsDialog. */ function RedeemDialog({ open, onClose, onRedeemed }: DialogProps) { const { t } = useTranslation(); if (isDesktopLocal()) return null; diff --git a/apps/web/src/components/layout/WalletLedgerPanel.tsx b/apps/web/src/components/layout/WalletLedgerPanel.tsx index 7a7f0ce9..54e66364 100644 --- a/apps/web/src/components/layout/WalletLedgerPanel.tsx +++ b/apps/web/src/components/layout/WalletLedgerPanel.tsx @@ -188,7 +188,7 @@ function WalletLedgerPanel({ planExpiresAt: walletExpires, }); - /** Deep-link ?redeem=1 still opens redeem (legacy) 鈥?skip when embedded / local desktop. */ + /** Deep-link ?redeem=1 still opens redeem; skip when embedded / local desktop. */ useEffect(() => { if (embedded || desktopLocal) return; const flag = (searchParams.get('redeem') || '').trim(); diff --git a/apps/web/src/components/rcb/__tests__/sceneNodeZod.test.ts b/apps/web/src/components/rcb/__tests__/sceneNodeZod.test.ts index 11669246..5e8c0809 100644 --- a/apps/web/src/components/rcb/__tests__/sceneNodeZod.test.ts +++ b/apps/web/src/components/rcb/__tests__/sceneNodeZod.test.ts @@ -17,7 +17,7 @@ describe('SceneDocument Zod boundary', () => { expect(result.valid).toBe(true); }); - it('accepts video / lottie keys (not only legacy text|shape|image)', () => { + it('accepts video / lottie keys (not only text|shape|image)', () => { const result = validateSceneDocument({ width: 800, height: 600, diff --git a/apps/web/src/components/rcb/canvas/RcbCanvas.tsx b/apps/web/src/components/rcb/canvas/RcbCanvas.tsx index e71deb7d..21fba272 100644 --- a/apps/web/src/components/rcb/canvas/RcbCanvas.tsx +++ b/apps/web/src/components/rcb/canvas/RcbCanvas.tsx @@ -17,10 +17,6 @@ import { RcbOverlayRootContext, RcbViewportElContext, } from '../camera/context'; -import { - installDprDebugHelpers, - logDprCameraState, -} from '../core/dprDebug'; import { readDevicePixelRatio, subscribeDevicePixelRatio } from '../core/dpr'; import { rcbCameraCssZoom, @@ -231,53 +227,6 @@ function RcbCanvas({ // Browser zoom / HiDPI — keep DPR in sync (camera pan snaps to this). useEffect(() => subscribeDevicePixelRatio(setDevicePixelRatio), []); - // Opt-in camera logs: window.__RCB_DPR_DEBUG__ = true - useEffect(() => { - if (typeof window === 'undefined' || window.__RCB_DPR_DEBUG__ !== true) return; - logDprCameraState({ - reason: 'camera-or-dpr', - dpr: devicePixelRatio, - camera, - camCss: { - ...rcbCameraScreenOffset(camera, devicePixelRatio), - z: rcbCameraCssZoom(camera), - }, - }); - }, [devicePixelRatio, camera]); - - // Console helpers: window.__rcbDumpDpr() / __rcbDumpGrid() - useEffect(() => { - installDprDebugHelpers(() => { - const stage = stageRef.current; - const boxes: Array<{ - id: string; - left: number; - top: number; - width: number; - height: number; - }> = []; - if (stage) { - const nodes = stage.querySelectorAll('[data-scene-node-id]'); - nodes.forEach((el) => { - const id = el.getAttribute('data-scene-node-id') || ''; - if (!id) return; - try { - const bb = (el as SVGGraphicsElement).getBBox(); - boxes.push({ - id, - left: bb.x, - top: bb.y, - width: bb.width, - height: bb.height, - }); - } catch { - /* ignore detached */ - } - }); - } - return { dpr: devicePixelRatio, camera: cameraRef.current, boxes }; - }); - }, [devicePixelRatio, stageRef]); emptyDragPansRef.current = emptyDragPans; shouldBlockEmptyPanRef.current = shouldBlockEmptyPan; panBlockSelectorRef.current = panBlockSelector; diff --git a/apps/web/src/components/rcb/core/__tests__/textPlaceFontSize.test.ts b/apps/web/src/components/rcb/core/__tests__/textPlaceFontSize.test.ts index 688d7756..731fa4a6 100644 --- a/apps/web/src/components/rcb/core/__tests__/textPlaceFontSize.test.ts +++ b/apps/web/src/components/rcb/core/__tests__/textPlaceFontSize.test.ts @@ -14,7 +14,7 @@ describe('rcbDefaultPlaceFontSize (T-tool at zoom)', () => { it('at 4000% zoom is ~1 scene px (not document-14 filling the view)', () => { const fs = rcbDefaultPlaceFontSize(40, 14); // eslint-disable-next-line no-console - console.log('[test:text-font@4000%]', { fs, legacy: 14 }); + console.log('[test:text-font@4000%]', { fs, documentPx: 14 }); expect(fs).toBe(1); expect(fs).toBeLessThan(14); }); @@ -48,10 +48,10 @@ describe('rcbDefaultPlaceFontSize (T-tool at zoom)', () => { it('empty caret chrome height must not use a document-20px floor', () => { const fs = rcbDefaultPlaceFontSize(20, 14); // 0.7 → rounds to 0.5? 14/20=0.7 → 0.5? round*2/2 const emptyH = Math.ceil(fs * 1.4); - const legacyEmptyH = Math.max(fs * 1.4, 20); + const oldEmptyH = Math.max(fs * 1.4, 20); // eslint-disable-next-line no-console - console.log('[test:text-empty-h]', { fs, emptyH, legacyEmptyH }); + console.log('[test:text-empty-h]', { fs, emptyH, oldEmptyH }); expect(emptyH).toBeLessThan(20); - expect(legacyEmptyH).toBe(20); + expect(oldEmptyH).toBe(20); }); }); diff --git a/apps/web/src/components/rcb/core/dprDebug.ts b/apps/web/src/components/rcb/core/dprDebug.ts deleted file mode 100644 index 54eaa12c..00000000 --- a/apps/web/src/components/rcb/core/dprDebug.ts +++ /dev/null @@ -1,372 +0,0 @@ -/** - * Temporary DPR / subpixel diagnostics. - * Enable: window.__RCB_DPR_DEBUG__ = true - * Dump now: window.__rcbDumpDpr?.() - * - * Align guides: window.__RCB_ALIGN_DEBUG__ = true - * Last align dump: window.__rcbLastAlignDump - * Dump now: window.__rcbDumpAlign?.() - * - * Default OFF — enable explicitly when debugging browser-zoom seams. - */ - -import { nearestDprMultiple } from './dpr'; -import { rcbSceneToScreen } from './math'; -import type { RcbCamera } from './types'; - -declare global { - interface Window { - __RCB_DPR_DEBUG__?: boolean; - __RCB_ALIGN_DEBUG__?: boolean; - __rcbDumpDpr?: () => void; - __rcbDumpAlign?: () => void; - __rcbDumpGrid?: () => Record; - __rcbLastDprDump?: Record; - __rcbLastAlignDump?: Record; - __rcbLastGridDump?: Record; - } -} - -const TAG = '[rcb:dpr]'; - -function debugEnabled() { - if (typeof window === 'undefined') return false; - // Opt-in only — default OFF (was spamming + noise during 90% zoom tests). - return window.__RCB_DPR_DEBUG__ === true; -} - -function frac(n: number) { - return Math.abs(n - Math.round(n)); -} - -function classify(devicePx: number) { - const f = frac(devicePx); - if (f < 0.02 || f > 0.98) return 'integer'; - if (f > 0.45 && f < 0.55) return 'half'; - return 'frac'; -} - -/** Scene → CSS px under camera (uses snapped camera pan). */ -export function sceneToCss(camera: RcbCamera, sceneX: number, sceneY: number, dpr?: number) { - return rcbSceneToScreen(camera, sceneX, sceneY, dpr); -} - -export type DprEdgeSample = { - id: string; - scene: { left: number; top: number; right: number; bottom: number }; - css: { left: number; top: number; right: number; bottom: number }; - device: { left: number; top: number; right: number; bottom: number }; - edgeClass: { - left: string; - top: string; - right: string; - bottom: string; - }; -}; - -export function sampleBoxEdges( - id: string, - box: { left: number; top: number; width: number; height: number }, - camera: RcbCamera, - dpr: number -): DprEdgeSample { - const right = box.left + box.width; - const bottom = box.top + box.height; - const tl = sceneToCss(camera, box.left, box.top, dpr); - const br = sceneToCss(camera, right, bottom, dpr); - const device = { - left: tl.x * dpr, - top: tl.y * dpr, - right: br.x * dpr, - bottom: br.y * dpr, - }; - return { - id, - scene: { left: box.left, top: box.top, right, bottom }, - css: { left: tl.x, top: tl.y, right: br.x, bottom: br.y }, - device, - edgeClass: { - left: classify(device.left), - top: classify(device.top), - right: classify(device.right), - bottom: classify(device.bottom), - }, - }; -} - -/** Gap between A's right edge and B's left edge in device pixels. */ -export function adjacentSeam( - a: DprEdgeSample, - b: DprEdgeSample -): { cssGap: number; deviceGap: number; aRightClass: string; bLeftClass: string } | null { - // Prefer horizontal neighbors: A left of B - const cssGap = b.css.left - a.css.right; - if (Math.abs(cssGap) > 40) return null; - return { - cssGap, - deviceGap: b.device.left - a.device.right, - aRightClass: a.edgeClass.right, - bLeftClass: b.edgeClass.left, - }; -} - -export function logDprCameraState(opts: { - reason: string; - dpr: number; - camera: RcbCamera; - camCss?: { x: number; y: number; z: number }; -}) { - if (!debugEnabled()) return; - const { reason, dpr, camera, camCss } = opts; - const multiple = nearestDprMultiple(dpr); - const payload = { - reason, - dpr, - dprMultiple: multiple, - dprTimesMultiple: dpr * multiple, - dprIsFractional: Math.abs(dpr - Math.round(dpr)) > 0.02, - camera: { ...camera }, - camCssWritten: camCss ?? { - x: camera.x, - y: camera.y, - z: camera.zoom, - }, - // After CSS scale(z) translate(x,y), a scene unit becomes zoom CSS px → zoom*dpr device px. - sceneUnitDevicePx: camera.zoom * dpr, - visualViewportScale: - typeof window !== 'undefined' && window.visualViewport - ? window.visualViewport.scale - : undefined, - }; - window.__rcbLastDprDump = payload; - console.log(TAG, reason, payload); -} - -export function logEdgeSamples( - reason: string, - samples: DprEdgeSample[], - dpr: number, - camera: RcbCamera -) { - if (!debugEnabled() || !samples.length) return; - console.groupCollapsed(`${TAG} edges · ${reason} · n=${samples.length}`); - console.table( - samples.map((s) => ({ - id: s.id.slice(0, 12), - sceneL: s.scene.left, - sceneR: s.scene.right, - cssL: +s.css.left.toFixed(3), - cssR: +s.css.right.toFixed(3), - devL: +s.device.left.toFixed(3), - devR: +s.device.right.toFixed(3), - classL: s.edgeClass.left, - classR: s.edgeClass.right, - classT: s.edgeClass.top, - classB: s.edgeClass.bottom, - })) - ); - - // Check pairwise horizontal seams (likely adjacent rects). - const seams: Array> = []; - for (let i = 0; i < samples.length; i++) { - for (let j = 0; j < samples.length; j++) { - if (i === j) continue; - const seam = adjacentSeam(samples[i], samples[j]); - if (!seam) continue; - if (Math.abs(seam.cssGap) > 8) continue; - seams.push({ - a: samples[i].id.slice(0, 12), - b: samples[j].id.slice(0, 12), - cssGap: +seam.cssGap.toFixed(4), - deviceGap: +seam.deviceGap.toFixed(4), - aRight: seam.aRightClass, - bLeft: seam.bLeftClass, - suspect: - Math.abs(seam.deviceGap) > 0.15 || - seam.aRightClass !== 'integer' || - seam.bLeftClass !== 'integer', - }); - } - } - if (seams.length) { - console.log(TAG, 'adjacent seams (cssGap≈0 = touching in scene*zoom)', { - dpr, - zoom: camera.zoom, - }); - console.table(seams); - } else { - console.log(TAG, 'no near-horizontal adjacent pairs found in sample'); - } - console.groupEnd(); -} - -export function installDprDebugHelpers(getState: () => { - dpr: number; - camera: RcbCamera; - boxes?: Array<{ id: string; left: number; top: number; width: number; height: number }>; -}) { - if (typeof window === 'undefined') return; - window.__rcbDumpDpr = () => { - const { dpr, camera, boxes = [] } = getState(); - logDprCameraState({ reason: 'manual-dump', dpr, camera }); - const samples = boxes.map((b) => - sampleBoxEdges(b.id, b, camera, dpr) - ); - logEdgeSamples('manual-dump', samples, dpr, camera); - }; - window.__rcbDumpAlign = () => { - const last = window.__rcbLastAlignDump; - if (!last) { - console.warn(TAG, 'no align dump yet — enable __RCB_ALIGN_DEBUG__ and drag to snap'); - return; - } - console.log(TAG, 'align dump (copy JSON)', JSON.stringify(last, null, 2)); - }; - window.__rcbDumpGrid = () => dumpGridVsHosts(getState); -} - -const GRID_TAG = '[rcb:grid]'; - -function parsePx(v: string | null | undefined): number | null { - if (v == null || v === '') return null; - const n = Number.parseFloat(String(v)); - return Number.isFinite(n) ? n : null; -} - -function onGrid(value: number, g: number) { - if (!(g > 0)) return true; - const q = Math.round(value / g) * g; - return Math.abs(value - q) < 1e-6; -} - -/** Measure infinite-canvas grid (Canvas underlay) vs shape hosts — always prints JSON. */ -export function dumpGridVsHosts(getState: () => { - dpr: number; - camera: RcbCamera; - boxes?: Array<{ id: string; left: number; top: number; width: number; height: number }>; -}): Record { - const { dpr, camera, boxes = [] } = getState(); - const sceneRoot = document.querySelector('[data-rcb-scene-root="1"]') as SVGSVGElement | null; - const cameraRoot = sceneRoot?.querySelector('[data-rcb-scene-camera="1"]') as SVGGElement | null; - const grid = - (document.querySelector('[data-rcb-scene-canvas][data-rcb-pixel-grid="1"]') as - | HTMLCanvasElement - | null) || - (document.querySelector('[data-rcb-pixel-grid="1"]') as SVGSVGElement | HTMLCanvasElement | null); - const g = Number(grid?.getAttribute('data-rcb-grid-size') || 1) || 1; - const gridLeft = parsePx(grid?.getAttribute('data-rcb-grid-left')); - const gridTop = parsePx(grid?.getAttribute('data-rcb-grid-top')); - const gridStyleLeft = - grid instanceof HTMLCanvasElement ? null : parsePx((grid as SVGSVGElement | null)?.style?.left); - const gridStyleTop = - grid instanceof HTMLCanvasElement ? null : parsePx((grid as SVGSVGElement | null)?.style?.top); - const gridRect = grid?.getBoundingClientRect?.() ?? null; - const worldTf = cameraRoot?.getAttribute('transform') || ''; - - const hosts = Array.from( - document.querySelectorAll('[data-rcb-infinite="1"]:not([data-rcb-pixel-grid]):not([data-rcb-scene-canvas])') - ); - const hostRows = hosts.slice(0, 24).map((node, i) => { - const el = node as SVGSVGElement; - const left = parsePx(el.style.left) ?? parsePx(el.getAttribute('x')); - const top = parsePx(el.style.top) ?? parsePx(el.getAttribute('y')); - const vb = (el.getAttribute('viewBox') || '').trim(); - const rect = el.getBoundingClientRect(); - const sceneLeft = left; - const sceneTop = top; - return { - i, - tag: el.tagName, - sceneLeft, - sceneTop, - viewBox: vb, - onGridX: sceneLeft == null ? null : onGrid(sceneLeft, g), - onGridY: sceneTop == null ? null : onGrid(sceneTop, g), - fracX: sceneLeft == null ? null : sceneLeft - Math.round(sceneLeft / g) * g, - fracY: sceneTop == null ? null : sceneTop - Math.round(sceneTop / g) * g, - client: { - left: +rect.left.toFixed(3), - top: +rect.top.toFixed(3), - width: +rect.width.toFixed(3), - height: +rect.height.toFixed(3), - }, - }; - }); - - const boxRows = boxes.map((b) => { - const sample = sampleBoxEdges(b.id, b, camera, dpr); - return { - id: b.id, - scene: sample.scene, - onGrid: { - left: onGrid(b.left, g), - top: onGrid(b.top, g), - right: onGrid(b.left + b.width, g), - bottom: onGrid(b.top + b.height, g), - }, - frac: { - left: b.left - Math.round(b.left / g) * g, - top: b.top - Math.round(b.top / g) * g, - right: b.left + b.width - Math.round((b.left + b.width) / g) * g, - bottom: b.top + b.height - Math.round((b.top + b.height) / g) * g, - }, - css: sample.css, - device: sample.device, - edgeClass: sample.edgeClass, - }; - }); - - const gridSharesStage = Boolean(grid && sceneRoot && grid.parentElement === sceneRoot.parentElement); - - const payload: Record = { - dpr, - visualViewportScale: window.visualViewport?.scale ?? null, - camera: { ...camera }, - grid: { - present: Boolean(grid), - sharesStageWithScene: gridSharesStage, - gridSize: g, - attrOrigin: { left: gridLeft, top: gridTop }, - styleOrigin: { left: gridStyleLeft, top: gridStyleTop }, - viewBox: grid?.getAttribute('viewBox') || null, - pathLen: grid?.querySelector('path')?.getAttribute('d')?.length ?? 0, - usesPattern: Boolean(grid?.querySelector('pattern')), - client: gridRect - ? { - left: +gridRect.left.toFixed(3), - top: +gridRect.top.toFixed(3), - width: +gridRect.width.toFixed(3), - height: +gridRect.height.toFixed(3), - } - : null, - }, - worldTransform: worldTf, - stateBoxes: boxRows, - domHosts: hostRows, - }; - - window.__rcbLastGridDump = payload; - console.log(GRID_TAG, 'dump', payload); - console.log(GRID_TAG, 'json', JSON.stringify(payload)); - return payload; -} - -const ALIGN_TAG = '[rcb:align]'; - -function alignDebugEnabled() { - if (typeof window === 'undefined') return false; - return window.__RCB_ALIGN_DEBUG__ === true || window.__RCB_DPR_DEBUG__ === true; -} - -/** Opt-in JSON dump while orange align guides are active (browser-zoom seams). */ -export function logAlignGuideDump(payload: Record) { - if (!alignDebugEnabled()) return; - window.__rcbLastAlignDump = payload; - console.log(ALIGN_TAG, 'dump', payload); - // One-line copy-friendly JSON for pasting back into chat. - try { - console.log(ALIGN_TAG, 'json', JSON.stringify(payload)); - } catch { - /* ignore */ - } -} diff --git a/apps/web/src/components/rcb/core/geometry/__tests__/baseline.test.ts b/apps/web/src/components/rcb/core/geometry/__tests__/baseline.test.ts index f97f68f0..e0302965 100644 --- a/apps/web/src/components/rcb/core/geometry/__tests__/baseline.test.ts +++ b/apps/web/src/components/rcb/core/geometry/__tests__/baseline.test.ts @@ -85,7 +85,7 @@ describe('advanceEllipseArcAlong', () => { expect(d).toContain('A 20 20 0 0 0'); }); - it('preserves a legacy reverse arc direction without selecting a new direction mid-drag', async () => { + it('preserves reverse arc direction without selecting a new direction mid-drag', async () => { const { advanceEllipseArcAlong, ellipseArcPercentFromAlongRad } = await import( '@/components/rcb/scene/document/sceneShapes' ); diff --git a/apps/web/src/components/rcb/frames/__tests__/frameDrawGrid.test.ts b/apps/web/src/components/rcb/frames/__tests__/frameDrawGrid.test.ts index 6d3e96b4..3d788a9e 100644 --- a/apps/web/src/components/rcb/frames/__tests__/frameDrawGrid.test.ts +++ b/apps/web/src/components/rcb/frames/__tests__/frameDrawGrid.test.ts @@ -57,7 +57,7 @@ describe('frame draw (artboard) vs rect contract', () => { expect(Number.isInteger(box.top)).toBe(true); }); - it('high-zoom soft drag 5×4 still commits (legacy 24 min rejected)', () => { + it('high-zoom soft drag 5×4 still commits (old 24 min rejected)', () => { const box = resolveFrameDrawBox( { left: 100.2, top: 50.7, width: 4.6, height: 3.4 }, true, diff --git a/apps/web/src/components/rcb/scene/__tests__/sceneText.test.ts b/apps/web/src/components/rcb/scene/__tests__/sceneText.test.ts index a058ca3f..1edd012c 100644 --- a/apps/web/src/components/rcb/scene/__tests__/sceneText.test.ts +++ b/apps/web/src/components/rcb/scene/__tests__/sceneText.test.ts @@ -68,7 +68,7 @@ describe('measurePlainTextSize', () => { const fontSize = 1; const size = measurePlainTextSize(text, { fontSize, lineHeight: 1.4 }); // eslint-disable-next-line no-console - console.log('[test:text-measure@fs1]', { size, legacyFloor: 24 }); + console.log('[test:text-measure@fs1]', { size, oldFloor: 24 }); expect(size.width).toBeLessThan(24); expect(size.width).toBe(Math.max(fontSize, text.length * fontSize)); expect(size.height).toBe(Math.ceil(fontSize * 1.4)); diff --git a/apps/web/src/components/rcb/scene/document/__tests__/stackCover.test.ts b/apps/web/src/components/rcb/scene/document/__tests__/stackCover.test.ts index d87a93d3..3b16e95e 100644 --- a/apps/web/src/components/rcb/scene/document/__tests__/stackCover.test.ts +++ b/apps/web/src/components/rcb/scene/document/__tests__/stackCover.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { addNodeToDocument, createBareDocument, + reorderNodesInDocument, stackZIndex } from '../sceneDocument'; import { @@ -25,6 +26,36 @@ function svgRoot(attrs: Record = {}) { } describe('unified HTML media stack (foreignObject)', () => { + it('keeps frame children out of the world stack and orders them locally', () => { + let doc = createBareDocument(); + doc.frames = [ + { id: 'frame-a', name: 'A', backgroundColor: '#fff', x: 0, y: 0, width: 300, height: 200 }, + { id: 'frame-b', name: 'B', backgroundColor: '#fff', x: 400, y: 0, width: 300, height: 200 }, + ]; + doc = addNodeToDocument(doc, 'a0', { + id: 'a0', key: 'rect', x: 10, y: 10, width: 20, height: 20, + attrs: { frameId: 'frame-a' }, children: [], + }); + doc = addNodeToDocument(doc, 'a1', { + id: 'a1', key: 'rect', x: 40, y: 10, width: 20, height: 20, + attrs: { frameId: 'frame-a' }, children: [], + }); + doc = addNodeToDocument(doc, 'world', { + id: 'world', key: 'rect', x: 800, y: 10, width: 20, height: 20, + attrs: {}, children: [], + }); + + expect(doc.stackOrder).toEqual(['frame:frame-a', 'frame:frame-b', 'node:world']); + expect(doc.deltaSetLike.a0.attrs.frameOrder).toBe(0); + expect(doc.deltaSetLike.a1.attrs.frameOrder).toBe(1); + expect(stackZIndex(doc, 'node', 'a1')).toBeGreaterThan(stackZIndex(doc, 'node', 'a0')); + + doc = reorderNodesInDocument(doc, ['a0'], 'front'); + expect(doc.deltaSetLike.a0.attrs.frameOrder).toBe(1); + expect(doc.deltaSetLike.a1.attrs.frameOrder).toBe(0); + expect(doc.stackOrder).not.toContain('node:a0'); + }); + it('addNodeToDocument appends new nodes on top of stackOrder', () => { let doc = createBareDocument(); doc = addNodeToDocument(doc, 'lot1', { diff --git a/apps/web/src/components/rcb/scene/document/sceneDocument.ts b/apps/web/src/components/rcb/scene/document/sceneDocument.ts index 549f5621..89c415c9 100644 --- a/apps/web/src/components/rcb/scene/document/sceneDocument.ts +++ b/apps/web/src/components/rcb/scene/document/sceneDocument.ts @@ -55,7 +55,7 @@ export function cloneSceneValue(value: T): T { return JSON.parse(JSON.stringify(plain)) as T; } -/** Unified paint / layer order: `frame:id` | `node:id` (bottom → top). */ +/** World paint order: `frame:id` | unbound `node:id` (bottom → top). */ export function stackFrameKey(id: string) { return `frame:${id}`; } @@ -81,9 +81,20 @@ function listRootNodeIds(doc: SceneDocument): string[] { return Array.isArray(fromRoot) ? fromRoot.filter(Boolean).map(String) : []; } +function isNodeBoundToFrame(doc: SceneDocument, nodeId: string): boolean { + const frameId = String(doc.deltaSetLike?.[nodeId]?.attrs?.frameId || '').trim(); + if (!frameId) return false; + return (doc.frames || []).some((frame) => String(frame?.id || '') === frameId); +} + +function listWorldNodeIds(doc: SceneDocument): string[] { + return listRootNodeIds(doc).filter((nodeId) => !isNodeBoundToFrame(doc, nodeId)); +} + /** - * Keep `doc.stackOrder` in sync with frames + root nodes. - * Empty → frames first, then root nodes. + * Keep `doc.stackOrder` in sync with frames + unbound world nodes. + * Frame children use `attrs.frameOrder` and never occupy a world stack slot. + * Empty → frames first, then unbound nodes. * Missing frames insert under content; missing nodes append on top. */ export function reconcileStackOrder(doc: SceneDocument): string[] { @@ -91,7 +102,7 @@ export function reconcileStackOrder(doc: SceneDocument): string[] { const frameIds = (Array.isArray(doc.frames) ? doc.frames : []) .map((f) => (f?.id != null ? String(f.id) : '')) .filter(Boolean); - const nodeIds = listRootNodeIds(doc); + const nodeIds = listWorldNodeIds(doc); const frameSet = new Set(frameIds); const nodeSet = new Set(nodeIds); const raw = Array.isArray(doc.stackOrder) ? doc.stackOrder.map(String) : []; @@ -151,16 +162,23 @@ const STACK_GROUP_STRIDE = 100000; export function stackZIndex(doc: SceneDocument, kind: 'frame' | 'node', id: string): number { const order = Array.isArray(doc?.stackOrder) ? doc.stackOrder : []; - const key = kind === 'frame' ? stackFrameKey(id) : stackNodeKey(id); - const i = order.indexOf(key); - if (i < 0) return 0; - const groupBase = (i + 1) * STACK_GROUP_STRIDE; - if (kind !== 'node') return groupBase; + if (kind === 'frame') { + const frameIndex = order.indexOf(stackFrameKey(id)); + return frameIndex < 0 ? 0 : (frameIndex + 1) * STACK_GROUP_STRIDE; + } const node = doc.deltaSetLike?.[id]; const frameId = String(node?.attrs?.frameId || '').trim(); - if (!frameId) return groupBase + Math.floor(STACK_GROUP_STRIDE / 2); + if (!frameId) { + const nodeIndex = order.indexOf(stackNodeKey(id)); + if (nodeIndex < 0) return 0; + return (nodeIndex + 1) * STACK_GROUP_STRIDE + Math.floor(STACK_GROUP_STRIDE / 2); + } const frameIndex = order.indexOf(stackFrameKey(frameId)); - if (frameIndex < 0) return groupBase + Math.floor(STACK_GROUP_STRIDE / 2); + if (frameIndex < 0) { + const nodeIndex = order.indexOf(stackNodeKey(id)); + if (nodeIndex < 0) return 0; + return (nodeIndex + 1) * STACK_GROUP_STRIDE + Math.floor(STACK_GROUP_STRIDE / 2); + } const siblings = listRootNodeIds(doc) .map((nodeId) => doc.deltaSetLike?.[nodeId]) .filter((item) => String(item?.attrs?.frameId || '').trim() === frameId); @@ -548,16 +566,36 @@ export function addNodeToDocument( node: SceneNodeInput | Record ) { const next = normalizeDocument(doc); - next.deltaSetLike[nodeId] = node as SceneNode; + const incoming = node as SceneNode; + const frameId = String(incoming.attrs?.frameId || '').trim(); + let storedNode = incoming; + if (frameId) { + const orders = listRootNodeIds(next) + .map((id) => next.deltaSetLike?.[id]) + .filter((item) => String(item?.attrs?.frameId || '').trim() === frameId) + .map((item) => Number(item?.attrs?.frameOrder)) + .filter(Number.isFinite); + storedNode = { + ...incoming, + attrs: { + ...(incoming.attrs || {}), + frameId, + frameOrder: orders.length ? Math.max(...orders) + 1 : 0, + }, + }; + } + next.deltaSetLike[nodeId] = storedNode; const page = getActivePage(next); if (page && !page.children.includes(nodeId)) { page.children.push(nodeId); } syncRootChildren(next); - const key = stackNodeKey(nodeId); - const order = Array.isArray(next.stackOrder) ? next.stackOrder.map(String) : []; - if (!order.includes(key)) next.stackOrder = [...order, key]; - else reconcileStackOrder(next); + if (!frameId) { + const key = stackNodeKey(nodeId); + const order = Array.isArray(next.stackOrder) ? next.stackOrder.map(String) : []; + if (!order.includes(key)) next.stackOrder = [...order, key]; + } + reconcileStackOrder(next); return next; } @@ -666,7 +704,29 @@ export function listSceneNodes(doc: SceneDocument | null | undefined) { .filter((item): item is { id: string; node: SceneNode } => Boolean(item.node)); } -/** Reorder selected nodes in z-order (ROOT / page children + unified stack). */ +function reorderFrameChildrenInDocument( + doc: SceneDocument, + frameId: string, + nodeIds: string[], + action: 'front' | 'back' | 'forward' | 'backward' +) { + const siblings = listRootNodeIds(doc).filter( + (nodeId) => String(doc.deltaSetLike?.[nodeId]?.attrs?.frameId || '').trim() === frameId + ); + const selected = nodeIds.filter((nodeId) => siblings.includes(nodeId)); + if (!selected.length) return; + const reordered = reorderKeysInList(siblings, selected, action); + reordered.forEach((nodeId, index) => { + const node = doc.deltaSetLike?.[nodeId]; + if (!node) return; + doc.deltaSetLike[nodeId] = { + ...node, + attrs: { ...(node.attrs || {}), frameId, frameOrder: index }, + }; + }); +} + +/** Reorder selected nodes in z-order, using each node's owning scope. */ export function reorderNodesInDocument( doc: SceneDocument, nodeIds: string[], @@ -679,24 +739,56 @@ export function reorderNodesInDocument( const selected = nodeIds.filter((id) => ids.includes(id)); if (!selected.length) return next; - page.children = reorderKeysInList(ids, selected, action); + const boundGroups = new Map(); + const worldSelected: string[] = []; + for (const nodeId of selected) { + const frameId = String(next.deltaSetLike?.[nodeId]?.attrs?.frameId || '').trim(); + if (frameId) { + const group = boundGroups.get(frameId) || []; + group.push(nodeId); + boundGroups.set(frameId, group); + continue; + } + worldSelected.push(nodeId); + } + boundGroups.forEach((group, frameId) => { + reorderFrameChildrenInDocument(next, frameId, group, action); + }); + if (worldSelected.length) { + page.children = reorderKeysInList(ids, worldSelected, action); + } syncRootChildren(next); - const selectedKeys = selected.map(stackNodeKey); + const selectedKeys = worldSelected.map(stackNodeKey); const stack = Array.isArray(next.stackOrder) ? next.stackOrder.map(String) : []; - next.stackOrder = reorderKeysInList(stack, selectedKeys, action); + if (selectedKeys.length) { + next.stackOrder = reorderKeysInList(stack, selectedKeys, action); + } reconcileStackOrder(next); return next; } -/** Reorder frames and/or nodes in the unified stack (and sync node page children). */ +/** Reorder world frames/nodes and route bound nodes to their local frame stack. */ export function reorderStackInDocument( doc: SceneDocument, entries: Array<{ kind: 'frame' | 'node'; id: string }>, action: 'front' | 'back' | 'forward' | 'backward' ) { const next = normalizeDocument(doc); - const selectedKeys = entries + const boundGroups = new Map(); + const worldEntries = entries.filter((entry) => { + if (entry.kind === 'frame') return true; + const frameId = String(next.deltaSetLike?.[entry.id]?.attrs?.frameId || '').trim(); + if (!frameId) return true; + const group = boundGroups.get(frameId) || []; + group.push(entry.id); + boundGroups.set(frameId, group); + return false; + }); + boundGroups.forEach((group, frameId) => { + reorderFrameChildrenInDocument(next, frameId, group, action); + }); + const selectedKeys = worldEntries .map((e) => (e.kind === 'frame' ? stackFrameKey(e.id) : stackNodeKey(e.id))) .filter((key) => (next.stackOrder || []).includes(key)); if (!selectedKeys.length) return next; @@ -708,7 +800,7 @@ export function reorderStackInDocument( const page = getActivePage(next); if (page) { - const nodeSelected = entries + const nodeSelected = worldEntries .filter((e) => e.kind === 'node') .map((e) => e.id) .filter((id) => (page.children || []).includes(id)); diff --git a/apps/web/src/components/rcb/scene/document/sceneHitBridge.ts b/apps/web/src/components/rcb/scene/document/sceneHitBridge.ts index a1b8aa5c..da1c45b4 100644 --- a/apps/web/src/components/rcb/scene/document/sceneHitBridge.ts +++ b/apps/web/src/components/rcb/scene/document/sceneHitBridge.ts @@ -205,18 +205,10 @@ export function hitTestSceneAtPoint(opts: HitTestSceneAtPointOpts): string | nul boxes.push({ id, box, hit }); if (hit) { lastHitDebug = { x, y, orderLen: order.length, orderHead: order.slice(0, 8), boxes }; - if (typeof window !== 'undefined') { - (window as unknown as { __rcbLastHitDebug?: typeof lastHitDebug }).__rcbLastHitDebug = - lastHitDebug; - } return id; } } lastHitDebug = { x, y, orderLen: order.length, orderHead: [...order].slice(0, 8), boxes }; - if (typeof window !== 'undefined') { - (window as unknown as { __rcbLastHitDebug?: typeof lastHitDebug }).__rcbLastHitDebug = - lastHitDebug; - } return null; } diff --git a/apps/web/src/components/rcb/scene/document/sceneRadii.ts b/apps/web/src/components/rcb/scene/document/sceneRadii.ts index b0d83699..9c126a6f 100644 --- a/apps/web/src/components/rcb/scene/document/sceneRadii.ts +++ b/apps/web/src/components/rcb/scene/document/sceneRadii.ts @@ -469,14 +469,14 @@ export function radiiFromAttrs(attrs: Record | null | undefined attrs?.radiusTR != null || attrs?.radiusBR != null || attrs?.radiusBL != null; - // Uniform legacy keys: `radius`, agent/import `cornerRadius`, SVG `rx`/`ry`. + // Uniform keys: `radius`, `cornerRadius`, SVG `rx`/`ry`. const uniform = num( attrs?.radius ?? attrs?.cornerRadius ?? attrs?.rx ?? attrs?.ry, NaN ); const stored = parseRadiusVertices(attrs?.radiusVertices); // Prefer per-corner attrs whenever present (toolbar / stroke panel). - // Fall back to uniform `radius` only for legacy nodes without corner keys. + // Fall back to uniform `radius` only when corner keys are absent. if (hasCornerAttrs || !linked || !Number.isFinite(uniform)) { const fallback = Number.isFinite(uniform) ? uniform diff --git a/apps/web/src/components/rcb/scene/paint/svgPaint.ts b/apps/web/src/components/rcb/scene/paint/svgPaint.ts index 64a9b8ab..54c38775 100644 --- a/apps/web/src/components/rcb/scene/paint/svgPaint.ts +++ b/apps/web/src/components/rcb/scene/paint/svgPaint.ts @@ -173,7 +173,7 @@ function applySvgEffects( return; } - // `BackgroundImage` in SVG filters is deprecated and is disabled by modern + // `BackgroundImage` in SVG filters is disabled by modern // browsers in many nested/shared SVG setups. CSS backdrop-filter is the // primary interactive path; the SVG branch below remains for exported SVGs. const backdropFilter = backdrop diff --git a/apps/web/src/components/rcb/selection/SelectionChrome.tsx b/apps/web/src/components/rcb/selection/SelectionChrome.tsx index 9d6f9ebb..f7c37d70 100644 --- a/apps/web/src/components/rcb/selection/SelectionChrome.tsx +++ b/apps/web/src/components/rcb/selection/SelectionChrome.tsx @@ -1044,7 +1044,7 @@ export function pickOverlayHandleAtClient( /** One HTML div hotzone per control (pick + debug paint). */ export const RCB_HIT_ZONE_ATTR = 'data-rcb-hit-zone'; -/** Invisible SVG (or knob) center this div follows ??legacy; prefer scene attrs. */ +/** Invisible SVG (or knob) center this div follows; prefer scene attrs. */ export const RCB_HIT_ANCHOR_ATTR = 'data-rcb-hit-anchor'; export const RCB_HIT_OWNER_ATTR = 'data-rcb-hit-owner'; export const RCB_HIT_PAD_ATTR = 'data-rcb-hit-pad'; @@ -1091,7 +1091,7 @@ export function chromeHitPadOverlayRoot(): HTMLElement | null { return layer; } -/** @deprecated use {@link chromeHitPadOverlayRoot} */ +/** Alias of {@link chromeHitPadOverlayRoot}. */ export function chromeHitPadWorldRoot(): HTMLElement | null { return chromeHitPadOverlayRoot(); } @@ -1312,7 +1312,7 @@ export function mountChromeRectPad(opts: { pad.style.boxSizing = 'border-box'; pad.style.pointerEvents = 'auto'; pad.style.zIndex = '1'; - // Keep the legacy hit pad transparent; rotation is picked by geometry. + // Keep the hit pad transparent; rotation is picked by geometry. pad.style.background = 'transparent'; pad.style.border = 'none'; pad.style.borderRadius = '0'; @@ -1422,7 +1422,7 @@ export function ChromeHitPad({ ); } -/** @deprecated use ChromeHitPad */ +/** Alias of ChromeHitPad. */ export const ChromeSvgHitPad = ChromeHitPad; function parseHitZoneKey(key: string): PaintedHitZonePick | null { @@ -1587,7 +1587,7 @@ export function hitZoneFromEventTarget( return parseHitZoneKey(el.getAttribute(RCB_HIT_ZONE_ATTR) || ''); } -/** SVG yellow disc ??client via getScreenCTM (legacy). */ +/** SVG yellow disc -> client via getScreenCTM. */ function hitZoneCircleClient( el: Element ): { cx: number; cy: number; r: number } | null { @@ -1620,7 +1620,7 @@ function hitZoneHtmlClient(el: Element): { cx: number; cy: number; r: number } | } /** - * Pick by painted hit zones ??each control's HTML div (GBR), else legacy SVG. + * Pick by painted hit zones ??each control's HTML div (GBR), else SVG. */ export function pickPaintedHitZone( clientX: number, diff --git a/apps/web/src/components/rcb/selection/SelectionFeature.tsx b/apps/web/src/components/rcb/selection/SelectionFeature.tsx index 5b965d24..780b04d4 100644 --- a/apps/web/src/components/rcb/selection/SelectionFeature.tsx +++ b/apps/web/src/components/rcb/selection/SelectionFeature.tsx @@ -12,7 +12,6 @@ import { rcbCameraCssZoom, rcbResolveViewportEl, } from '@/components/rcb/core/math'; -import { logEdgeSamples, sampleBoxEdges } from '@/components/rcb/core/dprDebug'; import { getDocumentGridSize, collectPairSpacingGuides, @@ -950,7 +949,7 @@ function SelectionFeature({ const lockedSelection = isSelectionOriginsLocked(sceneDoc, liveOriginsNow); const pickOpts = chromePickOptsRef.current; - // One pick: overlay seats → geometry chrome → (legacy DOM chrome). + // One pick: overlay seats → geometry chrome → DOM chrome. // Scene point shared with CameraTransform (ADR 0027). let chromePick: ChromeHandlePick | null = null; if ( @@ -2134,23 +2133,6 @@ function SelectionFeature({ clientToScene: (clientX, clientY) => toScene(clientX, clientY), }; - // DPR seam diagnostics ??opt-in: window.__RCB_DPR_DEBUG__ = true - useEffect(() => { - if (!enabled) return; - if (typeof window === 'undefined') return; - if (window.__RCB_DPR_DEBUG__ !== true) return; - if (!selectedNodeIds.length) return; - const dpr = window.devicePixelRatio || 1; - const samples = selectedNodeIds - .map((id) => { - const b = getNodeBox(id); - if (!b) return null; - return sampleBoxEdges(id, b, camera, dpr); - }) - .filter(Boolean) as ReturnType[]; - logEdgeSamples(`selection(${selectedNodeIds.length})`, samples, dpr, camera); - }, [enabled, selectedNodeIds, camera.x, camera.y, camera.zoom, getNodeBox, camera]); - const chromeUnion = resolveChromeUnion({ transforming, liveUnion, diff --git a/apps/web/src/components/rcb/selection/__tests__/chromePickDefersToRadius.test.ts b/apps/web/src/components/rcb/selection/__tests__/chromePickDefersToRadius.test.ts index a712f0dd..9bcfea8c 100644 --- a/apps/web/src/components/rcb/selection/__tests__/chromePickDefersToRadius.test.ts +++ b/apps/web/src/components/rcb/selection/__tests__/chromePickDefersToRadius.test.ts @@ -1,6 +1,6 @@ /** * Chrome pick must not steal radius / shape overlay ink. - * Pipeline (ADR 0027): overlay DOM → chrome **geometry** → legacy DOM chrome. + * Pipeline (ADR 0027): overlay DOM → chrome **geometry** → DOM chrome. */ import { describe, expect, it, beforeEach, afterEach } from 'vitest'; import { diff --git a/apps/web/src/components/rcb/selection/__tests__/generatorPlaceGrid.test.ts b/apps/web/src/components/rcb/selection/__tests__/generatorPlaceGrid.test.ts index dec4536e..babc9445 100644 --- a/apps/web/src/components/rcb/selection/__tests__/generatorPlaceGrid.test.ts +++ b/apps/web/src/components/rcb/selection/__tests__/generatorPlaceGrid.test.ts @@ -68,12 +68,12 @@ describe('generator plate place size + grid', () => { it('empty-gen icon fits inside a small high-zoom plate (no 72px floor)', () => { const box = 18; const icon = generatorEmptyIconSize(box, box); - const legacyBroken = Math.max(72, box * 0.34); + const oldFloor = Math.max(72, box * 0.34); // eslint-disable-next-line no-console - console.log('[test:gen-icon@small]', { box, icon, legacyBroken }); + console.log('[test:gen-icon@small]', { box, icon, oldFloor }); expect(icon).toBeLessThan(box); expect(icon).toBeCloseTo(box * 0.28, 6); - expect(legacyBroken).toBeGreaterThan(box); + expect(oldFloor).toBeGreaterThan(box); }); it('generator plates have no visual stroke outset (inset border === path)', () => { diff --git a/apps/web/src/components/rcb/selection/__tests__/highZoomHitAndMove.test.ts b/apps/web/src/components/rcb/selection/__tests__/highZoomHitAndMove.test.ts index eb8c9164..2a61cfe5 100644 --- a/apps/web/src/components/rcb/selection/__tests__/highZoomHitAndMove.test.ts +++ b/apps/web/src/components/rcb/selection/__tests__/highZoomHitAndMove.test.ts @@ -8,9 +8,9 @@ describe('sceneHitSlop (high-zoom blank click)', () => { const pad = sceneHitSlop(zoom); expect(pad).toBeCloseTo(12 / 40, 6); // Old bug: Math.max(STROKE_HIT/2, 12/zoom) === 12 scene u ≈ 480 CSS px. - const legacyBroken = Math.max(STROKE_HIT / 2, 12 / zoom); - expect(legacyBroken).toBe(12); - expect(pad * zoom).toBeLessThan(legacyBroken * zoom / 10); + const oldHit = Math.max(STROKE_HIT / 2, 12 / zoom); + expect(oldHit).toBe(12); + expect(pad * zoom).toBeLessThan(oldHit * zoom / 10); }); it('click 2 grid cells outside a 1px-stroke rect is outside hit slop at zoom 40', () => { diff --git a/apps/web/src/components/rcb/selection/__tests__/pickPaintedHitZone.test.ts b/apps/web/src/components/rcb/selection/__tests__/pickPaintedHitZone.test.ts index fffd121c..550103f9 100644 --- a/apps/web/src/components/rcb/selection/__tests__/pickPaintedHitZone.test.ts +++ b/apps/web/src/components/rcb/selection/__tests__/pickPaintedHitZone.test.ts @@ -1,5 +1,5 @@ /** - * Hit zones — SVG CTM circles (chrome); HTML GBR kept for legacy pads. + * Hit zones — SVG CTM circles (chrome); HTML GBR kept for painted pads. */ import { describe, expect, it, beforeEach, afterEach } from 'vitest'; import { diff --git a/apps/web/src/components/rcb/selection/chrome/BlendModeControl.tsx b/apps/web/src/components/rcb/selection/chrome/BlendModeControl.tsx index 4e1e629f..411c3d6a 100644 --- a/apps/web/src/components/rcb/selection/chrome/BlendModeControl.tsx +++ b/apps/web/src/components/rcb/selection/chrome/BlendModeControl.tsx @@ -1,18 +1,21 @@ +import { useMemo, useState, type CSSProperties, type ReactNode, memo } from 'react'; import { - useEffect, - useMemo, - useRef, - useState, - type CSSProperties, - type ReactNode, - memo, -} from 'react'; + autoUpdate, + flip, + FloatingPortal, + offset, + shift, + useClick, + useDismiss, + useFloating, + useInteractions, +} from '@floating-ui/react'; import { useTranslation } from 'react-i18next'; -import { BiExit } from 'react-icons/bi'; import { HiOutlineArrowPath, HiOutlineCheck, HiOutlineChevronDown } from 'react-icons/hi2'; import { MdOutlineOpacity } from 'react-icons/md'; import { Dropdown } from '@/components/base'; import type { MenuItemType } from '@/components/base/dropdown'; +import { DropdownPanel } from '@/components/base/dropdown/DropdownPanel'; import Slider from '@/components/base/slider'; import Tooltip from '@/components/base/tooltip'; import { cn } from '@/utils/classnames'; @@ -126,8 +129,95 @@ export function BlendModeIcon({ mode, className }: { mode: BlendModeId; classNam ); } -const opacityPanelBtn = - 'inline-flex h-7 min-w-0 flex-1 items-center justify-center whitespace-nowrap rounded-xl px-2 text-[12px] font-medium leading-none transition-colors'; +export function OpacityControl({ + opacity, + onOpacityChange, + className, +}: { + opacity?: unknown; + onOpacityChange: (opacity01: number) => void; + className?: string; +}) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const pct = layerOpacityToPct(parseLayerOpacity(opacity, 1)); + const opacityLabel = t('editor.imageToolbar.opacity'); + const applyPct = (nextPct: number) => { + onOpacityChange(clampOpacityPct(nextPct) / 100); + }; + const { refs, floatingStyles, context } = useFloating({ + open, + onOpenChange: setOpen, + placement: 'bottom-start', + strategy: 'fixed', + whileElementsMounted: autoUpdate, + middleware: [ + offset(6), + flip({ + padding: 12, + fallbackPlacements: ['top-start', 'top-end', 'right-start', 'left-start'], + }), + shift({ padding: 12 }), + ], + }); + const click = useClick(context); + const dismiss = useDismiss(context, { outsidePressEvent: 'pointerdown' }); + const { getReferenceProps, getFloatingProps } = useInteractions([click, dismiss]); + + return ( +
+ + + {open ? ( + +
+ + {opacityLabel} + + + + +
+
+ +
+
+ ) : null} +
+
+ ); +} type Props = { blendMode?: unknown; @@ -136,11 +226,6 @@ type Props = { allowPassThrough?: boolean; onBlendModeChange: (mode: BlendModeId) => void; onOpacityChange: (opacity01: number) => void; - /** - * When set (e.g. image selection), opacity opens a docked side panel and the - * selection toolbar hides — same pattern as Eraser. Trigger shows label text. - */ - onOpacityOpen?: () => void; /** Inserted between blend-mode dropdown and opacity (e.g. corner radius). */ afterBlendSlot?: ReactNode; className?: string; @@ -152,19 +237,12 @@ function BlendModeControl({ allowPassThrough = false, onBlendModeChange, onOpacityChange, - onOpacityOpen, afterBlendSlot, className, }: Props) { const { t } = useTranslation(); const [blendOpen, setBlendOpen] = useState(false); - const [opacityOpen, setOpacityOpen] = useState(false); - const opacityRootRef = useRef(null); - const baselinePctRef = useRef(100); const mode = parseBlendMode(blendMode, { allowPassThrough }); - const pct = layerOpacityToPct(parseLayerOpacity(opacity, 1)); - const opacityLabel = t('editor.imageToolbar.opacity'); - const labelOf = (id: BlendModeId) => t(`editor.blendMode.${id}`); const items: MenuItemType[] = useMemo(() => { @@ -193,59 +271,12 @@ function BlendModeControl({ // eslint-disable-next-line react-hooks/exhaustive-deps -- t + mode drive labels }, [mode, t, allowPassThrough]); - const applyPct = (nextPct: number) => { - onOpacityChange(clampOpacityPct(nextPct) / 100); - }; - - const openOpacityPanel = () => { - if (onOpacityOpen) { - onOpacityOpen(); - return; - } - baselinePctRef.current = pct; - setBlendOpen(false); - setOpacityOpen(true); - }; - - const closeOpacityKeep = () => { - setOpacityOpen(false); - }; - - const closeOpacityRevert = () => { - applyPct(baselinePctRef.current); - setOpacityOpen(false); - }; - - useEffect(() => { - if (!opacityOpen || onOpacityOpen) return undefined; - const onDown = (e: PointerEvent) => { - if (opacityRootRef.current?.contains(e.target as Node)) return; - setOpacityOpen(false); - }; - const onKey = (e: KeyboardEvent) => { - if (e.key === 'Escape') { - e.preventDefault(); - closeOpacityRevert(); - } - }; - window.addEventListener('pointerdown', onDown, true); - window.addEventListener('keydown', onKey); - return () => { - window.removeEventListener('pointerdown', onDown, true); - window.removeEventListener('keydown', onKey); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [opacityOpen, onOpacityOpen]); - return (
{ - setBlendOpen(next); - if (next) setOpacityOpen(false); - }} + onOpenChange={setBlendOpen} placement="bottom-start" offset={6} strategy="fixed" @@ -275,96 +306,7 @@ function BlendModeControl({ {afterBlendSlot} -
- - - {!onOpacityOpen && opacityOpen ? ( -
{ - e.stopPropagation(); - e.nativeEvent.stopImmediatePropagation?.(); - }} - > -
-

- {opacityLabel} -

-
- - - - - - -
-
- -
- -
- -
- - -
-
- ) : null} -
+
); } diff --git a/apps/web/src/components/rcb/selection/chrome/EffectsControl.tsx b/apps/web/src/components/rcb/selection/chrome/EffectsControl.tsx index aeed494a..074122fc 100644 --- a/apps/web/src/components/rcb/selection/chrome/EffectsControl.tsx +++ b/apps/web/src/components/rcb/selection/chrome/EffectsControl.tsx @@ -1,27 +1,8 @@ -import { useState, memo, type ReactNode } from 'react'; -import { - autoUpdate, - flip, - FloatingPortal, - offset, - shift, - useDismiss, - useFloating, - useInteractions, - useClick, -} from '@floating-ui/react'; -import { - HiOutlineAdjustmentsHorizontal, - HiOutlineArrowsRightLeft, - HiOutlineChevronDown, -} from 'react-icons/hi2'; +import { type ReactNode } from 'react'; +import { HiOutlineArrowsRightLeft } from 'react-icons/hi2'; import { ColorPanelPopover } from '@/components/base/colorPanel'; import Slider from '@/components/base/slider'; import Switch from '@/components/base/switch'; -import Tooltip from '@/components/base/tooltip'; -import { DropdownPanel } from '@/components/base/dropdown/DropdownPanel'; -import { cn } from '@/utils/classnames'; -import { SEL_ICON_BTN_ACTIVE, SEL_TOOL_BTN } from './ToolbarValueSlider'; type EffectPatch = Record; @@ -218,60 +199,3 @@ export function EffectsForm({ attrs, onChange }: Props) { ); } - -function EffectsControl({ attrs, onChange }: Props) { - const [open, setOpen] = useState(false); - const { refs, floatingStyles, context } = useFloating({ - open, - onOpenChange: setOpen, - placement: 'bottom-start', - strategy: 'fixed', - whileElementsMounted: autoUpdate, - middleware: [ - offset(6), - flip({ - padding: 12, - fallbackPlacements: ['top-start', 'top-end', 'right-start', 'left-start'], - }), - shift({ padding: 12 }), - ], - }); - const click = useClick(context); - const dismiss = useDismiss(context, { outsidePressEvent: 'pointerdown' }); - const { getReferenceProps, getFloatingProps } = useInteractions([click, dismiss]); - - return ( -
- - - - - {open ? ( - -
效果
- -
- ) : null} -
-
- ); -} - -export default memo(EffectsControl); diff --git a/apps/web/src/components/rcb/selection/chrome/SelectionContextToolbar.tsx b/apps/web/src/components/rcb/selection/chrome/SelectionContextToolbar.tsx index c6eae9a3..84309389 100644 --- a/apps/web/src/components/rcb/selection/chrome/SelectionContextToolbar.tsx +++ b/apps/web/src/components/rcb/selection/chrome/SelectionContextToolbar.tsx @@ -62,8 +62,7 @@ import { } from '@/components/rcb/scene/document/nodeCapabilities'; import { type ImageProcessKind } from '@/components/rcb/scene/document/mediaLifecycle'; import ToolbarMenuSelect from './ToolbarMenuSelect'; -import BlendModeControl from './BlendModeControl'; -import EffectsControl from './EffectsControl'; +import { BlendModeIcon, OpacityControl } from './BlendModeControl'; import { SEL_ICON_BTN, SEL_ICON_BTN_ACTIVE, @@ -74,7 +73,9 @@ import TextEditDialog from '@/components/editor/nodes/TextNode/TextEditDialog'; import IconAnnotateToolbar from '@/components/editor/nodes/ImageNode/IconAnnotateToolbar'; import ImageToolbarEditTools from '@/components/editor/nodes/ImageNode/ImageToolbarEditTools'; import ImageToolbarMoreDownload, { + ToolbarMoreMenu, type ImageMoreAction, + type ToolbarMoreItem, } from '@/components/editor/nodes/ImageNode/ImageToolbarMoreDownload'; import ImageFullscreenPreviewButton from '@/components/editor/nodes/ImageNode/ImageFullscreenPreviewButton'; import { @@ -93,6 +94,7 @@ import { buildOutlinePathAsync, canOutlineNode, outlineNodePatch, + requestEnterPathEdit, } from '@/components/rcb/scene/paint/outlineToPath'; import { loadFontCatalog, @@ -101,7 +103,7 @@ import { toggleCatalogTextBold, weightOptionsForFamily, } from '@/components/rcb/scene/document/fontCatalog'; -import { TbVectorBezier } from 'react-icons/tb'; +import { TbDroplet, TbVectorBezier } from 'react-icons/tb'; import { message } from '@/components/base'; import { cn } from '@/utils/classnames'; import type { SceneDocument, SceneNode, SceneNodeInput } from '@/components/rcb/sceneNode'; @@ -297,6 +299,7 @@ async function outlineSelectedNode(opts: { loadingLabel: string; failLabel: string; okLabel: string; + enterPathEdit?: boolean; }) { const hide = message.loading(opts.loadingLabel, 0); try { @@ -319,8 +322,12 @@ async function outlineSelectedNode(opts: { }, }) ); - // Like text 轮廓化: stay on the filled silhouette in normal selection. - // Auto path-edit force-hides the host → hairline + knob carpet. + if (opts.enterPathEdit) { + const st = String(opts.node?.attrs?.shapeType || opts.node?.key || ''); + const fromStrokeOutline = + st === 'pen' || st === 'pencil' || st === 'line' || st === 'arrow'; + requestEnterPathEdit(opts.nodeId, outline.pathD, { fromStrokeOutline }); + } message.success(opts.okLabel); } finally { hide(); @@ -444,28 +451,70 @@ function SelectionContextToolbar(props: Props): ReactNode { ); }; - const showBlend = kind !== 'image'; + const showLayerChrome = kind !== 'image'; const supportsEffects = !['image', 'video', 'audio', 'lottie', 'frame', 'group'].includes(kind); - const effectControl = supportsEffects ? ( - dispatch(patchDocumentNode({ nodeId, patch: { attrs } }))} - /> - ) : null; + const showOutline = canOutlineNode(node); const imageAspectLocked = resolveImageAspectLocked(node, kind); - const blendControl = showBlend ? ( - - dispatch(patchDocumentNode({ nodeId, patch: { attrs: { blendMode: mode } } })) - } onOpacityChange={(opacity) => dispatch(patchDocumentNode({ nodeId, patch: { attrs: { opacity } } })) } /> ) : null; + const elementMoreItems: ToolbarMoreItem[] = []; + if (showOutline) { + elementMoreItems.push({ + key: 'outline', + icon: , + label: t('editor.imageToolbar.outline'), + }); + } + if (showLayerChrome) { + elementMoreItems.push({ + key: 'blendMode', + icon: , + label: t('editor.imageToolbar.blendMode'), + }); + } + if (supportsEffects) { + elementMoreItems.push({ + key: 'effects', + icon: , + label: t('editor.imageToolbar.effects'), + }); + } + const runElementMore = (key: string) => { + if (key === 'outline') { + const isShapeKind = + kind === 'shape' || kind === 'rect' || kind === 'ellipse' || kind === 'path'; + outlineSelectedNode({ + node, + nodeId, + dispatch, + loadingLabel: '轮廓化中…', + failLabel: '轮廓化失败', + okLabel: '已轮廓化', + enterPathEdit: isShapeKind, + }); + return; + } + if (key === 'blendMode' || key === 'effects') { + dispatch(openImageToolPanel({ nodeId, kind: key })); + } + }; + const elementLayerChrome = + opacityControl || elementMoreItems.length ? ( + <> + {opacityControl} + + + ) : null; if (quickEditOpen || lottieEditOpen) { if (kind === 'video') { @@ -678,7 +727,7 @@ function SelectionContextToolbar(props: Props): ReactNode { } bare={kind === 'image' && isIconImageNode(node)} > - {/* Order: Style/Edit → Geometry → Blend/Opacity → Actions */} + {/* Order: Style/Edit → Geometry → Opacity → More → Actions */} {kind === 'text' && style ? ( <> - {canOutlineNode(node) ? ( - - - - ) : null} - {blendControl ? ( - <> - - {blendControl} - - ) : null} - {effectControl ? ( - <> - - {effectControl} - - ) : null} + {elementLayerChrome} @@ -912,28 +928,16 @@ function SelectionContextToolbar(props: Props): ReactNode { document={document} hideExport /> - {blendControl} - {effectControl ? ( - <> - - {effectControl} - - ) : null} + {elementLayerChrome} ) : null} {kind === 'svg' ? ( <> - {blendControl ? ( - <> - {blendControl} - - - ) : null} - {effectControl ? ( + {elementLayerChrome ? ( <> - {effectControl} + {elementLayerChrome} ) : null} diff --git a/apps/web/src/components/rcb/shapes/RcbShapeHost.tsx b/apps/web/src/components/rcb/shapes/RcbShapeHost.tsx index 1bc1ccbc..a4c59631 100644 --- a/apps/web/src/components/rcb/shapes/RcbShapeHost.tsx +++ b/apps/web/src/components/rcb/shapes/RcbShapeHost.tsx @@ -27,20 +27,6 @@ import { } from '@/components/rcb/shapes/shapeHostRegistry'; import type { SceneDocument } from '@/components/rcb/sceneNode'; -function hostJumpLog(event: string, data: Record = {}) { - if (!import.meta.env.DEV) return; - const row = { event, t: Math.round(performance.now()), ...data }; - const w = window as Window & { - __rcbJumpLog?: unknown[]; - __rcbJumpDump?: () => string; - }; - if (!Array.isArray(w.__rcbJumpLog)) w.__rcbJumpLog = []; - w.__rcbJumpLog.push(row); - if (w.__rcbJumpLog.length > 300) w.__rcbJumpLog.splice(0, w.__rcbJumpLog.length - 300); - w.__rcbJumpDump = () => JSON.stringify(w.__rcbJumpLog, null, 2); - console.info(JSON.stringify(row)); -} - type Props = { nodeId: string; document: SceneDocument; @@ -260,7 +246,6 @@ function RcbShapeHost({ return () => { cancelled = true; - hostJumpLog('host.unmount', { nodeId, paintToken: String(paintToken).slice(0, 120) }); unregisterShapeHost(nodeId); try { layer.remove(); diff --git a/apps/web/src/components/rcb/tools/__tests__/penAnchorGridSnap.test.ts b/apps/web/src/components/rcb/tools/__tests__/penAnchorGridSnap.test.ts index d0852c51..795a7c0d 100644 --- a/apps/web/src/components/rcb/tools/__tests__/penAnchorGridSnap.test.ts +++ b/apps/web/src/components/rcb/tools/__tests__/penAnchorGridSnap.test.ts @@ -129,7 +129,7 @@ describe('pen draw full flow (click → snap → path)', () => { expect(bounds.width).toBeGreaterThan(0); }); - it('edit-drag: start off-grid legacy + move → ends on lattice', () => { + it('edit-drag: start off-grid then move → ends on lattice', () => { const start = { x: 14.3, y: 11.7 }; const pointer = { x: 20.2, y: 15.1 }; const dx = pointer.x - 14.3; diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index 4d32d41b..5912694f 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -844,6 +844,7 @@ const en = { fitCanvas: 'Zoom to fit', zoomToPercent: 'Zoom to {{percent}}%', zoomMenu: 'Zoom', + fpsHud: 'FPS meter', pathEditSelect: 'Select', pathEditPen: 'Pen', pathEditAddAnchor: 'Add anchor', @@ -1840,7 +1841,7 @@ const en = { settings: 'Model settings', settingsTitle: 'Add model', settingsHint: - 'Add an OpenAI / Claude-compatible provider. Saved providers appear in the model list. Scenes are routed automatically by the orchestrator.', + 'Add an OpenAI / Claude-style provider. Saved providers appear in the model list. Scenes are routed automatically by the orchestrator.', composerMode: 'Mode', modeAgent: 'Agent', providerName: 'Provider name', @@ -1894,7 +1895,7 @@ const en = { providerApiKeyHint: 'Keys stay in this browser only. Uses your own provider quota — not billed on platform credits. Custom endpoint proxy comes next.', providerBaseUrl: 'Base URL', - providerBaseUrlHint: 'OpenAI / Claude-compatible endpoint. Do not end with a slash.', + providerBaseUrlHint: 'OpenAI / Claude-style endpoint. Do not end with a slash.', providerSave: 'Save provider', providerSaveMember: 'Subscribe to save', providerSaved: 'Saved providers', diff --git a/apps/web/src/i18n/locales/ja.ts b/apps/web/src/i18n/locales/ja.ts index c890f4df..d3c293c0 100644 --- a/apps/web/src/i18n/locales/ja.ts +++ b/apps/web/src/i18n/locales/ja.ts @@ -823,6 +823,7 @@ const ja = { fitCanvas: '画面に合わせる', zoomToPercent: '{{percent}}% にズーム', zoomMenu: 'ズーム', + fpsHud: 'FPSメーター', pathEditSelect: '選択', pathEditPen: 'ペン', pathEditAddAnchor: 'アンカーを追加', diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index 96ff351d..3d78f162 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -836,6 +836,7 @@ const zhCN = { fitCanvas: '缩放以适合', zoomToPercent: '缩放至 {{percent}}%', zoomMenu: '缩放', + fpsHud: '帧率监视', pathEditSelect: '选择', pathEditPen: '钢笔', pathEditAddAnchor: '增加锚点', diff --git a/apps/web/src/i18n/locales/zh-TW.ts b/apps/web/src/i18n/locales/zh-TW.ts index a855e8b4..5f370c11 100644 --- a/apps/web/src/i18n/locales/zh-TW.ts +++ b/apps/web/src/i18n/locales/zh-TW.ts @@ -816,6 +816,7 @@ const zhTW = { fitCanvas: '縮放以適合', zoomToPercent: '縮放至 {{percent}}%', zoomMenu: '縮放', + fpsHud: '幀率監視', pathEditSelect: '選擇', pathEditPen: '鋼筆', pathEditAddAnchor: '增加錨點', diff --git a/apps/web/src/models/plaza.ts b/apps/web/src/models/plaza.ts index 592a0bb8..12c13d70 100644 --- a/apps/web/src/models/plaza.ts +++ b/apps/web/src/models/plaza.ts @@ -71,9 +71,6 @@ export function plazaDisplayCoverUrls(item: { }): string[] { const custom = String(item.customCoverImageUrl || '').trim(); if (custom) return [custom]; - if (Array.isArray(item.thumbnailUrl)) { - return item.thumbnailUrl.map((u) => String(u || '').trim()).filter(Boolean).slice(0, 4); - } - const one = String(item.thumbnailUrl || '').trim(); - return one ? [one] : []; + if (!Array.isArray(item.thumbnailUrl)) return []; + return item.thumbnailUrl.map((u) => String(u || '').trim()).filter(Boolean).slice(0, 4); } diff --git a/apps/web/src/pages/EditorPage.tsx b/apps/web/src/pages/EditorPage.tsx index bdb87b3f..17d7064e 100644 --- a/apps/web/src/pages/EditorPage.tsx +++ b/apps/web/src/pages/EditorPage.tsx @@ -96,17 +96,6 @@ import EditorStageWorld from '@/components/editor/page/EditorStageWorld'; const BOOT_MIN_MS = 520; const BOOT_EXIT_MS = 280; -/** Jump diagnostics (`window.__rcbJumpDump`). */ -function rcbJumpLog(event: string, data: Record = {}) { - const row = { event, t: Math.round(performance.now()), ...data }; - const w = window as Window & { - __rcbJumpLog?: unknown[]; - __rcbJumpDump?: () => string; - }; - if (!Array.isArray(w.__rcbJumpLog)) w.__rcbJumpLog = []; - w.__rcbJumpLog.push(row); - w.__rcbJumpDump = () => JSON.stringify(w.__rcbJumpLog, null, 2); -} function documentToCanvasFill(document: SceneDocument, themeFallback: string): FillPanelValue { const raw = String(document?.backgroundColor || '').trim(); @@ -689,7 +678,7 @@ function EditorPage() { [document, followThemeCanvas, themeCanvas] ); - /** Editor UI is design-only; hide legacy Design/Dev toggle. */ + /** Editor UI is design-only; hide Design/Dev toggle. */ useEffect(() => { dispatch(setWorkspaceMode('design')); }, [dispatch]); @@ -711,7 +700,7 @@ function EditorPage() { const [stageSize, setStageSize] = useState({ width: 0, height: 0 }); useEffect(() => { const el = stageEl; - if (!el || typeof ResizeObserver === 'undefined') return undefined; + if (!el) return undefined; const apply = () => { const next = { width: Math.max(1, el.clientWidth), @@ -719,12 +708,6 @@ function EditorPage() { }; setStageSize((prev) => { if (prev.width === next.width && prev.height === next.height) return prev; - rcbJumpLog('stageSize', { - prev, - next, - bootOpen: bootOpenRef.current, - didFit: didInitialFitRef.current, - }); return next; }); }; @@ -734,27 +717,6 @@ function EditorPage() { return () => ro.disconnect(); }, [stageEl]); - /** - * Catch late auto-fit / collab camera writes AFTER boot. - * Skip when the user already owns the camera 鈥?otherwise every wheel zoom - * spam-logs as `afterReveal` and looks like a reveal fight (it is not). - */ - useEffect(() => { - if (bootOpen) return; - if (cameraUserTouchedRef.current) return; - rcbJumpLog('camera.afterReveal', { - x: Number(camera.x.toFixed(2)), - y: Number(camera.y.toFixed(2)), - zoom: Number(camera.zoom.toFixed(4)), - userTouched: false, - stageW: stageSize.width, - stageH: stageSize.height, - stack: (new Error().stack || '') - .split('\n') - .slice(2, 10) - .map((s) => s.trim()), - }); - }, [bootOpen, camera.x, camera.y, camera.zoom, stageSize.width, stageSize.height]); // Scene paper follows content bounds only. Camera pan/zoom is CSS on RcbCanvas 鈥? // never resize/slide SVG viewBox to chase the frustum. @@ -1107,30 +1069,16 @@ function EditorPage() { bootFinishingRef.current = true; const el = stageRef.current; const cam = cameraRef.current; - rcbJumpLog('finishBoot.start', { - waitMs: Math.max(0, BOOT_MIN_MS - (Date.now() - bootStartedAt.current)), - stageW: el?.clientWidth || 0, - stageH: el?.clientHeight || 0, - camera: { x: cam.x, y: cam.y, zoom: cam.zoom }, - }); const wait = Math.max(0, BOOT_MIN_MS - (Date.now() - bootStartedAt.current)); window.setTimeout(() => { setBootProgress(advanceBootProgress(100)); setBootExiting(true); - rcbJumpLog('finishBoot.exiting', { - stageW: stageRef.current?.clientWidth || 0, - stageH: stageRef.current?.clientHeight || 0, - }); bootExitTimer.current = window.setTimeout(() => { bootOpenRef.current = false; setBootOpen(false); setBootExiting(false); bootExitTimer.current = null; resetBootProgress(); - rcbJumpLog('finishBoot.revealed', { - stageW: stageRef.current?.clientWidth || 0, - stageH: stageRef.current?.clientHeight || 0, - }); }, BOOT_EXIT_MS); }, wait); }, []); @@ -1202,7 +1150,6 @@ function EditorPage() { const vh = el?.clientHeight || 0; // Match RcbCanvas autofit gate 鈥?tiny/unlaid-out stages must not count as fitted. if (vw < 40 || vh < 40) { - rcbJumpLog('fitView.skipTiny', { vw, vh }); return false; } const doc = (store.getState() as any).editor?.document; @@ -1210,27 +1157,12 @@ function EditorPage() { // Empty scene 鈫?100%. With content 鈫?fit all artboards/nodes with 120px margins. if (!editorHasFitContent(doc, fr)) { const next = { ...DEFAULT_CAMERA, zoom: 1 }; - rcbJumpLog('fitView.empty100', { vw, vh, next }); setCamera(next); setZoomFitActive(true); return true; } const bounds = editorContentBounds(doc, fr); const next = rcbFitCamera({ width: vw, height: vh }, bounds, 120, 1); - rcbJumpLog('fitView', { - vw, - vh, - bounds, - docOrigin: { x: Number(doc?.x) || 0, y: Number(doc?.y) || 0 }, - next: { - x: Number(next.x.toFixed(2)), - y: Number(next.y.toFixed(2)), - zoom: Number(next.zoom.toFixed(4)), - }, - bootOpen: bootOpenRef.current, - userTouched: cameraUserTouchedRef.current, - }); - // Camera pan/zoom only 鈥?never move node/frame scene coordinates. setCamera(next); setZoomFitActive(true); return true; @@ -1246,11 +1178,6 @@ function EditorPage() { const onCanvasCameraChange = useCallback((next: CanvasCamera) => { cameraUserTouchedRef.current = true; setZoomFitActive(false); - rcbJumpLog('camera.user', { - x: Number(next.x.toFixed(2)), - y: Number(next.y.toFixed(2)), - zoom: Number(next.zoom.toFixed(4)), - }); setCamera(next); }, []); @@ -1273,7 +1200,6 @@ function EditorPage() { const ox = Number(document.x) || 0; const oy = Number(document.y) || 0; if (ox !== 0 || oy !== 0) { - rcbJumpLog('bakeDocumentOrigin', { ox, oy, currentId }); dispatch(bakeDocumentOrigin()); return; } @@ -1295,14 +1221,6 @@ function EditorPage() { const finishOnce = (fitted: boolean) => { if (cancelled) return; didInitialFitRef.current = true; - rcbJumpLog('initialFit.done', { - fitted, - stageW: stageRef.current?.clientWidth || 0, - stageH: stageRef.current?.clientHeight || 0, - tries, - stableFrames, - hasContent, - }); finishBoot(); }; @@ -1324,13 +1242,6 @@ function EditorPage() { if (Math.abs(w - lastW) <= 1 && Math.abs(h - lastH) <= 1) { stableFrames += 1; } else { - if (lastW || lastH) { - rcbJumpLog('initialFit.stageUnstable', { - from: { w: lastW, h: lastH }, - to: { w, h }, - tries, - }); - } stableFrames = 0; lastW = w; lastH = h; diff --git a/apps/web/src/service/auth.ts b/apps/web/src/service/auth.ts index a3e2a3f2..c221488f 100644 --- a/apps/web/src/service/auth.ts +++ b/apps/web/src/service/auth.ts @@ -35,7 +35,7 @@ export const sendEmailCode = (data: { email: string; captchaToken?: string }) => mode?: string; }>; -/** Consume /activate/:id one-time link → session (legacy magic-link mails). */ +/** Consume /activate/:id one-time link → session (email magic-link mails). */ export const activateEmailLink = (data: { id: string }) => apiClient.authEmailActivate({ body: data }) as Promise<{ user: AuthUserDto; diff --git a/apps/web/src/service/chat.ts b/apps/web/src/service/chat.ts index df586786..030339b6 100644 --- a/apps/web/src/service/chat.ts +++ b/apps/web/src/service/chat.ts @@ -69,7 +69,7 @@ export type ByokPresetDefaults = { defaultDuration?: number; }; -/** One selectable model under a legacy per-endpoint preset. */ +/** One selectable model under a per-endpoint preset. */ export type ByokPresetModel = { apiModel: string; label: string; @@ -91,11 +91,6 @@ export type ByokPlatform = { hint?: string; }; -/** @deprecated Prefer ByokPlatform — older ``byokPresets`` field. */ -export type ByokPresetProvider = ByokPlatform & { - models?: ByokPresetModel[]; -}; - export type ChatModelsResponse = { models: LlmModel[]; available: boolean; @@ -108,8 +103,6 @@ export type ChatModelsResponse = { openrouterAvailable?: boolean; /** Aggregator platforms — one key unlocks catalog models. */ byokPlatforms?: ByokPlatform[]; - /** Alias of byokPlatforms for older clients. */ - byokPresets?: ByokPresetProvider[]; }; export type GenerateImageInput = { diff --git a/apps/web/src/service/client.ts b/apps/web/src/service/client.ts index 75c9e00a..d3243b21 100644 --- a/apps/web/src/service/client.ts +++ b/apps/web/src/service/client.ts @@ -54,7 +54,7 @@ export function getHttpErrorDetail(err: unknown): unknown { return undefined; } -/** User-facing message from oRPC / ky / legacy axios errors. */ +/** User-facing message from oRPC / ky / axios-family errors. */ export function getHttpErrorMessage(err: unknown, fallback = ''): string { const detail = getHttpErrorDetail(err); if (typeof detail === 'string' && detail.trim()) return detail; diff --git a/apps/web/src/service/wallet.ts b/apps/web/src/service/wallet.ts index 39388efd..f5fbb0c1 100644 --- a/apps/web/src/service/wallet.ts +++ b/apps/web/src/service/wallet.ts @@ -58,7 +58,6 @@ function mergePlanCatalog(rows: WalletPlanRow[] | undefined): Record = { mark: true, }; +/** Blend / effects dock beside any selected node (not image-only tools). */ +const NODE_LAYER_TOOL_PANEL_KIND: Record = { + effects: true, + blendMode: true, +}; + const IMAGE_TOOL_CROP_SESSION_KIND: Record = { crop: true, expand: true, @@ -146,6 +152,10 @@ export function isImageToolSidePanelKind(kind: string | undefined | null): boole return Boolean(kind && kind in IMAGE_TOOL_SIDE_PANEL_KIND); } +export function isNodeLayerToolPanelKind(kind: string | undefined | null): boolean { + return Boolean(kind && kind in NODE_LAYER_TOOL_PANEL_KIND); +} + export function isImageToolCropSessionKind(kind: string | undefined | null): boolean { return Boolean(kind && kind in IMAGE_TOOL_CROP_SESSION_KIND); } @@ -500,12 +510,18 @@ const editorSlice = createSlice({ */ removeDocumentNodes(state, action) { if (!state.document) return; - const nodeIds = (action.payload?.nodeIds || []) + const requestedNodeIds = (action.payload?.nodeIds || []) .map((id: unknown) => String(id || '').trim()) .filter(Boolean); const frameIds = (action.payload?.frameIds || []) .map((id: unknown) => String(id || '').trim()) .filter(Boolean); + const frameIdSet = new Set(frameIds); + const frameNodeIds = Object.values(state.document.deltaSetLike || {}) + .filter((node) => frameIdSet.has(String(node?.attrs?.frameId || '').trim())) + .map((node) => String(node?.id || '').trim()) + .filter(Boolean); + const nodeIds = [...new Set([...requestedNodeIds, ...frameNodeIds])]; if (!nodeIds.length && !frameIds.length) return; const ephemeralIds = nodeIds.filter((id: string) => @@ -519,7 +535,7 @@ const editorSlice = createSlice({ let next: SceneDocument | null | undefined = state.document; if (nodeIds.length) next = removeNodesFromDocument(next, nodeIds); if (frameIds.length) { - const idSet = new Set(frameIds); + const idSet = frameIdSet; const frames = (Array.isArray(next.frames) ? next.frames : []).filter( (f) => f && !idSet.has(String(f.id)) ); diff --git a/apps/web/src/store/modules/editorHistory.ts b/apps/web/src/store/modules/editorHistory.ts index ce74bd8a..31d58b71 100644 --- a/apps/web/src/store/modules/editorHistory.ts +++ b/apps/web/src/store/modules/editorHistory.ts @@ -30,7 +30,7 @@ export function isHistoryEntry(x: unknown): x is HistoryEntry { return kind === 'snap' || kind === 'nodes'; } -/** Accept legacy raw-document entries still sitting in session state. */ +/** Accept raw-document entries still sitting in session state. */ export function asHistoryEntry(x: unknown): HistoryEntry { if (isHistoryEntry(x)) return x; return { kind: 'snap', doc: x as SceneDocument }; diff --git a/apps/web/src/styles/fonts.css b/apps/web/src/styles/fonts.css index 8bf30a16..3703a775 100644 --- a/apps/web/src/styles/fonts.css +++ b/apps/web/src/styles/fonts.css @@ -1,4 +1,4 @@ -/* Display — Noto Sans SC (hero Heiti) + Noto Serif / Cormorant (legacy editorial) */ +/* Display — Noto Sans SC (hero Heiti) + Noto Serif / Cormorant (editorial) */ @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,500;0,600;0,700;1,500;1,600;1,700&family=Noto+Sans+SC:wght@400;500;700&family=Noto+Serif+SC:wght@400;600;700&display=swap'); /* 阿里巴巴普惠体 3.0 — jsDelivr CDN (c1-alibaba-puhui-ti) diff --git a/apps/web/src/utils/docsUrl.ts b/apps/web/src/utils/docsUrl.ts index 7e1b8254..0e302d06 100644 --- a/apps/web/src/utils/docsUrl.ts +++ b/apps/web/src/utils/docsUrl.ts @@ -44,7 +44,6 @@ export function docsOrigin(): string { return baked || PROD_DOCS; } -/** @deprecated Prefer docsOrigin() — kept for existing imports. */ export const DOCS_ORIGIN = bakedOrigin() || PROD_DOCS; export function docsUrl(path: string): string { diff --git a/apps/web/src/utils/officialCases.ts b/apps/web/src/utils/officialCases.ts index e5f329d2..485e7277 100644 --- a/apps/web/src/utils/officialCases.ts +++ b/apps/web/src/utils/officialCases.ts @@ -35,7 +35,7 @@ export type OfficialCaseMeta = { coverDocument?: unknown | null; /** Up to 4 cover tiles for list collage. */ thumbnailUrls?: string[] | null; - /** @deprecated first tile — prefer thumbnailUrls */ + /** First tile URL; prefer thumbnailUrls when available. */ thumbnail?: string | null; /** HD PNG panel URLs from admin approve — left-rail images. */ panelUrls?: Array<{ id: string; name?: string; url: string }> | null; diff --git a/apps/web/src/utils/projectThumb.ts b/apps/web/src/utils/projectThumb.ts index a8f11450..6076cf6c 100644 --- a/apps/web/src/utils/projectThumb.ts +++ b/apps/web/src/utils/projectThumb.ts @@ -58,7 +58,7 @@ export function toBrowserThumbUrl(url: string | null | undefined): string { } /** - * Optional cache-bust for legacy fixed keys (`thumb.webp`). + * Optional cache-bust for fixed keys (`thumb.webp`). * New uploads use `thumb-{ms}.webp` — return as-is (no `?v=` clutter). */ export function withThumbCacheBust( diff --git a/apps/web/src/utils/wallet.ts b/apps/web/src/utils/wallet.ts index ebd7861f..e888a814 100644 --- a/apps/web/src/utils/wallet.ts +++ b/apps/web/src/utils/wallet.ts @@ -8,7 +8,7 @@ export type PayMethod = 'wechat' | 'alipay' | 'card'; -/** free → plus → pro (3 monthly tiers; ultra kept for legacy accounts). */ +/** free → plus → pro (3 monthly tiers; ultra kept for existing accounts). */ export type PlanId = 'free' | 'plus' | 'pro' | 'ultra'; export type LedgerKind = 'redeem' | 'spend' | 'recharge' | 'plan'; @@ -35,10 +35,6 @@ export type PlanDef = { priceCny: number; /** Unified 积分 granted each billing month. */ creditsIncluded: number; - /** - * @deprecated Same as creditsIncluded (unified wallet). - */ - imageCreditsIncluded?: number; /** * Free-tier design runs per calendar day (server-enforced when balance < hold). */ @@ -71,7 +67,6 @@ export const PLAN_CATALOG: Record = { id: 'free', priceCny: 0, creditsIncluded: 0, - imageCreditsIncluded: 0, dailyRuns: 1, }, /** ¥49 — 340 积分 / mo(与 Intelligence commercial + 扣费锚点一致). */ @@ -79,34 +74,31 @@ export const PLAN_CATALOG: Record = { id: 'plus', priceCny: 49, creditsIncluded: 340, - imageCreditsIncluded: 340, recommended: true, }, pro: { id: 'pro', priceCny: 149, creditsIncluded: 1030, - imageCreditsIncluded: 1030, }, ultra: { id: 'ultra', priceCny: 499, creditsIncluded: 4000, - imageCreditsIncluded: 4000, }, }; /** Plans shown on the membership picker (3 tiers). */ export const PLAN_ORDER: PlanId[] = ['free', 'plus', 'pro']; -/** Highest plan currently sold in PLAN_ORDER (Pro). Ultra is legacy-only. */ +/** Highest plan currently sold in PLAN_ORDER (Pro). */ export function isTopOfferedPlan(id: PlanId | string | null | undefined): boolean { const pid = normalizePlanId(id); const top = PLAN_ORDER[PLAN_ORDER.length - 1] || 'pro'; return pid === top || pid === 'ultra'; } -/** Map legacy ids → current catalog. */ +/** Map historical ids → current catalog. */ export function normalizePlanId(raw: unknown): PlanId { if (raw === 'free' || raw === 'plus' || raw === 'pro' || raw === 'ultra') return raw; if (raw === 'hobby') return 'free'; diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.yml index 03d769e7..ecdc8abe 100644 --- a/docker-compose.ghcr.yml +++ b/docker-compose.ghcr.yml @@ -1,7 +1,7 @@ # Optional override: pull pre-built images from GHCR instead of local --build. # Requires Docker Compose v2.24+ (`!reset` to clear `build:` from the base file). # -# export RECOMBYN_TAG=v0.1.0 +# # Put RECOMBYN_TAG in .env (repo root), e.g. RECOMBYN_TAG=v0.1.0 # docker compose -f docker-compose.yml -f docker-compose.ghcr.yml pull # docker compose -f docker-compose.yml -f docker-compose.ghcr.yml up -d # diff --git a/docs/adr/0002-canvas-rcb-runtime.md b/docs/adr/0002-canvas-rcb-runtime.md index 45c13fe2..7a72c0b6 100644 --- a/docs/adr/0002-canvas-rcb-runtime.md +++ b/docs/adr/0002-canvas-rcb-runtime.md @@ -11,7 +11,7 @@ The product needs an infinite multi-artboard canvas with LOD, freehand ink, medi Own a **Resume Canvas Backend (RCB)** runtime under `apps/web/src/components/rcb` + `editor/canvas`, with document model in `rcb/scene` / `packages/scene-schema`. Redux (`store/modules/editor.ts`) is the live document owner; SvgCanvas hosts tools and media overlays. -**Runtime fact layer** (paint / hit / chrome) is specified in [ADR 0027](./0027-canvas-layered-runtime.md): `SceneDocument` + `CameraTransform` + spatial index — SVG is export/compat and transitional live paint, not the interaction substrate. +**Runtime fact layer** (paint / hit / chrome) is specified in [ADR 0027](./0027-canvas-layered-runtime.md): `SceneDocument` + `CameraTransform` + spatial index — SVG is export and transitional live paint, not the interaction substrate. Detailed behavior: [docs/canvas-architecture.md](../canvas-architecture.md). diff --git a/docs/adr/0013-skill-extensions.md b/docs/adr/0013-skill-extensions.md index 4bf5f4e8..61099e9b 100644 --- a/docs/adr/0013-skill-extensions.md +++ b/docs/adr/0013-skill-extensions.md @@ -11,7 +11,7 @@ We want third-party / private-deploy **extensions** without a full plugin platfo 1. **Phase A = Skill playbooks only.** A pack teaches the agent; it does **not** execute `handler.py` yet. 2. **Two product roots only** (later wins on duplicate `skill_key`): - - `apps/api/seeds/design_skills` — shipped / first-party + - `skills/foundation` + `skills/domains` — shipped / first-party - `/plugins/skills` — private / self-host mount - Extra dirs from `DESIGN_SKILLS_PLUGIN_DIRS` (comma-separated) 3. **`.agents/skills` is out of product scan** — Cursor/IDE agents only; do not place Design Agent packs there. diff --git a/docs/adr/0015-skill-ops-runner.md b/docs/adr/0015-skill-ops-runner.md index da5ead54..2a9632fd 100644 --- a/docs/adr/0015-skill-ops-runner.md +++ b/docs/adr/0015-skill-ops-runner.md @@ -12,7 +12,7 @@ Skill packs (ADR 0013) are playbooks: the LLM Paint stage emits `tool_ops`. Auth 1. **Opt-in runner** (`DESIGN_SKILL_OPS_RUNNER`, default off). When on, Paint tries a pack `handler.py` **before** the LLM structured call. 2. **Contract:** `def run(ctx: dict, payload: dict) -> list[dict]` only. Return value must be a list of op dicts. 3. **Isolation:** subprocess + JSON stdin/stdout + timeout (`DESIGN_SKILL_OPS_RUNNER_TIMEOUT_SEC`). Bad handlers do not crash the API worker. -4. **Trust boundary:** only `handler.py` under known pack roots (`seeds/design_skills`, `plugins/skills`, `DESIGN_SKILLS_PLUGIN_DIRS`). No Admin-zip / remote code in this phase. +4. **Trust boundary:** only `handler.py` under known pack roots (`skills/foundation`, `skills/domains`, `plugins/skills`, `DESIGN_SKILLS_PLUGIN_DIRS`). No Admin-zip / remote code in this phase. 5. **Always re-validate** via existing `validate_ops` (preferred_tools / output_schema / canvas contract). Empty or invalid ops → fall through to LLM paint. 6. **Sample:** `plugins/skills/festival_poster/handler.py`. diff --git a/docs/adr/0016-recombyn-plugin-pack.md b/docs/adr/0016-recombyn-plugin-pack.md index 4455ad6b..a65cfed7 100644 --- a/docs/adr/0016-recombyn-plugin-pack.md +++ b/docs/adr/0016-recombyn-plugin-pack.md @@ -16,7 +16,7 @@ Skills and canvas plugins are folders today. Distributors need a single uploadab - ``install``: ``user`` (default for skill) | ``disk`` (required for canvas) - ``permissions``: documentation / future ACL list 3. **Install paths:** - - ``skill`` + ``user`` → existing end-user skill upsert (same as legacy zip) + - ``skill`` + ``user`` → existing end-user skill upsert - ``skill|canvas`` + ``disk`` → write under ``/plugins/{skills|canvas}//`` when ``DESIGN_PLUGIN_DISK_INSTALL=true`` 4. **Optional signature:** ``plugin.sig`` = HMAC-SHA256 hex of a canonical digest. Required only when ``DESIGN_PLUGIN_HMAC_SECRET`` is set. 5. **APIs:** ``POST /api/v1/design/plugins/install``; ``POST /api/v1/design/skills/import`` auto-detects branded packs. diff --git a/docs/adr/0018-public-skills-catalog.md b/docs/adr/0018-public-skills-catalog.md index 90b26be6..a26e5489 100644 --- a/docs/adr/0018-public-skills-catalog.md +++ b/docs/adr/0018-public-skills-catalog.md @@ -13,7 +13,7 @@ Shipped Design Agent skills lived under `apps/api/seeds/design_skills`. The open - `skills/foundation/` — core craft packs - `skills/domains/` — surface / deliverable packs 2. **Private / self-host overrides:** `plugins/skills/` (+ `DESIGN_SKILLS_PLUGIN_DIRS`) — later wins on `skill_key`. -3. **Legacy:** `apps/api/seeds/design_skills` remains scannable for empty mounts / migration, but is not the primary catalog. +3. **`apps/api/seeds/design_skills` is unused** (empty leftover path; not scanned). 4. **Documentation rule:** This repo documents pack layout and open methodology only. Do not describe proprietary prompt inventories or closed skill backends here. ## Consequences diff --git a/docs/adr/0026-task-centric-billing.md b/docs/adr/0026-task-centric-billing.md index ae78e500..9921a039 100644 --- a/docs/adr/0026-task-centric-billing.md +++ b/docs/adr/0026-task-centric-billing.md @@ -70,7 +70,7 @@ token SKUs. Self-host default: TaskPricing + CreditPolicy floor. Cloud hosts may supply a quote endpoint; open Runtime never requires proprietary pricing code. -### What is deprecated as product truth +### What is no longer product truth Using `15000 tokens = 1 credit` as the **primary** user SKU. Token meters remain valid usage inputs; they are not the Design Agent sell unit. @@ -80,7 +80,7 @@ valid usage inputs; they are not the Design Agent sell unit. - Runtime estimates/authorizes from `TaskPricingSchema` (+ meters), not token÷15000 alone. - Protocol pin: **0.1.3+**. - Capture prefers an optional host quote (`credits_to_charge`); otherwise OSS - TaskPricing / legacy hybrid / BYOK agent fee. + TaskPricing / BYOK agent fee. - `default_oss_task_pricing_catalog()` is the shared authorize floor (`packages/protocol/recombyn_protocol/billing/task_pricing.py`). - Public docs and ADRs do not describe host markup formulas or private services. diff --git a/docs/adr/0027-canvas-layered-runtime.md b/docs/adr/0027-canvas-layered-runtime.md index 6288dab5..45242a65 100644 --- a/docs/adr/0027-canvas-layered-runtime.md +++ b/docs/adr/0027-canvas-layered-runtime.md @@ -21,7 +21,7 @@ Treat the editor runtime as four facts (**this is the product architecture — d 1. **`SceneDocument`** — unique document source of truth (Redux / collab patches write here). 2. **`CameraTransform`** — single pan/zoom matrix; only `worldToScreen` / `screenToWorld` / `screenDeltaToWorldDelta` on hot paths. No DOM “correction” of coordinates during gestures. 3. **Layered render** — current committed ink remains in per-node SVG hosts; Canvas2D is used for the grid and eligible LOD proxies. Media `foreignObject`, selection, guides, and drawing previews share the SVG camera group; only true screen UI stays in the HTML overlay. WebGL is a future backend, not part of the current runtime. -4. **Independent hit** — root pointer capture → chrome hit → spatial index coarse → precise geometry. `sceneToSvg` stays an **export / compat** path, not the live paint core. +4. **Independent hit** — root pointer capture → chrome hit → spatial index coarse → precise geometry. `sceneToSvg` stays an **export** path, not the live paint core. SVG is not the editor runtime fact layer. Fact layer = `SceneDocument` + `CameraTransform` + `SceneSpatialRuntime`. diff --git a/docs/desktop.md b/docs/desktop.md index d9f19802..d250daef 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -17,7 +17,7 @@ You can run Recombyn as a desktop app (Tauri v2). Two flavors: **Local** (bundle **Billing UI:** Local flavor hides plans / redeem / upgrade (no cloud account switch in-app — use the Cloud desktop build for that). -**Models:** Local does **not** expose the platform LLM catalog (no Seedream / OpenRouter entries for end users). Add your own OpenAI-compatible providers + API keys under Agent settings (BYOK). Wallet holds are skipped. +**Models:** Local does **not** expose the platform LLM catalog (no Seedream / OpenRouter entries for end users). Add your own OpenAI-style providers + API keys under Agent settings (BYOK). Wallet holds are skipped. ## Prerequisites diff --git a/docs/import-pipeline.md b/docs/import-pipeline.md index 62d7bf0d..80e390b2 100644 --- a/docs/import-pipeline.md +++ b/docs/import-pipeline.md @@ -26,7 +26,7 @@ Coordinates are scaled to `SCENE_TARGET_WIDTH` (default 794) before writing Scen ## Stage 3: object storage + frontend async import -### S3-compatible storage +### S3-style storage Local disk by default. When enabled, page images upload via boto3 (Aliyun OSS, Tencent COS, MinIO, AWS S3): diff --git a/docs/quality-gates.md b/docs/quality-gates.md index 5bfd4832..693ad456 100644 --- a/docs/quality-gates.md +++ b/docs/quality-gates.md @@ -107,8 +107,6 @@ View in Prometheus **Alerts**. Alertmanager listens on `:9093` (compose profile | **`ci.yml`** (umbrella) | Every PR / main — `check` + web unit + API unit + web build → **`CI / gate`** | | `release-docker.yml` | `v*.*.*` tags / dispatch — push api/web/collab to GHCR | | `desktop-build.yml` | Dispatch — unsigned Windows Tauri bundle (ADR 0010) | -| `web-tests.yml` | Path-filtered — web unit + stress + coverage | -| `api-tests.yml` | Path-filtered — API unit + integration + cov | | `e2e-tests.yml` | Path-filtered — Playwright | | `perf-k6.yml` | Path-filtered / dispatch — k6 smoke | | `dependency-audit.yml` | Lockfile PRs + weekly — soft audit | diff --git a/docs/roadmap/platform.md b/docs/roadmap/platform.md index e3bc50c6..939475b7 100644 --- a/docs/roadmap/platform.md +++ b/docs/roadmap/platform.md @@ -39,7 +39,7 @@ One FastAPI app with domain modules, plus the collab WebSocket process: | AI 模型入口 | In-process façade (`get_llm_endpoint` / `build_chat_model`) | | 异步任务 | Celery worker sharing the API codebase (hydrate / export / image) | | 协同 | `apps/collab` WebSocket process | -| 扩展(Skill) | File packs: `seeds/design_skills` + `plugins/skills` ([ADR 0013](../adr/0013-skill-extensions.md)) | +| 扩展(Skill) | File packs: `skills/foundation|domains` + `plugins/skills` ([ADR 0013](../adr/0013-skill-extensions.md)) | | 扩展(Canvas) | Toolbar plugins: `plugins/canvas` ([ADR 0014](../adr/0014-canvas-plugins.md)) | → See [ADR 0004](../adr/0004-modular-monolith-first.md). @@ -59,7 +59,7 @@ One FastAPI app with domain modules, plus the collab WebSocket process: | 关系库 | SQLite / MySQL via settings | Document HA as ops guide; shard only with metrics | | 任务与协同缓存 | Job store + collab wait | Cache hot project meta; no premature cluster | | 协同日志独立 | Collab room vs project DB | ADR when splitting durable collab persistence | -| 对象存储 | S3-compatible hooks | Default path for uploads in prod compose | +| 对象存储 | S3-style hooks | Default path for uploads in prod compose | | 向量库检索 | Optional memory extra | Keep optional; not core path | | 配置中心 | env / Settings | Stay env-based until multi-cluster | diff --git a/docs/self-hosting.md b/docs/self-hosting.md index c1f26f69..73d1509d 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -225,8 +225,8 @@ User turn | Namespace | Source | Notes | |-----------|--------|--------| -| `core` | Legacy `source=seed` only (not shipped) | Prefer file packs; bare keys stay BC aliases | -| `ext` | **`skills/foundation|domains`** + `plugins/skills/` (+ legacy `seeds/design_skills`) | Same canonical layout; `.agents/skills` is IDE-only | +| `core` | File packs under `skills/foundation` | Bare keys; prefer file packs | +| `ext` | **`skills/foundation|domains`** + `plugins/skills/` | Same canonical layout; `.agents/skills` is IDE-only | | `user` | Admin API | Always `user.`; cannot claim core keys | Env: `DESIGN_SKILLS_HOT_RELOAD` (default true), `DESIGN_SKILLS_HOT_RELOAD_INTERVAL_SEC`, `DESIGN_SKILLS_PLUGIN_DIRS` (extra roots). Manual: Admin `POST /api/v1/admin/design/skills/resync`. @@ -253,7 +253,7 @@ Do not duplicate craft into `paint_system` / `react_system`. Brush / Lottie → ## BYOK / secrets -User OpenAI-compatible endpoints (custom LLM providers) store API keys encrypted (AES-GCM). Set a dedicated `BYOK_AES_KEY` (32+ chars) in production; empty falls back to a derive-from-`CARD_KEY_SALT` path for local only. +User OpenAI-style endpoints (custom LLM providers) store API keys encrypted (AES-GCM). Set a dedicated `BYOK_AES_KEY` (32+ chars) in production; empty falls back to a derive-from-`CARD_KEY_SALT` path for local only. ## Quick path (Docker) diff --git a/docs/skill-extensions.md b/docs/skill-extensions.md index dadddc1b..cf072ff4 100644 --- a/docs/skill-extensions.md +++ b/docs/skill-extensions.md @@ -9,7 +9,6 @@ You can teach the Design Agent a new category of work with a Skill pack — same | `skills/foundation//` | Shipped core craft (open) | | `skills/domains//` | Shipped surfaces / deliverables (open) | | `plugins/skills//` | Private / self-host extensions (Compose-mounted) | -| `apps/api/seeds/design_skills//` | Legacy empty shim (still scanned) | Do **not** put product skills in `.agents/skills/` — that tree is for Cursor/IDE coding agents only. diff --git a/docs/stress-baselines.md b/docs/stress-baselines.md index e52025d1..79d08ab5 100644 --- a/docs/stress-baselines.md +++ b/docs/stress-baselines.md @@ -8,7 +8,7 @@ How to capture a performance baseline (canvas, API, collab, Agent). Tools alread |---------|---------|------------------| | Canvas store + E2E stress | `npm run test:canvas:stress` | Console + Playwright/HTML; optional JSON under `e2e/tests/*.results.json` (local, gitignored if untracked) | | Canvas deep / tools | `npm run test:canvas:deep` / `test:canvas:tools` | Same | -| Vitest canvas stress | `npm run test:stress --workspace=apps/web` | Vitest (also in `web-tests.yml`) | +| Vitest canvas stress | `npm run test:stress --workspace=apps/web` | Vitest (local) | | API k6 smoke | `npm run perf:k6:smoke` | k6 summary; CI: `perf-k6.yml` | | API CRUD load | `PERF_TOKEN=… npm run perf:k6:api` | k6 | | Collab WS | `COLLAB_WS_URL=ws://127.0.0.1:1234 npm run perf:k6:collab` | k6 | diff --git a/packages/contracts/generated/api/orpc.gen.ts b/packages/contracts/generated/api/orpc.gen.ts index 3f4fad1b..5e0c68e8 100644 --- a/packages/contracts/generated/api/orpc.gen.ts +++ b/packages/contracts/generated/api/orpc.gen.ts @@ -59,10 +59,10 @@ export const authEmailSendCode = oc.route({ /** * Email Activate * - * Consume one-time /activate/{{id}} link → session (legacy magic-link mails). + * Consume one-time /activate/{{id}} link → session (email magic-link mails). */ export const authEmailActivate = oc.route({ - description: 'Consume one-time /activate/{{id}} link → session (legacy magic-link mails).', + description: 'Consume one-time /activate/{{id}} link → session (email magic-link mails).', inputStructure: 'detailed', method: 'POST', operationId: 'auth-email_activate', @@ -826,10 +826,10 @@ export const adminAdminDesignDecisionLogsClear = oc.route({ /** * Admin Design Stage Reviews * - * Historical stage ratings (legacy training runs). + * Historical stage ratings (training runs). */ export const adminAdminDesignStageReviews = oc.route({ - description: 'Historical stage ratings (legacy training runs).', + description: 'Historical stage ratings (training runs).', inputStructure: 'detailed', method: 'GET', operationId: 'admin-admin_design_stage_reviews', @@ -1418,12 +1418,12 @@ export const plazaPlazaMine = oc.route({ * Plaza Feed * * Public plaza feed (no login required). - * tab=recommended|latest (following deprecated — use authorIds to filter by creator) + * tab=recommended|latest (use authorIds to filter by creator) * category=optional category filter (website|mobile|image|poster|video) * authorIds=comma-separated user ids to filter works by creator. */ export const plazaPlazaFeed = oc.route({ - description: 'Public plaza feed (no login required).\ntab=recommended|latest (following deprecated — use authorIds to filter by creator)\ncategory=optional category filter (website|mobile|image|poster|video)\nauthorIds=comma-separated user ids to filter works by creator.', + description: 'Public plaza feed (no login required).\ntab=recommended|latest (use authorIds to filter by creator)\ncategory=optional category filter (website|mobile|image|poster|video)\nauthorIds=comma-separated user ids to filter works by creator.', inputStructure: 'detailed', method: 'GET', operationId: 'plaza-plaza_feed', diff --git a/packages/eval-framework/src/compare.mjs b/packages/eval-framework/src/compare.mjs index a495b3bd..dc4ea0d1 100644 --- a/packages/eval-framework/src/compare.mjs +++ b/packages/eval-framework/src/compare.mjs @@ -49,12 +49,11 @@ export function extractTasks(doc) { return out; } -/** Resolve skill pack version from open `skills/` (+ legacy seeds). */ +/** Resolve skill pack version from open `skills/`. */ export function loadSkillVersions(repoRoot, keys = ['poster_craft', 'landing_page', 'dashboard_ui', 'image_gen']) { const roots = [ path.join(repoRoot, 'skills', 'foundation'), path.join(repoRoot, 'skills', 'domains'), - path.join(repoRoot, 'apps', 'api', 'seeds', 'design_skills'), ]; const versions = {}; for (const key of keys) { diff --git a/packages/intelligence-client/README.md b/packages/intelligence-client/README.md index 59e2cde4..dd2e9a8b 100644 --- a/packages/intelligence-client/README.md +++ b/packages/intelligence-client/README.md @@ -7,7 +7,4 @@ # swarm_direction, simulate, counterfactual, review, optimize, govern, # autonomous_plan, autonomous_sync, retrieve_memory, write_principle # -# Legacy aliases (Client): candidates, swarm, gate_governance, -# plan_autonomous, sync_autonomous -# # Do not document proprietary backends, private datasets, or closed prompts here. diff --git a/packages/intelligence-client/recombyn_intelligence_client/client.py b/packages/intelligence-client/recombyn_intelligence_client/client.py index fea29537..fd305f1a 100644 --- a/packages/intelligence-client/recombyn_intelligence_client/client.py +++ b/packages/intelligence-client/recombyn_intelligence_client/client.py @@ -10,8 +10,7 @@ class DesignIntelligenceClient: """Single entry used by Design Runtime. Does not embed provider logic. - Stable method names are the contract. Legacy aliases keep older call sites - working without Kernel rewrites. + Stable canonical method names are the only contract. """ def __init__(self, provider: IntelligenceProvider) -> None: @@ -65,20 +64,3 @@ async def retrieve_memory(self, rt: Any) -> dict[str, Any] | None: async def write_principle(self, rt: Any) -> dict[str, Any] | None: return await self._provider.write_principle(rt) - - # ── Legacy aliases (do not use in new Kernel code) ────────────────────── - - async def candidates(self, rt: Any) -> dict[str, Any] | None: - return await self.propose_candidates(rt) - - async def swarm(self, rt: Any) -> dict[str, Any] | None: - return await self.swarm_direction(rt) - - async def gate_governance(self, rt: Any) -> dict[str, Any]: - return await self.govern(rt) - - async def plan_autonomous(self, rt: Any) -> dict[str, Any] | None: - return await self.autonomous_plan(rt) - - async def sync_autonomous(self, rt: Any) -> dict[str, Any] | None: - return await self.autonomous_sync(rt) diff --git a/packages/intelligence-client/recombyn_intelligence_client/protocol.py b/packages/intelligence-client/recombyn_intelligence_client/protocol.py index 8cce08ee..c94d7aa8 100644 --- a/packages/intelligence-client/recombyn_intelligence_client/protocol.py +++ b/packages/intelligence-client/recombyn_intelligence_client/protocol.py @@ -5,10 +5,6 @@ swarm_direction, simulate, counterfactual, review, optimize, govern, autonomous_plan, autonomous_sync, retrieve_memory, write_principle -Legacy aliases remain on the Client for one release cycle: - candidates→propose_candidates, swarm→swarm_direction, - gate_governance→govern, plan_autonomous→autonomous_plan, - sync_autonomous→autonomous_sync """ from __future__ import annotations diff --git a/packages/intelligence-client/recombyn_intelligence_client/remote.py b/packages/intelligence-client/recombyn_intelligence_client/remote.py index ff4c0e8b..8e76cd95 100644 --- a/packages/intelligence-client/recombyn_intelligence_client/remote.py +++ b/packages/intelligence-client/recombyn_intelligence_client/remote.py @@ -7,11 +7,12 @@ from __future__ import annotations import logging +import asyncio +import time from collections.abc import Awaitable, Callable from typing import Any import httpx -from recombyn_protocol import INTELLIGENCE_METHOD_ALIASES from recombyn_runtime import build_intelligence_request, remote_result_usable _log = logging.getLogger("recombyn_intelligence_client.remote") @@ -20,8 +21,7 @@ def _wire_method(name: str) -> str: - key = str(name or "").strip() - return INTELLIGENCE_METHOD_ALIASES.get(key, key) + return str(name or "").strip() class RemoteIntelligenceProvider: @@ -41,6 +41,30 @@ def __init__( self._timeout = float(timeout_sec or 30.0) self._fallback = fallback self._apply = apply_result + self._client: httpx.AsyncClient | None = None + self._client_lock = asyncio.Lock() + self._circuit_open_until = 0.0 + self._failure_count = 0 + self._dedupe: dict[tuple[str, str, str], dict[str, Any]] = {} + + async def _http_client(self) -> httpx.AsyncClient: + if self._client is None or self._client.is_closed: + async with self._client_lock: + if self._client is None or self._client.is_closed: + self._client = httpx.AsyncClient(timeout=self._timeout) + return self._client + + def _circuit_open(self) -> bool: + return time.monotonic() < self._circuit_open_until + + def _mark_failure(self) -> None: + self._failure_count += 1 + if self._failure_count >= 1: + self._circuit_open_until = time.monotonic() + min(30.0, self._timeout) + + def _mark_success(self) -> None: + self._failure_count = 0 + self._circuit_open_until = 0.0 def _headers(self) -> dict[str, str]: headers = {"Content-Type": "application/json", "Accept": "application/json"} @@ -51,35 +75,56 @@ def _headers(self) -> dict[str, str]: async def _post(self, method: str, rt: Any) -> dict[str, Any] | None: if not self._base: return None + if self._circuit_open(): + return None wire = _wire_method(method) url = f"{self._base}/v1/{wire}" payload = build_intelligence_request(wire, rt) try: - async with httpx.AsyncClient(timeout=self._timeout) as client: - res = await client.post(url, json=payload, headers=self._headers()) - if res.status_code >= 400: - _log.warning("intelligence remote %s status=%s", wire, res.status_code) - return None - data = res.json() - if not isinstance(data, dict): - return None - if not remote_result_usable(wire, data): - return None - return data + client = await self._http_client() + res = await client.post(url, json=payload, headers=self._headers()) + if res.status_code >= 400: + self._mark_failure() + _log.warning("intelligence remote %s status=%s", wire, res.status_code) + return None + data = res.json() + if not isinstance(data, dict) or not remote_result_usable(wire, data): + self._mark_failure() + return None + self._mark_success() + return data except Exception: + self._mark_failure() _log.warning("intelligence remote %s failed", wire, exc_info=True) return None async def _call(self, method: str, rt: Any) -> dict[str, Any] | None: + request = build_intelligence_request(_wire_method(method), rt) + key = ( + str(request.get("run_id") or ""), + _wire_method(method), + str(request.get("input_hash") or ""), + ) + if key[0] and key in self._dedupe: + return self._dedupe[key] remote = await self._post(method, rt) if remote_result_usable(method, remote): if self._apply is not None: - return self._apply(method, rt, remote) - return remote + result = self._apply(method, rt, remote) + else: + result = remote + if key[0] and isinstance(result, dict): + self._dedupe[key] = result + if len(self._dedupe) > 128: + self._dedupe.pop(next(iter(self._dedupe))) + return result if self._fallback is not None: fn = getattr(self._fallback, method, None) if callable(fn): - return await fn(rt) + result = await fn(rt) + if key[0] and isinstance(result, dict): + self._dedupe[key] = result + return result return None async def analyze_reference(self, rt: Any) -> dict[str, Any] | None: @@ -128,21 +173,5 @@ async def retrieve_memory(self, rt: Any) -> dict[str, Any] | None: async def write_principle(self, rt: Any) -> dict[str, Any] | None: return await self._call("write_principle", rt) - async def candidates(self, rt: Any) -> dict[str, Any] | None: - return await self.propose_candidates(rt) - - async def swarm(self, rt: Any) -> dict[str, Any] | None: - return await self.swarm_direction(rt) - - async def gate_governance(self, rt: Any) -> dict[str, Any]: - return await self.govern(rt) - - async def plan_autonomous(self, rt: Any) -> dict[str, Any] | None: - return await self.autonomous_plan(rt) - - async def sync_autonomous(self, rt: Any) -> dict[str, Any] | None: - return await self.autonomous_sync(rt) - - # Satisfy type checkers that treat unused Awaitable _ = Awaitable diff --git a/packages/plugin-sdk/recombyn_plugin_sdk/__init__.py b/packages/plugin-sdk/recombyn_plugin_sdk/__init__.py index f674aeb3..60883d6d 100644 --- a/packages/plugin-sdk/recombyn_plugin_sdk/__init__.py +++ b/packages/plugin-sdk/recombyn_plugin_sdk/__init__.py @@ -3,7 +3,6 @@ from __future__ import annotations from recombyn_plugin_sdk.manifest import ( - FORMAT, FORMAT_NAME, INSTALL_TARGETS, KINDS, @@ -14,7 +13,6 @@ ) __all__ = [ - "FORMAT", "FORMAT_NAME", "INSTALL_TARGETS", "KINDS", diff --git a/packages/plugin-sdk/recombyn_plugin_sdk/manifest.py b/packages/plugin-sdk/recombyn_plugin_sdk/manifest.py index f4572f45..8734c56e 100644 --- a/packages/plugin-sdk/recombyn_plugin_sdk/manifest.py +++ b/packages/plugin-sdk/recombyn_plugin_sdk/manifest.py @@ -6,7 +6,6 @@ from typing import Any FORMAT_NAME = "recombyn-plugin" -FORMAT = FORMAT_NAME # alias PLUGIN_JSON = "plugin.json" PLUGIN_SIG = "plugin.sig" KINDS = frozenset({"skill", "canvas"}) diff --git a/packages/protocol/recombyn_protocol/__init__.py b/packages/protocol/recombyn_protocol/__init__.py index 52141d5d..0b3d0693 100644 --- a/packages/protocol/recombyn_protocol/__init__.py +++ b/packages/protocol/recombyn_protocol/__init__.py @@ -17,7 +17,6 @@ BillingEventKind, BillingEventSchema, BillingMeterSchema, - BillingProviderProtocol, BudgetCheckSchema, BudgetPolicySchema, BudgetSchema, @@ -81,7 +80,6 @@ from recombyn_protocol.intelligence import ( AUTONOMOUS_HOPS, GOVERNANCE_LANES, - INTELLIGENCE_METHOD_ALIASES, INTELLIGENCE_METHODS, INTELLIGENCE_REQUEST_FIELDS, TOURNAMENT_DIMS, @@ -90,7 +88,6 @@ DesignGovernanceSchema, GovernanceLaneResultSchema, intelligence_wire_methods, - normalize_intelligence_method, remote_result_usable, ) from recombyn_protocol.paint import ( @@ -141,7 +138,6 @@ "DESIGN_BRIEF_P0_FIELDS", "DESIGN_BRIEF_P1_FIELDS", "GOVERNANCE_LANES", - "INTELLIGENCE_METHOD_ALIASES", "INTELLIGENCE_METHODS", "INTELLIGENCE_REQUEST_FIELDS", "MULTI_REVIEW_LANES", @@ -150,7 +146,6 @@ "BillingEventKind", "BillingEventSchema", "BillingMeterSchema", - "BillingProviderProtocol", "BudgetCheckSchema", "BudgetPolicySchema", "BudgetSchema", @@ -252,7 +247,6 @@ "intelligence_wire_methods", "merge_nested_op_args", "new_design_transaction", - "normalize_intelligence_method", "paint_op_name", "remote_result_usable", "resolve_transaction_phase", diff --git a/packages/protocol/recombyn_protocol/billing/__init__.py b/packages/protocol/recombyn_protocol/billing/__init__.py index 868cb0ca..dfd16038 100644 --- a/packages/protocol/recombyn_protocol/billing/__init__.py +++ b/packages/protocol/recombyn_protocol/billing/__init__.py @@ -22,7 +22,6 @@ CreditTransactionSchema, ) from recombyn_protocol.billing.lifecycle import ( - BILLING_LIFECYCLE_ALIASES, BILLING_LIFECYCLE_DOC, BILLING_LIFECYCLE_STAGES, BILLING_SETTLE_ACTIONS, @@ -50,7 +49,6 @@ resolve_pricing, ) from recombyn_protocol.billing.provider import ( - BillingProviderProtocol, ProviderBillingAdapter, ProviderSchema, ) @@ -64,7 +62,6 @@ from recombyn_protocol.billing.usage import ProviderUsageSchema, UsageEventSchema, UsageStatus __all__ = [ - "BILLING_LIFECYCLE_ALIASES", "BILLING_LIFECYCLE_DOC", "BILLING_LIFECYCLE_STAGES", "BILLING_SETTLE_ACTIONS", @@ -73,7 +70,6 @@ "BillingEventKind", "BillingEventSchema", "BillingMeterSchema", - "BillingProviderProtocol", "BudgetCheckSchema", "BudgetDecision", "BudgetPolicySchema", diff --git a/packages/protocol/recombyn_protocol/billing/cost.py b/packages/protocol/recombyn_protocol/billing/cost.py index e943cd4d..903854bd 100644 --- a/packages/protocol/recombyn_protocol/billing/cost.py +++ b/packages/protocol/recombyn_protocol/billing/cost.py @@ -87,15 +87,7 @@ class TaskCostSchema(BaseModel): currency: str = "USD" credits_estimated_low: int | None = None credits_estimated_high: int | None = None - credits_authorized: int = Field( - default=0, - description="Alias of reserved hold (Stripe authorize)", - ) credits_reserved: int = 0 - credits_captured: int = Field( - default=0, - description="Alias of charged (Stripe capture)", - ) credits_charged: int = 0 credits_refunded: int = 0 credits_released: int = 0 @@ -107,20 +99,8 @@ class TaskCostSchema(BaseModel): breakdown: CostBreakdownSchema = Field(default_factory=CostBreakdownSchema) status: str = Field( default="open", - description="open | authorized|reserved | settling | settled | cancelled", + description="open | reserved | settling | settled | cancelled", ) meta: dict[str, Any] = Field(default_factory=dict) model_config = {"extra": "allow"} - - @model_validator(mode="after") - def _sync_auth_capture_aliases(self) -> TaskCostSchema: - if self.credits_authorized and not self.credits_reserved: - self.credits_reserved = int(self.credits_authorized) - elif self.credits_reserved and not self.credits_authorized: - self.credits_authorized = int(self.credits_reserved) - if self.credits_captured and not self.credits_charged: - self.credits_charged = int(self.credits_captured) - elif self.credits_charged and not self.credits_captured: - self.credits_captured = int(self.credits_charged) - return self diff --git a/packages/protocol/recombyn_protocol/billing/events.py b/packages/protocol/recombyn_protocol/billing/events.py index 03a9b4b3..54d5147d 100644 --- a/packages/protocol/recombyn_protocol/billing/events.py +++ b/packages/protocol/recombyn_protocol/billing/events.py @@ -9,9 +9,9 @@ BillingEventKind = Literal[ "estimate", "authorize", - "reserve", # legacy alias of authorize + "reserve", "capture", - "charge", # legacy alias of capture + "charge", "release", "refund", "topup", @@ -33,9 +33,7 @@ class BillingEventSchema(BaseModel): user_id: str = "" task_id: str = "" credits_delta: int = 0 - credits_authorized: int | None = None credits_reserved: int | None = None - credits_captured: int | None = None credits_charged: int | None = None credits_released: int | None = None estimate_low: int | None = None diff --git a/packages/protocol/recombyn_protocol/billing/lifecycle.py b/packages/protocol/recombyn_protocol/billing/lifecycle.py index f55114e4..d95d3225 100644 --- a/packages/protocol/recombyn_protocol/billing/lifecycle.py +++ b/packages/protocol/recombyn_protocol/billing/lifecycle.py @@ -1,28 +1,16 @@ -"""Billing lifecycle — estimate → authorize → execute → capture/release. - -Stripe-shaped aliases (authorize/capture/refund) map onto wallet -reserve/charge/release. Prefer the Stripe names in new product code. -""" +"""Billing lifecycle — estimate → authorize → execute → capture/release.""" from __future__ import annotations -# Open state machine for task billing (wallet side). BILLING_LIFECYCLE_STAGES: tuple[str, ...] = ( "estimate", - "authorize", # == reserve + "authorize", "execute", "settle", ) -# Legacy aliases still accepted by Runtime / wallets. -BILLING_LIFECYCLE_ALIASES: dict[str, str] = { - "reserve": "authorize", - "charge": "capture", -} - -# Terminal settle actions (after ACTUAL USAGE). BILLING_SETTLE_ACTIONS: tuple[str, ...] = ( - "capture", # == charge + "capture", "release", "refund", ) @@ -30,14 +18,14 @@ BILLING_LIFECYCLE_DOC = """ ESTIMATE (TaskPricing + meters → credit band) ↓ -AUTHORIZE (hold estimate_high credits; alias: reserve) +AUTHORIZE (hold estimate_high credits) ↓ EXECUTE (Agent Runtime emits UsageEvents / meters) ↓ ACTUAL USAGE (host accounting → credits_to_charge) ↓ SETTLE - ├── CAPTURE (credits_captured = actual; alias: charge) - ├── RELEASE (authorized - captured) + ├── CAPTURE (credits_charged = actual) + ├── RELEASE (reserved - charged) └── REFUND (post-settle clawback) """.strip() diff --git a/packages/protocol/recombyn_protocol/billing/provider.py b/packages/protocol/recombyn_protocol/billing/provider.py index 9782a299..e0604830 100644 --- a/packages/protocol/recombyn_protocol/billing/provider.py +++ b/packages/protocol/recombyn_protocol/billing/provider.py @@ -65,7 +65,3 @@ def check_budget( policy: BudgetPolicySchema, usage: ProviderUsageSchema | None = None, ) -> BudgetCheckSchema: ... - - -# Back-compat alias -BillingProviderProtocol = ProviderBillingAdapter diff --git a/packages/protocol/recombyn_protocol/intelligence.py b/packages/protocol/recombyn_protocol/intelligence.py index f412f0b6..9db79258 100644 --- a/packages/protocol/recombyn_protocol/intelligence.py +++ b/packages/protocol/recombyn_protocol/intelligence.py @@ -25,15 +25,6 @@ "write_principle", ) -# Wire / legacy aliases → canonical (HTTP adapters may accept either). -INTELLIGENCE_METHOD_ALIASES: dict[str, str] = { - "candidates": "propose_candidates", - "swarm": "swarm_direction", - "gate_governance": "govern", - "plan_autonomous": "autonomous_plan", - "sync_autonomous": "autonomous_sync", -} - # JSON body keys for POST /v1/{method} (RemoteIntelligenceProvider). INTELLIGENCE_REQUEST_FIELDS: tuple[str, ...] = ( "method", @@ -105,15 +96,9 @@ ) -def normalize_intelligence_method(method: str) -> str: - """Map wire / legacy alias → canonical method name.""" - name = str(method or "").strip() - return INTELLIGENCE_METHOD_ALIASES.get(name, name) - - def intelligence_wire_methods() -> frozenset[str]: - """Canonical methods plus accepted HTTP aliases.""" - return frozenset(INTELLIGENCE_METHODS) | frozenset(INTELLIGENCE_METHOD_ALIASES) + """Canonical HTTP methods.""" + return frozenset(INTELLIGENCE_METHODS) def remote_result_usable(method: str, data: dict[str, Any] | None) -> bool: @@ -124,7 +109,7 @@ def remote_result_usable(method: str, data: dict[str, Any] | None) -> bool: """ if not isinstance(data, dict) or not data: return False - name = normalize_intelligence_method(method) + name = str(method or "").strip() if name == "govern": return bool(str(data.get("status") or "").strip()) return any( diff --git a/packages/protocol/recombyn_protocol/paint.py b/packages/protocol/recombyn_protocol/paint.py index 823fb984..ff7217c7 100644 --- a/packages/protocol/recombyn_protocol/paint.py +++ b/packages/protocol/recombyn_protocol/paint.py @@ -6,92 +6,28 @@ from pydantic import BaseModel, Field, field_validator, model_validator -PAINT_OP_META_KEYS = frozenset( - { - "name", - "tool", - "type", - "op", - "op_key", - "opKey", - "args", - "parameters", - "arguments", - "properties", - "props", - "updates", - "params", - "op_id", - "opId", - } -) -PAINT_OP_NEST_ARG_KEYS = ( - "args", - "parameters", - "arguments", - "properties", - "props", - "updates", - "params", -) -PAINT_OP_NAME_ALIASES = ("name", "tool", "op", "op_key", "opKey") -PAINT_CREATE_SHAPE_NAMES = frozenset( - { - "create_shape", - "create_text", - "create_image", - "create_frame", - "update_node", - "delete_nodes", - "delete_frame", - "create_svg", - "create_icon", - } -) - def paint_op_name(d: dict[str, Any]) -> str: - for key in PAINT_OP_NAME_ALIASES: - raw = d.get(key) - if raw is not None and str(raw).strip(): - return str(raw).strip() - type_as_name = str(d.get("type") or "").strip() - if type_as_name in PAINT_CREATE_SHAPE_NAMES: - return type_as_name - return "" + return str(d.get("name") or "").strip() def merge_nested_op_args(d: dict[str, Any]) -> dict[str, Any]: - args: dict[str, Any] = {} - for nest_key in PAINT_OP_NEST_ARG_KEYS: - nested = d.get(nest_key) - if not isinstance(nested, dict): - continue - for nk, nv in nested.items(): - args.setdefault(nk, nv) - if not args: - return {k: v for k, v in d.items() if k not in PAINT_OP_META_KEYS} - for k, v in d.items(): - if k not in PAINT_OP_META_KEYS: - args.setdefault(k, v) - return args + nested = d.get("args") + if isinstance(nested, dict): + return dict(nested) + return {} def coalesce_paint_tool_op(data: Any) -> Any: - """Normalize one tool_op envelope to ``{name, args}`` (accepts parameters).""" + """Normalize one tool_op envelope to ``{name, args}``.""" if not isinstance(data, dict): return data d = dict(data) - name = paint_op_name(d) args = merge_nested_op_args(d) - if ( - name == "create_shape" - and args.get("shapeType") is None - and d.get("type") is not None - and str(d.get("type")) not in {"create_shape"} - ): - args.setdefault("shapeType", d.get("type")) - return {"name": name, "args": args} + op_id = d.get("op_id") + if op_id is not None and str(op_id).strip(): + args["op_id"] = str(op_id).strip() + return {"name": paint_op_name(d), "args": args} class PaintToolOp(BaseModel): @@ -100,7 +36,7 @@ class PaintToolOp(BaseModel): name: str = Field(..., min_length=1) args: dict[str, Any] = Field( default_factory=dict, - description="Canvas op arguments. Prefer key 'args'; 'parameters' also accepted.", + description="Canvas op arguments.", ) model_config = {"extra": "allow"} @@ -118,34 +54,16 @@ class AgentTurnSchema(BaseModel): intent: str = "chat" reply: str = "" tool_ops: list[PaintToolOp] = Field(default_factory=list) - ops: list[PaintToolOp] = Field(default_factory=list) need_tools: list[Any] = Field(default_factory=list) need_skills: list[Any] = Field(default_factory=list) need_subagents: list[Any] = Field(default_factory=list) choices: list[Any] = Field(default_factory=list) apply_choice: str = "" - applyChoice: str = "" choice_ui: Any = None - choiceUi: Any = None - ask_ui: Any = None done: bool | None = None - needTools: list[Any] = Field(default_factory=list) - needSkills: list[Any] = Field(default_factory=list) - needSubagents: list[Any] = Field(default_factory=list) - tools_needed: list[Any] = Field(default_factory=list) model_config = {"extra": "allow"} - @model_validator(mode="before") - @classmethod - def _alias_ops_to_tool_ops(cls, data: Any) -> Any: - if not isinstance(data, dict): - return data - d = dict(data) - if not d.get("tool_ops") and d.get("ops"): - d["tool_ops"] = d.get("ops") - return d - class DecideTurnSchema(BaseModel): """Decision stage only — never emits canvas ops (paint_ops node does that).""" @@ -173,21 +91,9 @@ class PaintOpsSchema(BaseModel): model_config = {"extra": "allow"} - @model_validator(mode="before") - @classmethod - def _alias_ops_to_tool_ops(cls, data: Any) -> Any: - if not isinstance(data, dict): - return data - d = dict(data) - if not d.get("tool_ops") and d.get("ops"): - d["tool_ops"] = d.get("ops") - return d - @field_validator("tool_ops", mode="before") @classmethod def _coerce_tool_ops_list(cls, value: Any) -> Any: if value is None: return [] - if isinstance(value, dict): - return [value] return value diff --git a/packages/protocol/recombyn_protocol/review.py b/packages/protocol/recombyn_protocol/review.py index 4fb57b40..1af5a40f 100644 --- a/packages/protocol/recombyn_protocol/review.py +++ b/packages/protocol/recombyn_protocol/review.py @@ -239,25 +239,6 @@ class ReviewIssueSchema(BaseModel): model_config = {"extra": "allow"} - @model_validator(mode="before") - @classmethod - def _repair_aliases(cls, data: Any) -> Any: - if not isinstance(data, dict): - return data - d = dict(data) - if not str(d.get("area") or "").strip() and d.get("type"): - d["area"] = d.get("type") - if not str(d.get("issue") or "").strip() and d.get("problem"): - d["issue"] = d.get("problem") - if not str(d.get("target") or "").strip() and d.get("nodeId"): - d["target"] = d.get("nodeId") - sev = str(d.get("severity") or "").strip().lower() - if sev in ("high", "medium"): - d["severity"] = "major" - elif sev == "low": - d["severity"] = "minor" - return d - class ReviewLaneSchema(BaseModel): """One of seven Reviewer lanes. Score is this dimension only; Host merges.""" diff --git a/packages/runtime/recombyn_runtime/intelligence.py b/packages/runtime/recombyn_runtime/intelligence.py index 0a095359..1a9dd109 100644 --- a/packages/runtime/recombyn_runtime/intelligence.py +++ b/packages/runtime/recombyn_runtime/intelligence.py @@ -7,6 +7,8 @@ from __future__ import annotations +import hashlib +import json from typing import Any from recombyn_protocol.intelligence import remote_result_usable @@ -48,6 +50,35 @@ def _painted(rt: Any) -> bool: return bool(flag) if flag is not None else False +_METHOD_CONTEXT: dict[str, tuple[str, ...]] = { + "analyze_reference": ("reference_dna", "reference_analyze", "reference_lock"), + "retrieve_memory": ("memory_notes",), + "research": ("reference_dna", "reference_analyze", "memory_notes", "design_research"), + "strategy": ("design_brief", "design_research", "reference_lock"), + "propose_candidates": ("design_brief", "design_research", "design_strategy"), + "tournament": ("design_research", "design_strategy", "design_candidates"), + "swarm_direction": ("design_research", "design_strategy", "design_tournament"), + "simulate": ("design_research", "design_strategy", "design_swarm", "observe_facts"), + "counterfactual": ("design_research", "design_strategy", "design_simulation", "observe_facts"), + "review": ("design_brief", "design_strategy", "design_simulation", "design_counterfactual", "observe_facts", "judge_verdict"), + "optimize": ("design_strategy", "design_simulation", "design_counterfactual"), + "govern": ("design_brief", "design_strategy", "observe_facts", "judge_verdict", "visual_diff"), + "autonomous_plan": ("design_brief",), + "autonomous_sync": ("design_brief", "design_research", "design_strategy", "design_candidates", "design_tournament", "design_swarm", "design_simulation", "design_counterfactual", "design_governance", "autonomous_art_director", "observe_facts"), + "write_principle": ("design_research", "design_strategy", "design_governance"), +} + + +def _run_id(rt: Any) -> str: + run = getattr(rt, "run", None) + return str( + getattr(run, "task_id", "") + or getattr(run, "trace_id", "") + or getattr(rt, "task_id", "") + or "" + ).strip() + + def build_intelligence_request(method: str, rt: Any) -> dict[str, Any]: """JSON body for ``POST {base}/v1/{method}`` (RemoteIntelligenceProvider).""" flags = getattr(rt, "flags", None) @@ -62,52 +93,44 @@ def build_intelligence_request(method: str, rt: Any) -> dict[str, Any]: ops = getattr(rt, "apply_ops", None) apply_ops = list(ops) if isinstance(ops, list) else [] - return { - "method": str(method or "").strip(), + canonical = str(method or "").strip() + values: dict[str, Any] = { + "design_brief": brief, + "design_research": _as_dict(getattr(rt, "design_research", None)) or _as_dict(_flag(rt, "design_research")), + "design_strategy": _as_dict(getattr(rt, "design_strategy", None)) or _as_dict(_flag(rt, "design_strategy")), + "design_candidates": _as_dict(getattr(rt, "design_candidates", None)) or _as_dict(_flag(rt, "design_candidates")), + "design_tournament": _as_dict(getattr(rt, "design_tournament", None)) or _as_dict(_flag(rt, "design_tournament")), + "design_swarm": _as_dict(getattr(rt, "design_swarm", None)) or _as_dict(_flag(rt, "design_swarm")), + "design_simulation": _as_dict(getattr(rt, "design_simulation", None)) or _as_dict(_flag(rt, "design_simulation")), + "design_counterfactual": _as_dict(getattr(rt, "design_counterfactual", None)) or _as_dict(_flag(rt, "design_counterfactual")), + "design_governance": _as_dict(getattr(rt, "design_governance", None)) or _as_dict(_flag(rt, "design_governance")), + "autonomous_art_director": _as_dict(getattr(rt, "autonomous_art_director", None)) or _as_dict(_flag(rt, "autonomous_art_director")), + "reference_dna": _as_dict(getattr(rt, "reference_dna", None)) or _as_dict(_flag(rt, "reference_dna")), + "reference_analyze": _as_dict(getattr(rt, "reference_analyze", None)) or _as_dict(_flag(rt, "reference_analyze")), + "reference_lock": _as_dict(getattr(rt, "reference_lock", None)) or _as_dict(_flag(rt, "reference_lock")), + "observe_facts": _as_dict(getattr(rt, "observe_facts", None)) or _as_dict(_flag(rt, "observe_facts")), + "judge_verdict": _as_dict(getattr(rt, "judge_verdict", None)) or _as_dict(_flag(rt, "judge_verdict")), + "visual_diff": _as_dict(_flag(rt, "visual_diff")), + "memory_notes": list(_flag(rt, "memory_notes") or []) if isinstance(_flag(rt, "memory_notes"), list) else [], + } + body: dict[str, Any] = { + "method": canonical, + "run_id": _run_id(rt), "prompt": str(getattr(rt, "prompt", "") or ""), "scene_key": str(getattr(rt, "scene_key", "") or ""), "intent": str(getattr(rt, "classified_intent", "") or ""), - "flags": flag_map, - "images": _images(rt), - "painted": _painted(rt), - "knowledge_written": bool(_flag(rt, "knowledge_written")), - "design_brief": brief, - "design_research": _as_dict(getattr(rt, "design_research", None)) - or _as_dict(_flag(rt, "design_research")), - "design_strategy": _as_dict(getattr(rt, "design_strategy", None)) - or _as_dict(_flag(rt, "design_strategy")), - "design_candidates": _as_dict(getattr(rt, "design_candidates", None)) - or _as_dict(_flag(rt, "design_candidates")), - "design_tournament": _as_dict(getattr(rt, "design_tournament", None)) - or _as_dict(_flag(rt, "design_tournament")), - "design_swarm": _as_dict(getattr(rt, "design_swarm", None)) - or _as_dict(_flag(rt, "design_swarm")), - "design_simulation": _as_dict(getattr(rt, "design_simulation", None)) - or _as_dict(_flag(rt, "design_simulation")), - "design_counterfactual": _as_dict(getattr(rt, "design_counterfactual", None)) - or _as_dict(_flag(rt, "design_counterfactual")), - "design_governance": _as_dict(getattr(rt, "design_governance", None)) - or _as_dict(_flag(rt, "design_governance")), - "autonomous_art_director": _as_dict( - getattr(rt, "autonomous_art_director", None) - ) - or _as_dict(_flag(rt, "autonomous_art_director")), - "reference_dna": _as_dict(getattr(rt, "reference_dna", None)) - or _as_dict(_flag(rt, "reference_dna")), - "reference_analyze": _as_dict(getattr(rt, "reference_analyze", None)) - or _as_dict(_flag(rt, "reference_analyze")), - "reference_lock": _as_dict(getattr(rt, "reference_lock", None)) - or _as_dict(_flag(rt, "reference_lock")), - "observe_facts": _as_dict(getattr(rt, "observe_facts", None)) - or _as_dict(_flag(rt, "observe_facts")), - "visual_diff": _as_dict(_flag(rt, "visual_diff")), - "judge_verdict": _as_dict(getattr(rt, "judge_verdict", None)) - or _as_dict(_flag(rt, "judge_verdict")), - "eval_patterns": list(_flag(rt, "eval_failure_patterns", "skill_failures") or []) - if isinstance(_flag(rt, "eval_failure_patterns", "skill_failures"), list) - else [], - "memory_notes": list(_flag(rt, "memory_notes") or []) - if isinstance(_flag(rt, "memory_notes"), list) - else [], - "apply_ops": apply_ops[:80], + "flags": { + key: flag_map[key] + for key in ("force_autonomous", "knowledge_written", "eval_failure_patterns") + if key in flag_map + }, + "images": _images(rt) if canonical in {"analyze_reference", "research", "review"} else [], + "painted": _painted(rt) if canonical in {"autonomous_sync", "review", "govern"} else False, + "knowledge_written": bool(_flag(rt, "knowledge_written")) if canonical in {"autonomous_sync", "write_principle"} else False, + "apply_ops": apply_ops[:80] if canonical in {"govern", "review"} else [], } + for key in _METHOD_CONTEXT.get(canonical, ()): + body[key] = values.get(key) + digest = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + body["input_hash"] = hashlib.sha256(digest.encode("utf-8")).hexdigest()[:32] + return body diff --git a/scripts/migrate_skills_layout.py b/scripts/migrate_skills_layout.py deleted file mode 100644 index bd790b32..00000000 --- a/scripts/migrate_skills_layout.py +++ /dev/null @@ -1,79 +0,0 @@ -"""One-shot: classify seeds/design_skills into skills/foundation|domains.""" -from __future__ import annotations - -import json -import shutil -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -SEEDS = ROOT / "apps" / "api" / "seeds" / "design_skills" -FOUNDATION_DIR = ROOT / "skills" / "foundation" -DOMAINS_DIR = ROOT / "skills" / "domains" - -FOUNDATION = { - "design_brief", - "visual_direction", - "design_system", - "composition", - "typography", - "color", - "imagery", - "layout", - "responsive", - "anti_ai_slop", - "design_review", - "polish", -} - -# Named domains from the public catalog; everything else surface → domains. -NAMED_DOMAINS = { - "poster_craft", - "landing_page", - "dashboard_ui", - "image_gen", - "presentation", - "social_media", -} - - -def main() -> None: - FOUNDATION_DIR.mkdir(parents=True, exist_ok=True) - DOMAINS_DIR.mkdir(parents=True, exist_ok=True) - if not SEEDS.is_dir(): - raise SystemExit(f"missing {SEEDS}") - - for pack in sorted(SEEDS.iterdir()): - if not pack.is_dir() or pack.name.startswith("."): - continue - meta_path = pack / "_meta.json" - category = "" - if meta_path.is_file(): - try: - category = str(json.loads(meta_path.read_text(encoding="utf-8")).get("category") or "") - except Exception: - category = "" - if pack.name in FOUNDATION or category == "foundation": - dest_root = FOUNDATION_DIR - else: - dest_root = DOMAINS_DIR - dest = dest_root / pack.name - if dest.exists(): - print(f"skip exists {dest.relative_to(ROOT)}") - continue - print(f"move {pack.name} -> {dest.relative_to(ROOT)} (cat={category or '?'})") - shutil.move(str(pack), str(dest)) - - # Leave a pointer so old docs/paths are not a dead end. - readme = SEEDS / "README.md" - if not readme.exists(): - readme.write_text( - "# Legacy path\n\n" - "Shipped Design Agent skills live under repo-root " - "`skills/foundation` and `skills/domains`.\n" - "This directory is kept for backward-compatible empty mounts.\n", - encoding="utf-8", - ) - - -if __name__ == "__main__": - main() diff --git a/skills/README.md b/skills/README.md index cde4b1a2..5de4f9da 100644 --- a/skills/README.md +++ b/skills/README.md @@ -36,5 +36,4 @@ Design Agent scans (later wins on duplicate `skill_key`): 1. `skills/foundation` 2. `skills/domains` -3. `apps/api/seeds/design_skills` (legacy empty shim) -4. `plugins/skills` (+ `DESIGN_SKILLS_PLUGIN_DIRS`) +3. `plugins/skills` (+ `DESIGN_SKILLS_PLUGIN_DIRS`)