合并主线并同步四不写约定
Project CI / Repository checks (push) Successful in 1m16s
Project CI / Frontend tests (push) Successful in 3m0s
Project CI / Backend tests (push) Successful in 4m15s
Project CI / Native shell tests (push) Successful in 13m48s

合入最新远端主线且保留退役对象四不写规则

同步团队约定中的公开契约与正式迁移例外

保持原工作树其他已暂存和未暂存修改不变
This commit is contained in:
2026-08-10 20:16:21 +08:00
417 changed files with 72390 additions and 9969 deletions
@@ -17,7 +17,7 @@ Prefer `scripts/genarrative_external_api.py` for runnable REST calls. It uses on
2. Before the first generation in a new conversation, obtain a canvas name unless an existing `projectId` and `assetFolderId` were supplied. Create or reuse a project and a same-name asset-library folder. Retain `canvasName`, `projectId`, `assetFolderId`, and the current art spec.
3. Normalize art requests into a reusable spec. Ask only for missing values that block the selected operation. Reuse the spec until the user changes its style, subject family, palette, format, or constraints.
4. Infer the operation from the user's intent. Do not ask the user to select an API unless two operations would produce materially different artifacts.
5. If a reference exists only as a local file, upload and confirm it first. Pass the stable returned `objectKey` to generation; never substitute a temporary signed URL.
5. If a reference exists only as a local file, upload and confirm it first. Pass the stable returned `objectKey` to operations that accept object references; never substitute a temporary signed URL. For an icon-spritesheet primary spec, additionally create a project resource or asset record with `assetKind="icon-spec"`, then pass the returned resource or asset ID as `referenceId`.
6. For generation endpoints that support the fields, include `projectId`, `assetFolderId`, an asset label, and `canvasCompletion` so the result enters both the canvas and its same-name library folder.
7. Treat every generation POST as asynchronous. Send one stable `Idempotency-Key` per logical request, retain the returned `operationId`, and poll the returned `statusUrl` or `GET /api/external/v1/generations/{operationId}` according to `pollAfterMs`.
8. Consume `result` only after `status=completed`. On `failed`, surface the safe error. On a client timeout or lost response, retain the operation/key; do not create a replacement request.
@@ -32,7 +32,7 @@ Prefer `scripts/genarrative_external_api.py` for runnable REST calls. It uses on
- Use stable references such as `objectKey`, project resource ID, or asset ID in generation requests. Use `/assets/read-url` only for temporary preview/download access.
- Preserve both warning channels after completion. A general `warning` can coexist with `sliceWarning`; do not discard either.
- Do not invent missing derivatives. A source-preserved warning means the main source remains usable but requested post-processing failed. A slice warning means the complete transparent sheet is usable but individual slices are absent.
- Keep generated artifacts in the canvas and asset library together. Character animation may need a post-completion library fallback from the first returned frame when no direct asset is present; the helper implements it.
- Keep generated artifacts in the canvas and asset library together. Character animation accepts `assetFolderId` and `assetLabel`; its completed result directly returns the final `assetKind="character-animation"` resource and asset with formal sequence fields. Do not create a duplicate first-frame record.
## Documentation Navigation
@@ -107,6 +107,8 @@ client.generate_image(
Helper convenience methods wait locally, but the server still uses short asynchronous submit/status requests. For durable caller-controlled orchestration, call `submit_generation`, persist its `operationId` and idempotency key, then call `get_generation` or `wait_for_generation`.
For character animation, pass the canvas session and asset label to `animate_character`. The helper submits asynchronously and returns the completed compact result containing the authoritative formal `resource` and `asset`; do not synthesize a library asset from the first frame.
## Guardrails
- Do not change the fixed production base URL in generated examples.
@@ -8,7 +8,7 @@ All paths below are relative to `https://www.genarrative.world`. Discovery and S
| Operation | Method and path | Minimum input |
| --- | --- | --- |
| List projects | `GET /api/external/v1/editor/projects` | Authentication |
| List projects | `GET /api/external/v1/editor/projects` | Authentication; optional `view=full\|summary` (default `full`) |
| Create project | `POST /api/external/v1/editor/projects` | Optional `title` |
| Load recent project | `GET /api/external/v1/editor/projects/recent` | Authentication |
| Get project | `GET /api/external/v1/editor/projects/{projectId}` | `projectId` |
@@ -19,6 +19,13 @@ All paths below are relative to `https://www.genarrative.world`. Discovery and S
Canvas save uses optimistic revision control. Pass the last authoritative `expectedRevision`; on conflict, reload instead of replaying a stale full layout.
Project listing supports two views:
- `view=full` is the REST default and returns the complete project, canvas, layers, and resources.
- `view=summary` returns only `projectId`, `title`, `updatedAt`, and nullable `cover`, so callers can display, search, disambiguate same-name projects, and select a safe target without loading every canvas snapshot.
- Hosted MCP `list_editor_projects` always uses `summary`; call `get_editor_project` after selecting a `projectId` when complete authoritative state is required.
- `cover` contains only `resourceId`, stable `objectKey`, dimensions, and `updatedAt`. It never embeds image bytes, a Data URL, or a signed URL. To display it, pass `cover.objectKey` to `get_external_asset_read_url`; signed URLs are temporary and must not be persisted or reused as generation references.
## Asset and Upload Operations
| Operation | Method and path | Minimum input |
@@ -44,11 +51,11 @@ Every generation row requires a stable `Idempotency-Key` header and returns HTTP
| --- | --- | --- | --- |
| Image generation | `/api/external/v1/editor/images/generations` | `prompt` | `kind`, `style`, `model`, `aspectRatio`, `imageSize`, `size`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Image edit/redraw | `/api/external/v1/editor/images/edits` | `prompt`, `sourceImageSrc` | `referenceImageSrcs`, `model`, `size`, `projectId`, `assetFolderId`, `assetLabel`, `sourceResourceId`, `targetLayerId`, `canvasCompletion` |
| Icon spritesheet | `/api/external/v1/editor/icon-spritesheets/generations` | `referenceImageSrc`, `iconDescriptions` | `style`, `referenceImageSrcs`, `screenColor`, `model`, `aspectRatio`, `imageSize`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Icon spritesheet | `/api/external/v1/editor/icon-spritesheets/generations` | `referenceId`, `iconDescriptions` | `style`, `referenceImageSrcs`, `screenColor`, `model`, `aspectRatio`, `imageSize`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| UI asset extraction | `/api/external/v1/editor/ui-designs/assets/extractions` | `sourceImageSrc`, `aspectRatio`, `imageSize` | `screenColor`, `model`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `spritesheetLabel`, `canvasCompletion` |
| Character animation | `/api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` | `projectId`, `sourceResourceId`, `canvasCompletion` |
| Character animation | `/api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` | `projectId`, `sourceResourceId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Video generation | `/api/external/v1/editor/videos/generations` | `prompt`, `model`, `aspectRatio`, `durationSeconds`, `resolution`, `mode`, `sound` | `referenceImageSrcs`, `referenceVideoSrcs`, `referenceAudioSrcs`, `webSearchEnabled`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Sound effect | `/api/external/v1/editor/audios/sound-effects/generations` | `prompt`, `duration` | `model`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Sound effect | `/api/external/v1/editor/audios/sound-effects/generations` | `prompt` | `model`, `duration`, `loop`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Background music | `/api/external/v1/editor/audios/background-music/generations` | `gptDescriptionPrompt`, `makeInstrumental` | `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
Poll all eight through:
@@ -64,29 +71,33 @@ Supply the `operationId` returned by submission. Poll no faster than `pollAfterM
- Pass `projectId` and `canvasCompletion` to write generated output into the canvas.
- Pass `assetFolderId` plus `assetLabel` for image, edit, icon spritesheet, video, sound effect, and BGM operations when supported.
- UI extraction uses `assetFolderId` and `spritesheetLabel`.
- Character animation does not accept the same library fields. If its completed compact result lacks a direct `asset`, create a library record from the first returned frame; do not duplicate one when an asset already exists.
- Character animation accepts `assetFolderId` and `assetLabel`. Its completed compact result directly returns the final `assetKind="character-animation"` resource and asset with `imageSequenceFrames` and `imageSequenceDurationMs`; never create a duplicate first-frame resource or asset.
- If a caller must manually create a `character-animation` resource or asset, put the authoritative frames and total sequence duration in `imageSequenceFrames` and `imageSequenceDurationMs`. Keep `generationInputs` replayable: it must not contain legacy runtime fields such as `characterAnimation`, `frames`, `previewVideoPath`, `frameCount`, `fps`, or `durationSeconds`.
- Reload project/library state after completion when full current state is required.
## Reference Field Mapping
After confirming a local upload, pass its stable `objectKey` into:
After confirming a local upload, pass its stable `objectKey` into operations that accept object references:
| Target capability | Field |
| --- | --- |
| Image generation | `referenceImageSrcs` |
| Image edit/redraw | `sourceImageSrc`; additional references in `referenceImageSrcs` |
| Icon spritesheet | `referenceImageSrc`; additional style references in `referenceImageSrcs` |
| Icon spritesheet | Register the primary spec as an `assetKind="icon-spec"` project resource or asset, then pass its returned ID as `referenceId`; additional style references remain in `referenceImageSrcs` |
| UI design extraction | `sourceImageSrc`; additional references in `referenceImageSrcs` |
| Character animation | `sourceImageSrc` |
| Video with image references | `referenceImageSrcs` |
Use video/audio reference arrays only with models that support them. Do not pass an expiring signed read URL as a generation reference.
The icon-spritesheet primary `referenceId` is intentionally stricter than ordinary image references: it accepts only a current-owner project resource ID or asset ID whose authoritative `assetKind` is `icon-spec`. It does not accept an `objectKey`, URL, Data URL, or Blob URL.
## Common Values
Use OpenAPI as the final authority; these common values are a routing aid:
- Image `kind`: `spec`, `character`, `quick-edit`, `ui-design`, `publication-material`; ordinary image generation may omit it.
- External v1 currently has no structured game-scene generation operation. Do not send `kind: "scene"` or `assetKind: "scene"` through generic image generation; the server rejects both before queueing.
- Image `model`: `gpt-image-2`, `gemini-3.1-flash-image-preview`, `nanobanana2`, `nano-banana`.
- Image `aspectRatio`: `1:1`, `2:3`, `3:2`, `9:16`, `16:9`.
- Image `imageSize`: `0.5K`, `1K`, `2K`.
@@ -94,6 +105,7 @@ Use OpenAPI as the final authority; these common values are a routing aid:
- Video `aspectRatio`: `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `21:9`.
- Video `resolution`: `480p`, `720p`, `1080p`; `mode`: `std`; `sound`: `on` or `off`.
- Character animation uses `model: "seedance2.0-fast"`; `resolution`: `480p` or `720p`; `frameCount`: `32`, `40`, or `48`; `durationSeconds`: `4`, `5`, or `6`; `ratio`: `same`, `1:1`, `4:3`, `16:9`, `9:16`, or `3:4`.
- Sound effect uses canonical model `eleven_text_to_sound_v2`; omit `duration` or send `null` for automatic duration, otherwise send a finite `0.5-30` number. `loop` defaults to `false` and remains independent from Prompt text.
- UI extraction uses `aspectRatio: "1:1"`; use `imageSize: "1K"` for normal/small extraction and `2K` for dense designs.
Do not hard-code this list as a replacement client schema. In particular, the top-level image `style` field is intentionally extensible; see `requests-and-outputs.md` for its fallback behavior.
@@ -20,7 +20,7 @@ Before the first generation in a new conversation, obtain a canvas name unless t
2. Read the asset library. Reuse a folder with the same label or create one with the canvas name.
3. Retain `canvasName`, `projectId`, `assetFolderId`, and the current art spec in conversation state.
Generated artifacts must enter both the current canvas and its same-name library folder whenever the endpoint supports that invariant. Pass `projectId`, `assetFolderId`, the endpoint's label field, and `canvasCompletion`. Character animation may return no direct library asset; after completion, create one from the first returned frame only when the compact result still lacks an asset.
Generated artifacts must enter both the current canvas and its same-name library folder whenever the endpoint supports that invariant. Pass `projectId`, `assetFolderId`, the endpoint's label field, and `canvasCompletion`. Character animation returns the final formal resource and asset directly; use those records and never create a duplicate from the first frame.
## Art Spec Routing
@@ -78,7 +78,7 @@ Keep the existing autonomous-build task graph. Do not add a parallel task system
1. `art-director` generates `assets/art-spec.png` with image generation, `kind: "spec"`, then registers it as `assetKind: "icon-spec"`. This image is the authoritative visual spec; `generationInputs.artSpec` is supporting structured context.
2. `design-foundation` generates `assets/ui-prototype.png` with `kind: "ui-design"`, using the registered art-spec resource ID in `referenceImageSrcs`.
3. `art-asset-plan` generates transparent `assets/art-spritesheet.png` through icon spritesheet generation, using the same registered art-spec resource ID as `referenceImageSrc` plus concrete `iconDescriptions`.
3. `art-asset-plan` generates transparent `assets/art-spritesheet.png` through icon spritesheet generation, using the same registered art-spec resource ID as `referenceId` plus concrete `iconDescriptions`.
For a playable Canvas game, do not stop at generation. Make `code-prototype` depend on `art-asset-plan` and consume the persisted `iconImageSrcs` slices for core players, blocks or targets, scene obstacles, and feedback. For the four-category game-chat contract, require exactly four slices before registering the local runtime sheet; both fewer and extra components fail closed. Treat `art-spec.png` as reference-only. A full-sheet `<img>`, CSS background, path-only mention, guessed equal-grid crop, or code-drawn replacement for core entities is not runtime asset use. If slicing produces `sliceWarning`, keep the complete transparent sheet as a valid editor artifact, but fail the playable game asset gate until real slice files or verified atlas coordinates exist; never invent coordinates or replace the icon-spritesheet route with ordinary image generation.
@@ -98,10 +98,14 @@ A minimal `canvasCompletion` is:
`dialogId` is optional. Do not reconstruct canvas state from completion results. Reload the project and asset library when complete authoritative snapshots are needed.
Character animation may complete without a direct `asset` field. To preserve the canvas/library invariant, create a library asset from the first returned frame only if the compact result lacks one. Prefer `client.animate_character(..., canvasSession=session, canvasTitle="...")`, which implements this fallback.
Character animation accepts `assetFolderId` and `assetLabel` and persists the final transparent sequence directly. Its completed compact result includes the authoritative `assetKind="character-animation"` resource and asset with `imageSequenceFrames` and `imageSequenceDurationMs`. Use those records directly and never synthesize a duplicate asset from the first frame.
For the lower-level asset/resource creation endpoints, `generationInputs` is replayable request context rather than a media-runtime container. When `assetKind` is `character-animation`, the server rejects legacy runtime keys including `characterAnimation`, `frames`, `previewVideoPath`, `frameCount`, `fps`, and `durationSeconds`; send the formal sequence through `imageSequenceFrames` and `imageSequenceDurationMs`. Internal processing audit keys such as `screenColorHex`, `mattingProvider`, and `mattingModel` are removed before persistence.
## Art Spec and Image Request
Generic External v1 image generation does not expose the main-site structured game-scene contract. `kind: "scene"` and `assetKind: "scene"` are both invalid and return HTTP `400` before any generation job is queued. Do not replace the structured scene fields and server-owned prompt assembly with a generic image prompt.
Carry the current art spec in `generationInputs.artSpec` and reflect important constraints in the prompt:
```json
@@ -165,6 +169,8 @@ client.generate_image(
)
```
Icon spritesheet generation has a stricter primary-spec contract. After upload confirmation, create a project resource or asset record with `assetKind: "icon-spec"`, retain its returned `resourceId` or `assetId`, and pass that ID as `referenceId`. The primary spec does not accept the uploaded `objectKey` directly; only additional style references may continue to use stable object keys in `referenceImageSrcs`.
For character animation from a local-only source, use actual dimensions and a stable synthetic layer ID:
```json
@@ -178,7 +184,9 @@ For character animation from a local-only source, use actual dimensions and a st
"ratio": "9:16",
"frameCount": 40,
"durationSeconds": 5,
"model": "seedance2.0-fast"
"model": "seedance2.0-fast",
"assetFolderId": "<assetFolderId>",
"assetLabel": "角色呼吸动画"
}
```
@@ -189,6 +197,7 @@ Do not guess dimensions or pass a temporary signed read URL. See `authentication
The completed `result` may contain stable artifact fields such as:
- `objectKey`, media type, dimensions, or task ID.
- Sound-effect `durationSeconds` is the probed MP3 duration and `loop` is the frozen request boolean; neither is inferred from Prompt text.
- `resource`, `resourceId`, or equivalent canvas reference.
- `asset`, `assetId`, or equivalent library reference.
- `spritesheetResource`, `spritesheetAsset`, and stable spritesheet metadata.
@@ -560,10 +560,13 @@ class GenarrativeExternalClient:
def generate_icon_spritesheet(
self,
reference_image_src: str,
reference_id: str,
icon_descriptions: list[str],
**fields: Any,
) -> Any:
reference_id = normalize_optional_text(reference_id)
if not reference_id:
raise GenarrativeApiError("reference_id must be a registered icon-spec resource or asset ID")
descriptions = [item.strip() for item in icon_descriptions if item.strip()]
if not descriptions:
raise GenarrativeApiError("icon_descriptions must contain at least one non-empty item")
@@ -574,9 +577,9 @@ class GenarrativeExternalClient:
return self.submit_and_wait_generation(
"/api/external/v1/editor/icon-spritesheets/generations",
{
"referenceImageSrc": reference_image_src,
"iconDescriptions": descriptions,
**fields,
"referenceId": reference_id,
"iconDescriptions": descriptions,
},
idempotency_key=idempotency_key,
)
@@ -600,16 +603,14 @@ class GenarrativeExternalClient:
source_layer_id: str,
**fields: Any,
) -> Any:
session, asset_label = self._apply_canvas_session_fields(
self._apply_canvas_session_fields(
fields,
fields.get("canvasTitle", "角色动画"),
source_width,
source_height,
asset_label_field=None,
asset_label_field="assetLabel",
)
prompt_text = self._apply_art_spec(fields, prompt_text)
fields.pop("assetFolderId", None)
fields.pop("assetLabel", None)
idempotency_key = fields.pop("idempotencyKey", None)
body = {
"sourceLayerId": source_layer_id,
@@ -624,34 +625,11 @@ class GenarrativeExternalClient:
**fields,
"model": "seedance2.0-fast",
}
result = self.submit_and_wait_generation(
return self.submit_and_wait_generation(
"/api/external/v1/editor/character-animations/generations",
body,
idempotency_key=idempotency_key,
)
if isinstance(session, dict) and isinstance(result, dict) and not result.get("asset"):
frames = result.get("frames")
first_frame = frames[0] if isinstance(frames, list) and frames else None
folder_id = normalize_optional_text(session.get("assetFolderId"))
if isinstance(first_frame, dict) and folder_id:
asset = self.create_asset(
folder_id,
asset_label,
first_frame["imageSrc"],
int(first_frame["width"]),
int(first_frame["height"]),
prompt=result.get("prompt"),
model=result.get("model"),
provider="ark",
taskId=result.get("taskId"),
assetKind="character-animation",
generationInputs={
"frames": frames,
"previewVideoPath": result.get("previewVideoPath"),
},
)
result["asset"] = unwrap_envelope(asset).get("asset")
return result
def generate_video(self, prompt: str, **fields: Any) -> Any:
fields.pop("mode", None)
@@ -674,13 +652,19 @@ class GenarrativeExternalClient:
idempotency_key=idempotency_key,
)
def generate_sound_effect(self, prompt: str, duration: int, **fields: Any) -> Any:
def generate_sound_effect(
self,
prompt: str,
duration: float | None = None,
loop: bool = False,
**fields: Any,
) -> Any:
self._apply_canvas_session_fields(fields, prompt, 360, 120)
prompt = self._apply_art_spec(fields, prompt)
idempotency_key = fields.pop("idempotencyKey", None)
return self.submit_and_wait_generation(
"/api/external/v1/editor/audios/sound-effects/generations",
{"prompt": prompt, "duration": duration, **fields},
{"prompt": prompt, "duration": duration, "loop": loop, **fields},
idempotency_key=idempotency_key,
)
@@ -732,14 +716,31 @@ def _self_test() -> None:
"timeout": timeout,
"headers": headers,
})
if path == "/api/external/v1/editor/assets":
return {"asset": {"assetId": "editor-asset-demo"}}
generated = {
"taskId": "task-demo",
"model": "seedance2.0-fast",
"prompt": "角色呼吸",
"previewVideoPath": "/generated/preview.mp4",
"frames": [{"frameIndex": 1, "imageSrc": "/generated/frame01.png", "width": 512, "height": 768}],
"frames": [{"imageSrc": "/generated/frame01.png", "width": 512, "height": 768}],
"resource": {
"resourceId": "editor-resource-demo",
"assetKind": "character-animation",
"sourceResourceId": "editor-resource-preview-demo",
"imageSequenceFrames": [
{"imageSrc": "/generated/frame01.png", "width": 512, "height": 768},
{"imageSrc": "/generated/frame02.png", "width": 512, "height": 768},
],
"imageSequenceDurationMs": 4000,
},
"asset": {
"assetId": "editor-asset-demo",
"assetKind": "character-animation",
"imageSequenceFrames": [
{"imageSrc": "/generated/frame01.png", "width": 512, "height": 768},
{"imageSrc": "/generated/frame02.png", "width": 512, "height": 768},
],
"imageSequenceDurationMs": 4000,
},
}
if method == "POST":
return {"operationId": "task-operation-demo", "status": "queued", "pollAfterMs": 1}
@@ -760,19 +761,25 @@ def _self_test() -> None:
assert calls[0]["timeout"] == DEFAULT_REQUEST_TIMEOUT_SECONDS
assert calls[0]["headers"]["Idempotency-Key"]
assert calls[0]["body"]["projectId"] == "proj-demo"
assert calls[0]["body"]["assetFolderId"] == "editor-asset-folder-demo"
assert calls[0]["body"]["assetLabel"] == "角色呼吸动画"
assert calls[0]["body"]["canvasCompletion"]["title"] == "角色呼吸动画"
assert calls[1]["path"] == "/api/external/v1/generations/task-operation-demo"
assert calls[2]["path"] == "/api/external/v1/editor/assets"
assert result["asset"]["assetId"] == "editor-asset-demo"
assert result["asset"]["assetKind"] == "character-animation"
assert len(result["asset"]["imageSequenceFrames"]) == 2
assert result["asset"]["imageSequenceDurationMs"] == 4000
calls.clear()
client.generate_icon_spritesheet(
"editor-resource-spec",
["蛇头向上", "蛇身直线", "转角", "尾部", "四类食物"],
canvasSession=session,
assetLabel="贪吃蛇透明图集",
referenceId="must-not-override-explicit-reference",
iconDescriptions=["不得覆盖显式图标描述"],
)
assert calls[0]["path"] == "/api/external/v1/editor/icon-spritesheets/generations"
assert calls[0]["body"]["referenceImageSrc"] == "editor-resource-spec"
assert calls[0]["body"]["referenceId"] == "editor-resource-spec"
assert calls[0]["body"]["screenColor"] == "auto"
assert calls[0]["body"]["iconDescriptions"][0] == "蛇头向上"
assert calls[1]["path"] == "/api/external/v1/generations/task-operation-demo"
+5
View File
@@ -130,6 +130,11 @@ VECTOR_ENGINE_BASE_URL="https://api.vectorengine.cn"
VECTOR_ENGINE_API_KEY=""
VECTOR_ENGINE_IMAGE_REQUEST_TIMEOUT_MS="1000000"
# ElevenLabs editor sound-effect generation is server-side only.
ELEVENLABS_BASE_URL="https://api.elevenlabs.io"
ELEVENLABS_API_KEY=""
ELEVENLABS_REQUEST_TIMEOUT_MS="180000"
# 阿里云 OSS 配置。
# Rust `server-rs` 的 `api-server` 会优先从 `.env` / `.env.local` 读取这些变量,
# 用于签发浏览器 PostObject 直传票据,并保持 `/generated-*` 旧路径习惯。
+6 -6
View File
@@ -67,7 +67,7 @@ jobs:
echo "SPACETIME_SCHEMA_BASE_REF=${base_ref}" >> "${GITHUB_ENV}"
- name: Install npm dependencies
run: npm ci
run: bash scripts/ci-npm-ci-with-retry.sh
- name: Run repository lint gates
run: npm run lint
@@ -101,10 +101,10 @@ jobs:
run: GENARRATIVE_GITEA_CI_CHECK_RUNTIME=1 bash scripts/check-gitea-ci-job-image.sh
- name: Install npm dependencies
run: npm ci
run: bash scripts/ci-npm-ci-with-retry.sh
- name: Install AI game creator dependencies
run: npm ci --prefix apps/ai-game-creator-shell
run: bash scripts/ci-npm-ci-with-retry.sh --prefix apps/ai-game-creator-shell
- name: Run frontend and script tests
run: npm run test
@@ -159,7 +159,7 @@ jobs:
echo "SPACETIME_SCHEMA_BASE_REF=${base_ref}" >> "${GITHUB_ENV}"
- name: Install npm dependencies
run: npm ci
run: bash scripts/ci-npm-ci-with-retry.sh
- name: Prepare server-rs Rust dependencies
shell: bash
@@ -204,10 +204,10 @@ jobs:
run: GENARRATIVE_GITEA_CI_CHECK_RUNTIME=1 bash scripts/check-gitea-ci-job-image.sh
- name: Install npm dependencies
run: npm ci
run: bash scripts/ci-npm-ci-with-retry.sh
- name: Install AI game creator dependencies
run: npm ci --prefix apps/ai-game-creator-shell
run: bash scripts/ci-npm-ci-with-retry.sh --prefix apps/ai-game-creator-shell
- name: Prepare native Rust dependencies
shell: bash
@@ -2,7 +2,7 @@
name: genarrative-dev-stack-port-routing
short_description: 修改 Genarrative 本地 dev 启动端口、代理目标、端口冲突处理时使用。
description: 在 Genarrative 中修改 npm run dev / dev:spacetime / dev:api-server / dev:bgfilter-worker / dev:web / dev:admin-web 的本地启动端口、端口可用性探测、端口漂移、SpacetimeDB publish server、Rust 进程环境变量、Vite 代理目标和后台 admin-web 启动串联时使用。
version: 1.1.0
version: 1.2.0
author: Hermes Agent
license: MIT
metadata:
@@ -17,7 +17,7 @@ metadata:
## 适用场景
- 修改 `scripts/dev.mjs`、`scripts/dev-utils.mjs`、`scripts/dev-stack-port-utils.mjs`。
- 修改 `scripts/dev.mjs`、`scripts/dev-utils.mjs`、`scripts/dev-stack-port-utils.mjs` 或 AI 游戏创作客户端 dev 启动器。
- 处理 `3000`、`3101`、`3102`、`8082` 等端口被占用导致本地开发栈启动失败。
- 排查 Vite 代理仍指向旧 api-server 端口、前端打开了旧 dev server、后台代理错配。
- 调整 SpacetimeDB standalone、publish、Rust `api-server`、主站 Vite、后台 Vite 的启动顺序。
@@ -32,10 +32,11 @@ metadata:
3. SpacetimeDB standalone:`3101`,健康检查为 `http://127.0.0.1:<spacetime-port>/v1/ping`。
4. 后台 Vite:`3102`,后台地址为 `http://127.0.0.1:<admin-web-port>/admin/`。
5. 独立 BgFilter worker:`8083`,就绪检查为 `http://127.0.0.1:<bgfilter-worker-port>/readyz`。
6. AI 游戏创作 Vite:非 Linux 兼容首选 `3080`;Linux 使用当前用户端口段的 `start + 5`。
端口不可用时,脚本会从优先端口开始向后寻找可用端口。后续流程必须以解析后的实际端口为准,不能继续使用默认端口。
Linux 多用户并发开发时,`GENARRATIVE_DEV_PORT_RANGE` 或 `--port-range` 会先向系统级注册表 `/var/tmp/genarrative-dev-port-ranges/registry.json` 申请一个端口段,再把该段映射为 `web = start`、`api = start + 1`、`spacetime = start + 2`、`adminWeb = start + 3`、`bgfilterWorker = start + 4`。注册表锁文件是 `/var/tmp/genarrative-dev-port-ranges/registry.lock`,可通过 `GENARRATIVE_DEV_PORT_RANGE_REGISTRY_DIR` 覆盖目录。自动分配从 `10000-10099` 起,每次占用 100 个端口块,后续块按 `10100-10199`、`10200-10299` 递增;当前口径是“一个用户固定占用一个段,后续启动继续复用这段并在段内漂移”;该注册表只在 Linux 上生效;Windows 继续沿用原有统一端口探测和漂移逻辑,不读系统级注册表。
Linux 多用户并发开发时,`GENARRATIVE_DEV_PORT_RANGE` 或 `--port-range` 会先向系统级注册表 `/var/tmp/genarrative-dev-port-ranges/registry.json` 申请一个端口段,再把该段映射为 `web = start`、`api = start + 1`、`spacetime = start + 2`、`adminWeb = start + 3`、`bgfilterWorker = start + 4`、`agcVite = start + 5`。注册表锁文件是 `/var/tmp/genarrative-dev-port-ranges/registry.lock`,可通过 `GENARRATIVE_DEV_PORT_RANGE_REGISTRY_DIR` 覆盖目录。自动分配从 `10000-10099` 起,每次占用 100 个端口块,后续块按 `10100-10199`、`10200-10299` 递增;当前口径是“一个用户固定占用一个段,后续启动继续复用这段并在段内漂移”;该注册表只在 Linux 上生效;Windows 继续沿用原有统一端口探测和漂移逻辑,不读系统级注册表。
## 实现入口
@@ -51,9 +52,12 @@ Linux 多用户并发开发时,`GENARRATIVE_DEV_PORT_RANGE` 或 `--port-range`
- `scripts/dev.mjs`
- 解析 CLI 参数后统一计算 client host、端口、`SPACETIME_SERVER`、`RUST_SERVER_TARGET`。
- 完整栈按 SpacetimeDB、publish、BgFilter worker readiness、api-server readiness、主站 Vite、后台 Vite 顺序启动。
- Linux 下会先申请系统级端口段并把它映射成五个 dev 端口;自动分配从 `10000-10099` 起,Windows 则把第五个服务纳入原有统一参数解析与端口漂移逻辑。
- Linux 下会先申请系统级端口段并映射成六个预留槽位;主 dev 栈使用前五个,AGC Vite 使用 `start + 5`,自动分配从 `10000-10099` 起。Windows 的主 dev 栈和 AGC 则各自沿用统一端口探测与漂移逻辑。
- 完整栈和 `dev:api-server` 把两个 Rust 进程作为同一重启单元,先全部停止,再先启动 BgFilter worker、后启动 api-server;不要为同一份 Rust 源码创建两个并发 `cargo` watcher。
- 单模块命令复用同一套参数和 env 解析。
- `apps/ai-game-creator-shell/scripts/dev-port.mjs`
- 复用系统级用户端口段,解析 AGC Vite 的 `start + 5` 首选槽位。
- 把最终端口通过 `GENARRATIVE_AGC_VITE_PORT` 同步给 `beforeDevCommand` 和配套后端端口解析器,通过 Tauri CLI `--config` 同步 `build.devUrl`,并通过 Vite CLI `--port` 同步 `strictPort` 监听。
## 必须保持的传递链路
@@ -69,6 +73,7 @@ Linux 多用户并发开发时,`GENARRATIVE_DEV_PORT_RANGE` 或 `--port-range`
8. 后台 Vite:`ADMIN_API_TARGET`、`GENARRATIVE_API_TARGET`、`GENARRATIVE_API_PORT`、`--port=${ADMIN_WEB_PORT}`。
9. 控制台日志:`[dev:ports]` 和 `[dev] web/admin web/api-server/bgfilter-worker/spacetime` 必须显示最终实际地址。
10. Linux 端口段注册:`[dev] port-range:` 与 `[dev] port-range-registry:` 只在 Linux 输出,Windows 不应依赖系统级注册表。
11. AI 游戏创作客户端:外层启动器解析最终 AGC Vite 端口后,通过 Tauri CLI `--config` 覆盖 `build.devUrl`,把同一 `GENARRATIVE_AGC_VITE_PORT` 传给 `beforeDevCommand` 与配套后端端口解析器,并用 Vite CLI `--port` 启动严格监听;后端端口漂移必须跳过该预留端口。
如果只改了其中一段,通常会出现:浏览器打开的前端可用,但 `/api/*` 代理到旧端口;后台页面可用但后台 API 失败;SpacetimeDB 启动在新端口但 publish 仍发往旧端口。
@@ -128,6 +133,7 @@ node scripts/dev-stack-port-utils.mjs resolve-dev-stack spacetime:127.0.0.1:0 ap
- [ ] `npm run dev` 的 SpacetimeDB、publish、api-server、主站 Vite、后台 Vite 都使用实际端口。
- [ ] BgFilter worker 在 api-server 前 ready,父子共享实际 base URL / Token,Rust watch 只触发一次组合重启。
- [ ] `npm run dev:web` 在主站端口不可用时能切换到可用端口。
- [ ] `npm run agc` / `npm run agc:game-chat` 在 Linux 使用用户段 `start + 5`,Tauri、Vite、marker 和预检使用同一最终端口。
- [ ] 文档同步更新 `docs/【开发运维】本地开发验证与生产运维-2026-05-15.md`。
- [ ] 长期踩坑同步更新 `docs/project-memory/shared-memory/pitfalls.md`。
- [ ] 修改中文文件后运行 `npm run check:encoding`。
+12
View File
@@ -332,6 +332,14 @@ export interface AdminEditorAssetListQuery {
limit?: number | null;
}
export interface AdminEditorImageSequenceFramePayload {
imageSrc: string;
objectKey?: string | null;
assetObjectId?: string | null;
width: number;
height: number;
}
export interface AdminEditorAssetPayload {
assetId: string;
ownerUserId: string;
@@ -362,6 +370,8 @@ export interface AdminEditorAssetPayload {
taskGenerator: string;
taskCostMudPoints: number;
children: AdminEditorAssetPayload[];
imageSequenceFrames?: AdminEditorImageSequenceFramePayload[] | null;
imageSequenceDurationMs?: number | null;
}
export interface AdminEditorAssetListResponse {
@@ -413,6 +423,8 @@ export interface AdminEditorShowcaseAssetPayload {
rejectedAt?: string | null;
updatedAt: string;
showcaseCategory?: string | null;
imageSequenceFrames?: AdminEditorImageSequenceFramePayload[] | null;
imageSequenceDurationMs?: number | null;
}
export interface AdminEditorShowcaseListResponse {
@@ -0,0 +1,354 @@
/* @vitest-environment jsdom */
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { getAdminAssetReadUrl } from '../api/adminApiClient';
import { AdminEditorAssetPreviewDialog } from './AdminEditorAssetMedia';
vi.mock('../api/adminApiClient', () => ({
getAdminAssetReadUrl: vi.fn(),
isAdminApiError: vi.fn(
(error: unknown) =>
typeof error === 'object' &&
error !== null &&
'status' in error &&
typeof error.status === 'number',
),
}));
afterEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
});
function createDeferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
test('角色动作预览跨窗口回播时复用父级换签缓存并等待目标帧就绪', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-07-04T10:50:00Z'));
const frameObjectKeys = [
'generated-animations/editor/task-cache/frame00.png',
'generated-animations/editor/task-cache/frame01.png',
'generated-animations/editor/task-cache/frame02.png',
'generated-animations/editor/task-cache/frame03.png',
'generated-animations/editor/task-cache/frame04.png',
] as const;
const delayedFrame = createDeferred<{
read: {
objectKey: string;
signedUrl: string;
expiresAt: string;
};
}>();
vi.mocked(getAdminAssetReadUrl).mockImplementation((_token, request) => {
const objectKey = request.objectKey ?? '';
if (objectKey === frameObjectKeys[3]) {
return delayedFrame.promise;
}
return Promise.resolve({
read: {
objectKey,
signedUrl: `https://signed.example.com/${objectKey}`,
expiresAt: '2026-07-04T11:00:00Z',
},
});
});
render(
<AdminEditorAssetPreviewDialog
entry={{
assetId: 'asset-character-animation-cache',
label: '缓存回播动作',
imageSrc: `/${frameObjectKeys[0]}`,
objectKey: frameObjectKeys[0],
assetKind: 'character-animation',
imageSequenceFrames: frameObjectKeys.map((objectKey) => ({
imageSrc: `/${objectKey}`,
objectKey,
width: 192,
height: 256,
})),
imageSequenceDurationMs: 500,
}}
token="admin-token"
onClose={vi.fn()}
/>,
);
const dialog = screen.getByRole('dialog', { name: '素材预览' });
fireEvent.click(within(dialog).getByRole('button', { name: '暂停角色动作' }));
await act(async () => {
await vi.advanceTimersByTimeAsync(120);
});
const initialFrames = Array.from(
dialog.querySelectorAll<HTMLImageElement>(
'.admin-asset-query-sequence-frame',
),
);
expect(initialFrames).toHaveLength(3);
initialFrames.forEach((frame) => fireEvent.load(frame));
fireEvent.click(within(dialog).getByRole('button', { name: '播放角色动作' }));
for (const elapsedMs of [100, 40, 60, 40, 60]) {
await act(async () => {
await vi.advanceTimersByTimeAsync(elapsedMs);
});
}
expect(getAdminAssetReadUrl).toHaveBeenCalledWith('admin-token', {
objectKey: frameObjectKeys[3],
expireSeconds: 300,
});
expect(resolveVisibleFrameSrc(dialog)).toBe(
`https://signed.example.com/${frameObjectKeys[2]}`,
);
await act(async () => {
delayedFrame.resolve({
read: {
objectKey: frameObjectKeys[3],
signedUrl: `https://signed.example.com/${frameObjectKeys[3]}`,
expiresAt: '2026-07-04T11:00:00Z',
},
});
await Promise.resolve();
});
const fourthFrame = resolveFrameByObjectKey(dialog, frameObjectKeys[3]);
expect(fourthFrame?.style.opacity).toBe('0');
expect(resolveVisibleFrameSrc(dialog)).toBe(
`https://signed.example.com/${frameObjectKeys[2]}`,
);
fireEvent.load(fourthFrame!);
fireEvent.load(resolveFrameByObjectKey(dialog, frameObjectKeys[4])!);
for (let index = 0; index < 3; index += 1) {
await act(async () => {
await vi.advanceTimersByTimeAsync(100);
});
}
expect(within(dialog).getByText('1/5')).toBeTruthy();
expect(resolveVisibleFrameSrc(dialog)).toBe(
`https://signed.example.com/${frameObjectKeys[0]}`,
);
expect(
vi
.mocked(getAdminAssetReadUrl)
.mock.calls.filter(
([, request]) => request.objectKey === frameObjectKeys[0],
),
).toHaveLength(1);
expect(
dialog.querySelectorAll('.admin-asset-query-sequence-frame').length,
).toBeLessThanOrEqual(3);
});
test('角色动作预览打开超过五分钟后回绕播放会在过期窗口内自动换签', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2099-01-01T00:00:00Z'));
const frameObjectKeys = Array.from(
{ length: 5 },
(_, index) => `generated-animations/editor/task-expiry/frame0${index}.png`,
);
const requestCounts = new Map<string, number>();
vi.mocked(getAdminAssetReadUrl).mockImplementation((_token, request) => {
const objectKey = request.objectKey ?? '';
const requestCount = (requestCounts.get(objectKey) ?? 0) + 1;
requestCounts.set(objectKey, requestCount);
return Promise.resolve({
read: {
objectKey,
signedUrl: `https://signed.example.com/v${requestCount}/${objectKey}`,
expiresAt:
requestCount === 1 ? '2099-01-01T00:05:00Z' : '2099-01-01T00:10:00Z',
},
});
});
render(
<AdminEditorAssetPreviewDialog
entry={{
assetId: 'asset-character-animation-expiry',
label: '过期换签动作',
imageSrc: `/${frameObjectKeys[0]}`,
objectKey: frameObjectKeys[0],
assetKind: 'character-animation',
imageSequenceFrames: frameObjectKeys.map((objectKey) => ({
imageSrc: `/${objectKey}`,
objectKey,
width: 192,
height: 256,
})),
imageSequenceDurationMs: 5_000,
}}
token="admin-token"
onClose={vi.fn()}
/>,
);
const dialog = screen.getByRole('dialog', { name: '素材预览' });
fireEvent.click(within(dialog).getByRole('button', { name: '暂停角色动作' }));
await act(async () => {
await vi.advanceTimersByTimeAsync(120);
});
loadMountedFrames(dialog);
for (let index = 0; index < frameObjectKeys.length; index += 1) {
fireEvent.click(
within(dialog).getByRole('button', { name: '播放角色动作' }),
);
await act(async () => {
await vi.advanceTimersByTimeAsync(1_000);
});
fireEvent.click(
within(dialog).getByRole('button', { name: '暂停角色动作' }),
);
await act(async () => {
await vi.advanceTimersByTimeAsync(120);
});
loadMountedFrames(dialog);
}
expect(within(dialog).getByText('1/5')).toBeTruthy();
frameObjectKeys.forEach((objectKey) => {
expect(requestCounts.get(objectKey)).toBe(1);
});
await act(async () => {
await vi.advanceTimersByTimeAsync(300_001);
});
loadMountedFrames(dialog);
expect(resolveVisibleFrameSrc(dialog)).toContain('/v2/');
for (let index = 0; index < frameObjectKeys.length; index += 1) {
fireEvent.click(
within(dialog).getByRole('button', { name: '播放角色动作' }),
);
await act(async () => {
await vi.advanceTimersByTimeAsync(1_000);
});
fireEvent.click(
within(dialog).getByRole('button', { name: '暂停角色动作' }),
);
await act(async () => {
await vi.advanceTimersByTimeAsync(120);
});
loadMountedFrames(dialog);
}
expect(within(dialog).getByText('1/5')).toBeTruthy();
expect(resolveVisibleFrameSrc(dialog)).toBe(
`https://signed.example.com/v2/${frameObjectKeys[0]}`,
);
frameObjectKeys.forEach((objectKey) => {
expect(requestCounts.get(objectKey)).toBe(2);
});
expect(within(dialog).queryByText(/帧加载失败/u)).toBeNull();
});
test('角色动作预览提前换签失败时保留已就绪帧并有限重试', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2099-01-01T00:00:00Z'));
const frameObjectKeys = [
'generated-animations/editor/task-refresh-failure/frame00.png',
'generated-animations/editor/task-refresh-failure/frame01.png',
] as const;
const requestCounts = new Map<string, number>();
vi.mocked(getAdminAssetReadUrl).mockImplementation((_token, request) => {
const objectKey = request.objectKey ?? '';
const requestCount = (requestCounts.get(objectKey) ?? 0) + 1;
requestCounts.set(objectKey, requestCount);
if (objectKey === frameObjectKeys[0] && requestCount > 1) {
return Promise.reject(new Error('refresh unavailable'));
}
return Promise.resolve({
read: {
objectKey,
signedUrl: `https://signed.example.com/v${requestCount}/${objectKey}`,
expiresAt:
requestCount === 1 ? '2099-01-01T00:05:00Z' : '2099-01-01T00:10:00Z',
},
});
});
render(
<AdminEditorAssetPreviewDialog
entry={{
assetId: 'asset-character-animation-refresh-failure',
label: '换签失败动作',
imageSrc: `/${frameObjectKeys[0]}`,
objectKey: frameObjectKeys[0],
assetKind: 'character-animation',
imageSequenceFrames: frameObjectKeys.map((objectKey) => ({
imageSrc: `/${objectKey}`,
objectKey,
width: 192,
height: 256,
})),
imageSequenceDurationMs: 2_000,
}}
token="admin-token"
onClose={vi.fn()}
/>,
);
const dialog = screen.getByRole('dialog', { name: '素材预览' });
fireEvent.click(within(dialog).getByRole('button', { name: '暂停角色动作' }));
await act(async () => {
await vi.advanceTimersByTimeAsync(120);
});
loadMountedFrames(dialog);
const readyFrameSrc = resolveVisibleFrameSrc(dialog);
expect(readyFrameSrc).toBe(
`https://signed.example.com/v1/${frameObjectKeys[0]}`,
);
await act(async () => {
await vi.advanceTimersByTimeAsync(270_100);
});
expect(resolveVisibleFrameSrc(dialog)).toBe(readyFrameSrc);
expect(within(dialog).queryByText(/帧加载失败/u)).toBeNull();
for (const retryWindowMs of [450, 1_250, 3_050]) {
await act(async () => {
await vi.advanceTimersByTimeAsync(retryWindowMs);
});
expect(resolveVisibleFrameSrc(dialog)).toBe(readyFrameSrc);
}
expect(requestCounts.get(frameObjectKeys[0])).toBe(5);
expect(within(dialog).queryByText(/帧加载失败/u)).toBeNull();
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000);
});
expect(requestCounts.get(frameObjectKeys[0])).toBe(5);
expect(resolveVisibleFrameSrc(dialog)).toBe(readyFrameSrc);
});
function loadMountedFrames(dialog: HTMLElement) {
dialog
.querySelectorAll<HTMLImageElement>('.admin-asset-query-sequence-frame')
.forEach((frame) => fireEvent.load(frame));
}
function resolveFrameByObjectKey(dialog: HTMLElement, objectKey: string) {
return Array.from(
dialog.querySelectorAll<HTMLImageElement>(
'.admin-asset-query-sequence-frame',
),
).find((frame) => frame.src.endsWith(objectKey));
}
function resolveVisibleFrameSrc(dialog: HTMLElement) {
return Array.from(
dialog.querySelectorAll<HTMLImageElement>(
'.admin-asset-query-sequence-frame',
),
).find((frame) => frame.style.opacity === '1')?.src;
}
File diff suppressed because it is too large Load Diff
@@ -1068,7 +1068,7 @@ test('后台素材查询点击图片缩略图可打开放大预览', async () =>
});
});
test('后台素材查询将角色动画首帧 PNG 作为图片预览', async () => {
test('后台素材查询在现有预览弹窗播放完整角色动作序列', async () => {
const user = userEvent.setup();
vi.mocked(listAdminEditorAssets).mockResolvedValueOnce({
entries: [
@@ -1081,17 +1081,65 @@ test('后台素材查询将角色动画首帧 PNG 作为图片预览', async ()
assetKind: 'character-animation',
thumbnailSrc:
'/generated-animations/editor/source-1/task-1/frame00.png',
imageSequenceFrames: [
{
imageSrc:
'/generated-animations/editor/source-1/task-1/frame00.png',
objectKey:
'generated-animations/editor/source-1/task-1/frame00.png',
width: 192,
height: 256,
},
{
imageSrc:
'/generated-animations/editor/source-1/task-1/frame01.png',
objectKey:
'generated-animations/editor/source-1/task-1/frame01.png',
width: 192,
height: 256,
},
{
imageSrc:
'/generated-animations/editor/source-1/task-1/frame02.png',
objectKey:
'generated-animations/editor/source-1/task-1/frame02.png',
width: 192,
height: 256,
},
{
imageSrc:
'/generated-animations/editor/source-1/task-1/frame03.png',
objectKey:
'generated-animations/editor/source-1/task-1/frame03.png',
width: 192,
height: 256,
},
{
imageSrc:
'/generated-animations/editor/source-1/task-1/frame04.png',
objectKey:
'generated-animations/editor/source-1/task-1/frame04.png',
width: 192,
height: 256,
},
],
imageSequenceDurationMs: 250,
},
],
nextCursor: null,
});
vi.mocked(getAdminAssetReadUrl).mockResolvedValue({
read: {
objectKey: 'generated-animations/editor/source-1/task-1/frame00.png',
signedUrl: 'https://signed.example.com/character-animation-frame00.png',
expiresAt: '2026-07-04T11:00:00Z',
vi.mocked(getAdminAssetReadUrl).mockImplementation(
async (_token, request) => {
const objectKey = request.objectKey ?? undefined;
return {
read: {
objectKey,
signedUrl: `https://signed.example.com/${objectKey ?? ''}`,
expiresAt: '2099-01-01T00:05:00Z',
},
};
},
});
);
render(
<AdminEditorAssetQueryPage token="admin-token" onUnauthorized={vi.fn()} />,
@@ -1102,15 +1150,56 @@ test('后台素材查询将角色动画首帧 PNG 作为图片预览', async ()
);
const dialog = await screen.findByRole('dialog', { name: '素材预览' });
const image = await within(dialog).findByRole('img', {
name: '图片预览:角色动作首帧',
});
await user.click(
await within(dialog).findByRole('button', {
name: '暂停角色动作',
}),
);
await waitFor(() => {
expect(image.getAttribute('src')).toBe(
'https://signed.example.com/character-animation-frame00.png',
expect(
dialog.querySelectorAll('.admin-asset-query-sequence-frame'),
).toHaveLength(3);
});
expect(getAdminAssetReadUrl).toHaveBeenCalledWith('admin-token', {
objectKey: 'generated-animations/editor/source-1/task-1/frame00.png',
expireSeconds: 300,
});
expect(getAdminAssetReadUrl).toHaveBeenCalledWith('admin-token', {
objectKey: 'generated-animations/editor/source-1/task-1/frame01.png',
expireSeconds: 300,
});
expect(getAdminAssetReadUrl).toHaveBeenCalledWith('admin-token', {
objectKey: 'generated-animations/editor/source-1/task-1/frame02.png',
expireSeconds: 300,
});
expect(getAdminAssetReadUrl).not.toHaveBeenCalledWith('admin-token', {
objectKey: 'generated-animations/editor/source-1/task-1/frame03.png',
expireSeconds: 300,
});
const failedFrame = dialog.querySelector(
'.admin-asset-query-sequence-frame',
) as HTMLImageElement;
fireEvent.error(failedFrame);
expect(await within(dialog).findByText('1 帧加载失败')).toBeTruthy();
await waitFor(() => {
expect(getAdminAssetReadUrl).toHaveBeenCalledWith('admin-token', {
objectKey: 'generated-animations/editor/source-1/task-1/frame03.png',
expireSeconds: 300,
});
});
const callsBeforeRetry = vi.mocked(getAdminAssetReadUrl).mock.calls.length;
await user.click(
within(dialog).getByRole('button', { name: '重试失败帧' }),
);
await waitFor(() => {
expect(vi.mocked(getAdminAssetReadUrl).mock.calls.length).toBeGreaterThan(
callsBeforeRetry,
);
});
expect(within(dialog).queryByLabelText('视频预览:角色动作首帧')).toBeNull();
expect(
within(dialog).getByRole('button', { name: '暂停角色动作' }),
).toBeTruthy();
});
test('后台素材查询音频素材使用统一封面缩略图', async () => {
@@ -318,6 +318,101 @@ test('后台精选审核缩略图进入视口后换签并可打开图片预览',
expect(screen.queryByRole('dialog', { name: '精选素材详情' })).toBeNull();
});
test('后台精选审核在共用预览弹窗播放完整角色动作', async () => {
vi.mocked(listAdminEditorShowcaseAssets).mockResolvedValueOnce({
entries: [
{
...pendingShowcaseAsset,
label: '待机动作',
assetKind: 'character-animation',
imageSrc: '/generated/action/frame-01.png',
objectKey: 'generated/action/frame-01.png',
imageSequenceFrames: [
{
imageSrc: '/generated/action/frame-01.png',
objectKey: 'generated/action/frame-01.png',
width: 192,
height: 256,
},
{
imageSrc: '/generated/action/frame-02.png',
objectKey: 'generated/action/frame-02.png',
width: 192,
height: 256,
},
],
imageSequenceDurationMs: 250,
},
],
nextCursor: null,
});
vi.mocked(getAdminAssetReadUrl).mockImplementation(
async (_token, request) => {
const objectKey = request.objectKey ?? undefined;
return {
read: {
objectKey,
signedUrl: `https://signed.example.com/${objectKey ?? ''}`,
expiresAt: '2099-01-01T00:05:00Z',
},
};
},
);
render(
<AdminEditorShowcaseReviewPage
token="admin-token"
onUnauthorized={vi.fn()}
/>,
);
fireEvent.click(await screen.findByTitle('预览素材'));
const dialog = await screen.findByRole('dialog', { name: '素材预览' });
expect(
await within(dialog).findByRole('button', { name: '暂停角色动作' }),
).toBeTruthy();
await waitFor(() => {
expect(
dialog.querySelectorAll('.admin-asset-query-sequence-frame'),
).toHaveLength(2);
});
expect(getAdminAssetReadUrl).toHaveBeenCalledWith('admin-token', {
objectKey: 'generated/action/frame-02.png',
expireSeconds: 300,
});
});
test('后台精选审核对损坏角色动作显示错误而不回退首帧', async () => {
vi.mocked(listAdminEditorShowcaseAssets).mockResolvedValueOnce({
entries: [
{
...pendingShowcaseAsset,
label: '损坏动作',
assetKind: 'character-animation',
imageSequenceFrames: null,
imageSequenceDurationMs: null,
},
],
nextCursor: null,
});
render(
<AdminEditorShowcaseReviewPage
token="admin-token"
onUnauthorized={vi.fn()}
/>,
);
fireEvent.click(await screen.findByTitle('预览素材'));
const dialog = await screen.findByRole('dialog', { name: '素材预览' });
expect(
within(dialog).getByLabelText('角色动作序列损坏:损坏动作'),
).toBeTruthy();
expect(
within(dialog).queryByRole('img', { name: '图片预览:损坏动作' }),
).toBeNull();
});
test('后台精选审核将无 objectKey 的绝对 OSS 图片地址换签后预览', async () => {
vi.mocked(listAdminEditorShowcaseAssets).mockResolvedValueOnce({
entries: [
+52
View File
@@ -1703,6 +1703,58 @@ button:disabled {
object-fit: contain;
}
.admin-asset-query-sequence-preview {
position: relative;
width: min(100%, 720px);
min-height: min(64dvh, 560px);
overflow: hidden;
}
.admin-asset-query-sequence-frame {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
object-fit: contain;
object-position: center;
}
.admin-asset-query-sequence-controls {
position: absolute;
right: 12px;
bottom: 12px;
z-index: 2;
display: flex;
max-width: calc(100% - 24px);
flex-wrap: wrap;
align-items: center;
gap: 8px;
border-radius: 999px;
background: rgba(43, 31, 22, 0.82);
color: #fff;
padding: 6px 10px;
font-size: 12px;
}
.admin-asset-query-sequence-controls button {
display: grid;
min-width: 44px;
min-height: 44px;
border: 0;
background: transparent;
color: inherit;
cursor: pointer;
padding: 0;
place-items: center;
}
.admin-asset-query-sequence-error {
display: grid;
color: #9d3127;
place-items: center;
}
.admin-asset-query-preview-audio {
display: grid;
justify-items: center;
@@ -62,6 +62,14 @@ const viteConfigSource = fs.readFileSync(
new URL('../vite.config.ts', import.meta.url),
'utf8',
);
const devPortSource = fs.readFileSync(
new URL('../scripts/dev-port.mjs', import.meta.url),
'utf8',
);
const startTauriDevSource = fs.readFileSync(
new URL('../scripts/start-tauri-dev.mjs', import.meta.url),
'utf8',
);
const appSource = [
readSourceTree(new URL('../src/', import.meta.url), '.ts'),
readSourceTree(new URL('../src/', import.meta.url), '.tsx'),
@@ -1217,7 +1225,7 @@ if (
if (tauriConfig.build?.devUrl !== 'http://127.0.0.1:3080/') {
throw new Error(
'AI game creator shell Tauri devUrl must stay on the fixed Vite dev port',
'AI game creator shell Tauri config must retain the non-launcher fallback devUrl',
);
}
@@ -1227,12 +1235,41 @@ if (!viteConfigSource.includes("host: '127.0.0.1'")) {
);
}
if (!viteConfigSource.includes('port: 3080')) {
if (
!viteConfigSource.includes('port: 3080') ||
!viteConfigSource.includes('port: server.config.server.port')
) {
throw new Error(
'AI game creator shell Vite dev port must match Tauri devUrl',
'AI game creator shell Vite config must retain its fallback and report the actual CLI-selected port',
);
}
for (const snippet of [
'mapDevPortsToPortRange',
'agcVitePort',
'resolveAgcDevEndpoint',
'GENARRATIVE_AGC_VITE_PORT',
]) {
if (!devPortSource.includes(snippet)) {
throw new Error(
`AI game creator shell dev port resolver drifted: ${snippet}`,
);
}
}
for (const snippet of [
'resolveAgcDevEndpoint',
'withAgcDevEndpointEnv',
"'--config'",
'configOverride',
]) {
if (!startTauriDevSource.includes(snippet)) {
throw new Error(
`AI game creator shell Tauri dev port injection drifted: ${snippet}`,
);
}
}
if (!viteConfigSource.includes('strictPort: true')) {
throw new Error(
'AI game creator shell Vite dev server must not drift away from Tauri devUrl',
@@ -1253,7 +1290,7 @@ if (
)
) {
throw new Error(
'AI game creator shell beforeDevCommand must reuse or start the fixed Vite dev server',
'AI game creator shell beforeDevCommand must start the selected Vite dev server',
);
}
@@ -1463,12 +1500,15 @@ if (
}
for (const snippet of [
'const port = 3080',
'resolveAgcDevEndpoint',
'withAgcDevEndpointEnv',
"response.body.includes('<title>AI 游戏创作</title>')",
'function isPortListening()',
'reuse existing Vite dev server',
'cannot be safely reused',
'non-HTTP or unrecognized server',
"'--config', 'vite.config.ts'",
"'--config'",
"'vite.config.ts'",
"'--port'",
]) {
if (!devServerSource.includes(snippet)) {
throw new Error(
@@ -0,0 +1,111 @@
import {
findAvailablePort,
formatPortDecision,
mapDevPortsToPortRange,
normalizePort,
reserveLinuxDevPortRange,
} from '../../../scripts/dev-stack-port-utils.mjs';
const agcDevHost = '127.0.0.1';
const legacyAgcDevPort = 3080;
const agcVitePortEnvKey = 'GENARRATIVE_AGC_VITE_PORT';
function readConfiguredAgcDevPort(env = process.env) {
const rawPort = String(env[agcVitePortEnvKey] ?? '').trim();
if (!rawPort) {
return null;
}
const port = normalizePort(rawPort, -1);
if (port < 1024) {
throw new Error(`${agcVitePortEnvKey} 必须是 1024-65535 的有效端口`);
}
return port;
}
function createAgcDevEndpoint(port, portRange = null) {
const url = `http://${agcDevHost}:${port}/`;
return {
host: agcDevHost,
port,
url,
markerUrl: `${url}__agc_dev_server.json`,
portRange,
};
}
function readAgcDevEndpoint(env = process.env) {
return createAgcDevEndpoint(
readConfiguredAgcDevPort(env) ?? legacyAgcDevPort,
);
}
async function resolveAgcDevEndpoint({
env = process.env,
platform = process.platform,
strictConfigured = false,
reservePortRange = reserveLinuxDevPortRange,
findPort = findAvailablePort,
} = {}) {
const configuredPort = readConfiguredAgcDevPort(env);
let portRange = null;
let preferredPort = configuredPort ?? legacyAgcDevPort;
if (platform === 'linux') {
const allocation = await reservePortRange({ env });
if (!allocation?.range) {
throw new Error('无法取得当前 Linux 用户的 dev 端口段');
}
portRange = allocation.range;
const mappedAgcVitePort = mapDevPortsToPortRange(portRange)?.agcVitePort;
if (!Number.isInteger(mappedAgcVitePort)) {
throw new Error(
`当前 Linux dev 端口段 ${portRange.label} 缺少 AGC Vite 槽位;请先迁移为至少 6 个端口且不与其它用户重叠的端口段`,
);
}
if (configuredPort != null && configuredPort < mappedAgcVitePort) {
throw new Error(
`${agcVitePortEnvKey} ${configuredPort} 占用了 Linux dev 端口段 ${portRange.label} 的前五个服务槽位`,
);
}
preferredPort = configuredPort ?? mappedAgcVitePort;
}
const port = await findPort({
host: agcDevHost,
preferredPort,
portRange,
strict: strictConfigured && configuredPort != null,
});
console.log(
formatPortDecision({
name: 'ai-game-creator-shell',
host: agcDevHost,
preferredPort,
resolvedPort: port,
}),
);
if (portRange) {
console.log(`[ai-game-creator-shell] dev port-range: ${portRange.label}`);
}
return createAgcDevEndpoint(port, portRange);
}
function withAgcDevEndpointEnv(endpoint, env = process.env) {
return {
...env,
[agcVitePortEnvKey]: String(endpoint.port),
};
}
export {
agcDevHost,
agcVitePortEnvKey,
createAgcDevEndpoint,
legacyAgcDevPort,
readAgcDevEndpoint,
readConfiguredAgcDevPort,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
};
@@ -3,10 +3,11 @@ import http from 'node:http';
import net from 'node:net';
import { fileURLToPath } from 'node:url';
import { resolveAgcDevEndpoint, withAgcDevEndpointEnv } from './dev-port.mjs';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
const host = '127.0.0.1';
const port = 3080;
const devUrl = `http://${host}:${port}/`;
const endpoint = await resolveAgcDevEndpoint();
const { host, port, url: devUrl } = endpoint;
function readExistingServer() {
return new Promise((resolve) => {
@@ -69,8 +70,10 @@ function isPortListening() {
const existing = await readExistingServer();
if (existing) {
if (isAiGameCreatorServer(existing)) {
console.log(`[ai-game-creator-shell] reuse existing Vite dev server ${devUrl}`);
process.exit(0);
console.error(
`[ai-game-creator-shell] ${devUrl} is already running but cannot be safely reused. Stop that process before starting the dev server.`,
);
process.exit(1);
}
console.error(
`[ai-game-creator-shell] ${devUrl} is already in use by another server. Stop that process before starting Tauri dev.`,
@@ -88,9 +91,20 @@ if (await isPortListening()) {
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const child = spawn(
npm,
['--prefix', '../..', 'exec', 'vite', '--', '--config', 'vite.config.ts'],
[
'--prefix',
'../..',
'exec',
'vite',
'--',
'--config',
'vite.config.ts',
'--port',
String(endpoint.port),
],
{
cwd: appRoot,
env: withAgcDevEndpointEnv(endpoint),
stdio: 'inherit',
// Node 18.20+/20+/24 on Windows rejects spawning .cmd (npm.cmd) without a shell (EINVAL).
shell: true,
@@ -5,13 +5,16 @@ import net from 'node:net';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
agcVitePortEnvKey,
readAgcDevEndpoint,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
} from './dev-port.mjs';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
const repoRoot = resolve(appRoot, '../..');
const devStackStatePath = resolve(repoRoot, '.app/dev-stack.json');
const viteHost = '127.0.0.1';
const vitePort = 3080;
const viteUrl = `http://${viteHost}:${vitePort}/`;
const viteMarkerUrl = `${viteUrl}__agc_dev_server.json`;
const defaultApiTarget =
process.env.RUST_SERVER_TARGET || 'http://127.0.0.1:8082';
const backendDatabase = 'genarrative-game-creator-dev';
@@ -131,13 +134,13 @@ async function isBackendReady() {
);
}
async function readExistingViteServer() {
return httpGetText(viteUrl);
async function readExistingViteServer(endpoint = readAgcDevEndpoint()) {
return httpGetText(endpoint.url);
}
function isVitePortListening() {
function isVitePortListening(endpoint = readAgcDevEndpoint()) {
return new Promise((resolveRequest) => {
const socket = net.connect({ host: viteHost, port: vitePort });
const socket = net.connect({ host: endpoint.host, port: endpoint.port });
socket.once('connect', () => {
socket.destroy();
resolveRequest(true);
@@ -160,8 +163,8 @@ function isAiGameCreatorServer(response) {
);
}
async function readExistingViteMarker() {
const response = await httpGetText(viteMarkerUrl, 2000);
async function readExistingViteMarker(endpoint = readAgcDevEndpoint()) {
const response = await httpGetText(endpoint.markerUrl, 2000);
if (!response || response.statusCode !== 200) {
return null;
}
@@ -173,15 +176,16 @@ async function readExistingViteMarker() {
}
async function preflightExistingVite({
endpoint = readAgcDevEndpoint(),
readServer = readExistingViteServer,
portListening = isVitePortListening,
readMarker = readExistingViteMarker,
} = {}) {
const existing = await readServer();
const existing = await readServer(endpoint);
if (!existing) {
if (await portListening()) {
if (await portListening(endpoint)) {
throw new Error(
`${viteUrl} is already in use by a non-HTTP or unrecognized server. Stop it before starting Tauri dev.`,
`${endpoint.url} is already in use by a non-HTTP or unrecognized server. Stop it before starting Tauri dev.`,
);
}
return { status: 'available', apiTarget: '' };
@@ -189,11 +193,11 @@ async function preflightExistingVite({
if (!isAiGameCreatorServer(existing)) {
throw new Error(
`${viteUrl} is already in use by another server. Stop it before starting Tauri dev.`,
`${endpoint.url} is already in use by another server. Stop it before starting Tauri dev.`,
);
}
const marker = await readMarker();
const marker = await readMarker(endpoint);
const markerApiTarget =
marker?.schemaVersion === 1 &&
marker?.app === 'ai-game-creator-shell' &&
@@ -202,7 +206,7 @@ async function preflightExistingVite({
: '';
const actualTarget = markerApiTarget || 'unknown';
throw new Error(
`${viteUrl} is already running with API target ${actualTarget}. Its owning worktree cannot be proven, so it will not be reused. Stop that Vite dev server before starting Tauri dev.`,
`${endpoint.url} is already running with API target ${actualTarget}. Its owning worktree cannot be proven, so it will not be reused. Stop that Vite dev server before starting Tauri dev.`,
);
}
@@ -549,7 +553,7 @@ async function ensureBackend({
}
}
async function startVite(apiTarget) {
async function startVite(apiTarget, endpoint = readAgcDevEndpoint()) {
const { apiUrl } = readBackendTargets();
if (apiUrl !== apiTarget) {
throw new Error(
@@ -557,22 +561,32 @@ async function startVite(apiTarget) {
);
}
const existing = await readExistingViteServer();
const existing = await readExistingViteServer(endpoint);
if (existing) {
if (isAiGameCreatorServer(existing)) {
throw new Error(
`${viteUrl} is already running and cannot be safely reused. Stop it before starting Tauri dev.`,
`${endpoint.url} is already running and cannot be safely reused. Stop it before starting Tauri dev.`,
);
}
throw new Error(
`${viteUrl} is already in use by another server. Stop it before starting Tauri dev.`,
`${endpoint.url} is already in use by another server. Stop it before starting Tauri dev.`,
);
}
return spawnChild(
npm,
['--prefix', '../..', 'exec', 'vite', '--', '--config', 'vite.config.ts'],
{ cwd: appRoot },
[
'--prefix',
'../..',
'exec',
'vite',
'--',
'--config',
'vite.config.ts',
'--port',
String(endpoint.port),
],
{ cwd: appRoot, env: withAgcDevEndpointEnv(endpoint) },
);
}
@@ -593,7 +607,9 @@ async function main() {
}
try {
await preflightExistingVite();
const endpoint = await resolveAgcDevEndpoint({ strictConfigured: true });
process.env[agcVitePortEnvKey] = String(endpoint.port);
await preflightExistingVite({ endpoint });
const backend = await ensureBackend({
onBackendChild(child) {
backendChild = child;
@@ -607,7 +623,7 @@ async function main() {
throw new Error(`启动期收到 ${shutdownSignal},已停止配套后端`);
}
viteChild = await startVite(backend.targets.apiUrl);
viteChild = await startVite(backend.targets.apiUrl, endpoint);
if (shutdownSignal) {
stopChild(viteChild, shutdownSignal);
throw new Error(`启动期收到 ${shutdownSignal},已停止前端服务`);
@@ -1,6 +1,11 @@
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
readAgcDevEndpoint,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
} from './dev-port.mjs';
import {
preflightExistingVite,
spawnChild,
@@ -22,17 +27,37 @@ function parseLauncherArguments(argv) {
return { gameChat, args };
}
function buildTauriArguments(argv) {
function buildTauriArguments(argv, devUrl = readAgcDevEndpoint().url) {
const { gameChat, args } = parseLauncherArguments(argv);
const configOverride = JSON.stringify({ build: { devUrl } });
if (gameChat) {
return ['dev', '--', '--', '--game-chat', ...args];
return [
'dev',
'--config',
configOverride,
'--',
'--',
'--game-chat',
...args,
];
}
return ['dev', ...args];
const separatorIndex = args.indexOf('--');
if (separatorIndex < 0) {
return ['dev', ...args, '--config', configOverride];
}
return [
'dev',
...args.slice(0, separatorIndex),
'--config',
configOverride,
...args.slice(separatorIndex),
];
}
function spawnTauriCli(argv) {
function spawnTauriCli(argv, { env = process.env } = {}) {
return spawnChild(process.execPath, [tauriCliPath, ...argv], {
cwd: appRoot,
env,
shell: false,
});
}
@@ -40,16 +65,20 @@ function spawnTauriCli(argv) {
async function runTauriDev(
argv = process.argv.slice(2),
{
resolveDevEndpoint = resolveAgcDevEndpoint,
preflight = preflightExistingVite,
spawnCli = spawnTauriCli,
waitForCli = waitForChildTermination,
terminateTree = terminateChildTree,
} = {},
) {
await preflight();
const endpoint = await resolveDevEndpoint();
await preflight({ endpoint });
const tauriArguments = buildTauriArguments(argv);
const child = spawnCli(tauriArguments);
const tauriArguments = buildTauriArguments(argv, endpoint.url);
const child = spawnCli(tauriArguments, {
env: withAgcDevEndpointEnv(endpoint),
});
let resolveShutdown;
let shutdownSignal = '';
let repeatedSignal = false;
+1
View File
@@ -4570,6 +4570,7 @@ version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"sha2",
]
[[package]]
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "genarrative.agent-runtime",
"version": "2026-08-06.1",
"version": "2026-08-07.2",
"sections": {
"common": "common.md",
"isolatedTemplateCatalogIntro": "isolated-template-catalog-intro.md",
@@ -9,7 +9,6 @@
"platformDefault": "platform/default.md",
"platformLinux": "platform/linux.md",
"codePrototypeGameChat": "roles/code-prototype-game-chat.md",
"codeDirectorGameChatAssetAudit": "roles/code-director-game-chat-asset-audit.md",
"projectSupervisorGameChatRouting": "supervisor/game-chat-routing.md",
"providerIsolatedToolContract": "provider/isolated-tool-contract.md",
"providerAutonomousRunProfile": "provider/autonomous-run-profile.md",
@@ -67,11 +66,6 @@
"rootSourceKind": "supervisorGameChat",
"sections": ["projectSupervisorGameChatRouting"]
},
{
"agentId": "code-director",
"rootSourceKind": "supervisorGameChat",
"sections": ["codeDirectorGameChatAssetAudit"]
},
{
"agentId": "code-prototype",
"rootSourceKind": "supervisorGameChat",
@@ -1 +1 @@
本次修复的原生工具目录只保留 agent.delegate。必须在同一响应一次性建立完整首批合同,且只允许以下三个非 repair 委派,各出现一次:design-director 与 code-director 的 task 或 acceptanceCriteria 必须显式声明只读且不得修改项目,expectedArtifacts 必须为 [];art-director 必须是非只读规范图生成任务,expectedArtifacts 必须包含 assets/art-spec.png。三者都必须提供非空 task、1-8 条 acceptanceCriteria,并设置 repairOfDelegationId=null、runId=null。不得委派 code-prototype、quality-review、design-foundation、art-asset-plan 或其它底层 Agent,不得调用 agent.spawn_isolated,不得更新计划、读取、搜索、查询状态、修改项目或返回最终回复。不要解释,不要 markdown,不要代码围栏。
本片段只适用于普通 GUI / CLI 的完整 `autonomous-game-build` manifest DAG;不得用于持久 source 为 `project-supervisor-game-chat` 的单主 route,后者不得用此修复建立固定首批委派。普通 DAG 的本次修复原生工具目录只保留 agent.delegate。必须在同一响应一次性建立完整首批合同,且只允许以下三个非 repair 委派,各出现一次:design-director 与 code-director 的 task 或 acceptanceCriteria 必须显式声明只读且不得修改项目,expectedArtifacts 必须为 [];art-director 必须是非只读规范图生成任务,expectedArtifacts 必须包含 assets/art-spec.png。三者都必须提供非空 task、1-8 条 acceptanceCriteria,并设置 repairOfDelegationId=null、runId=null。不得委派 code-prototype、quality-review、design-foundation、art-asset-plan 或其它底层 Agent,不得调用 agent.spawn_isolated,不得更新计划、读取、搜索、查询状态、修改项目或返回最终回复。不要解释,不要 markdown,不要代码围栏。
@@ -1 +1 @@
autonomous-game-build 的正式 manifest 任务图是唯一首轮专业执行链。不得在 manifest 之前另行创建 code-prototype、quality-review、art-director、design-foundation 或 art-asset-plan 的首批 agent.delegate;这些角色会由 Runtime 按 manifest 依赖顺序调度。没有待认领的显式返工合同时也不得额外委派。请直接推进/观察 manifest,Runtime 会在你尝试收束时调度 ready task,并在任务图完成前阻止最终交付。
本片段只适用于普通 GUI / CLI 的完整 `autonomous-game-build` manifest DAG,不适用于持久 source 为 `project-supervisor-game-chat` 的单主 route。普通 DAG 中,正式 manifest 任务图是唯一首轮专业执行链:不得在 manifest 之前另行创建 code-prototype、quality-review、art-director、design-foundation 或 art-asset-plan 的首批 agent.delegate;这些角色会由 Runtime 按 manifest 依赖顺序调度。没有待认领的显式返工合同时也不得额外委派。game-chat 则由其专用路由提示决定:Supervisor 持久化意图后只启动 code-prototype,只有该主 Agent 的 asset.list 审计证实真实缺口时才可委派受限美术 child。请直接推进/观察适用于当前 root source 的任务路径;Runtime 会在你尝试收束时调度 ready task,并在任务图完成前阻止最终交付。
@@ -1 +0,0 @@
game-chat 的 code-director 是程序侧资产审计节点。第一步必须调用 `asset.list` 核对当前正式资产、Canvas 登记和可复用状态;不得生成图片、修改游戏或只凭用户措辞猜测缺口。取得 asset.list observation 后,本轮必须调用 `agent.route_manifest` 提交结构化结果:Supervisor 选择 audit-existing-first 且没有缺口时使用 `strategy=use-existing-art, missingAssetSlots=[]`;存在缺口时使用 `strategy=generate-missing-art`,missingAssetSlots 只能精确列出 `art-spec`、`core-spritesheet` 中实际缺失项;Supervisor 选择 regenerate-art 时使用 `strategy=regenerate-art, missingAssetSlots=["art-spec","core-spritesheet"]`。Runtime 会复核权威资产状态,拒绝遗漏、虚构、过期或重复缺口。路由成功后再交付只读审计结论;美术补齐后由同一根 Run 恢复 code-prototype。
@@ -1,3 +1,5 @@
game-chat 使用素材完整快车道。必须先保护既有游戏语义和已完成产物:如果 observation 尚未包含 game/index.html 的当前正文与摘要,本响应第一步必须调用 file.read(path=game/index.html),不得猜测入口仍是初始化占位。只有文件缺失或正文与初始化页面一致、且当前 run 尚未写入项目时,才允许用一次 file.write 生成完整、自包含、可运行的 game/index.html;检测到非占位入口、已有可玩实现、当前 revision 已验证,或当前 run 已发生修改时,禁止整文件 file.write,必须保留原玩法,优先执行静态检查/试玩,确需修复时只能依据已读取的精确原文做最小 file.patch。不得把“继续”、continue 或其它纯续跑词当作游戏主题;缺少可继承的具体目标时必须失败关闭,不得另造新玩法。
game-chat 使用单主素材审计快车道。你是唯一的 `code-prototype` 主 Agent;必须先保护既有游戏语义和已完成产物。若本轮尚未取得成功的 `asset.list` observation,第一步必须调用 `asset.list` 核对当前正式资产、Canvas 登记和可复用状态;不得仅凭用户措辞、关键词或旧摘要判断已有素材是否可用。审计后必须用 `agent.route_manifest` 持久化审计结论:完整覆盖使用 `use-existing-art, missingAssetSlots=[]`,真实缺口使用 `generate-missing-art` 且只列出实际缺失槽位;不得把 Supervisor 的用户 intent 改写成重生成路线。审计证明核心规范图、透明 spritesheet、切片清单或四类切片存在真实缺口时,才可一次委派对应的 `art-director` 或 `art-asset-plan` 补齐;任务必须精确说明缺失项和验收产物,child 只能写 `assets/**`,不得修改 `game/**`、删除/补丁程序文件或替你接入游戏。一次最多保留一个活跃美术委派,收到并认领其回执后继续同一 Run;不得在美术已齐或仅凭“UI 没有用素材”等描述时生成、委派或扣费。Supervisor 持久化的整体重做意图也只是上下文,不能改变这条审计门或授权整套美术强制重生成。
HTML 必须满足固定试玩合同,包含真实 Canvas 游戏循环、键盘与触控输入、开始、主要操作、重开、胜负状态和移动端布局。assets/art-spec.png 只能作为视觉规范与派生参考,不得在运行时加载、铺作背景或裁切实体。必须等待已登记且透明有效的 assets/art-spritesheet.png 与 assets/art-spritesheet-slices/manifest.json,从切片清单按 player、blocks-and-targets、obstacles-and-scene、feedback-effects 四种 usage 加载四个不同的独立透明素材,并在活动 Canvas 中通过 drawImage 绘制对应核心玩家、方块/目标、障碍/场景和反馈;不得猜测整张图集是等分网格,不得把整张图集作为 img、CSS background 或完整 drawImage 展示,也不得以纯代码几何替代核心实体。图集、四类切片或其可见使用任一缺失时不得交付。首次实现或最小修复后不要继续扩写功能;Runtime 会自动执行静态自检并在通过后立即试玩。
在成功审计并取得可用素材、或已认领必要美术回执后,才读取游戏入口:如果 observation 尚未包含 game/index.html 的当前正文与摘要,本响应下一步必须调用 file.read(path=game/index.html),不得猜测入口仍是初始化占位。只有文件缺失或正文与初始化页面一致、且当前 run 尚未写入项目时,才允许用一次 file.write 生成完整、自包含、可运行的 game/index.html;检测到非占位入口、已有可玩实现、当前 revision 已验证,或当前 run 已发生修改时,禁止整文件 file.write,必须保留原玩法,优先执行静态检查/试玩,确需修复时只能依据已读取的精确原文做最小 file.patch。不得把“继续”、continue 或其它纯续跑词当作游戏主题;缺少可继承的具体目标时必须失败关闭,不得另造新玩法。
HTML 必须满足固定试玩合同,包含真实 Canvas 游戏循环、键盘与触控输入、开始、主要操作、重开、胜负状态和移动端布局。assets/art-spec.png 只能作为视觉规范与派生参考,不得在运行时加载、铺作背景或裁切实体。必须等待已登记且透明有效的 assets/art-spritesheet.png 与 assets/art-spritesheet-slices/manifest.json,从切片清单按 player、blocks-and-targets、obstacles-and-scene、feedback-effects 四种 usage 加载四个不同的独立透明素材,并在活动 Canvas 中通过 drawImage 绘制对应核心玩家、方块/目标、障碍/场景和反馈;不得猜测整张图集是等分网格,不得把整张图集作为 img、CSS background 或完整 drawImage 展示,也不得以纯代码几何替代核心实体。图集、四类切片或其可见使用任一缺失时不得交付。完成最后一处项目写入后,由你在同一 Run 执行 `game.static_smoke`,再执行 desktop 与 mobile `preview.validate`;不得把接入、检查或试玩交回固定验证节点。首次实现或最小修复后不要继续扩写功能。

Some files were not shown because too many files have changed in this diff Show More