Compare commits
4 Commits
2ebfd1cf55
...
1ca799c3e5
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ca799c3e5 | |||
| fc20c39519 | |||
| 4e04679ba4 | |||
| 9cb3c6a27e |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -26,3 +26,4 @@ temp*build*/
|
||||
/public/generated-animations
|
||||
/public/generated-character-drafts
|
||||
/public/generated-characters
|
||||
/target/
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# 拼图 Agent 操作回包收口说明
|
||||
|
||||
## 背景
|
||||
|
||||
拼图结果页在执行 `select_puzzle_image` 时,前端先调用 `POST /api/runtime/puzzle/agent/sessions/:sessionId/actions`,随后又调用 `GET /api/runtime/puzzle/agent/sessions/:sessionId` 拉取完整会话。完整会话包含消息、草稿与结果预览,体积明显大于一次选图操作本身,导致选择候选图时出现无意义流量与体感延迟。
|
||||
|
||||
## 落地规则
|
||||
|
||||
- `actions` 接口在服务端本来已经拿到变更后的 session,因此回包必须直接包含 `operation + session`。
|
||||
- 前端收到 `actions` 回包后直接用 `session` 更新本地状态,不再为了同步选图、生成图片或编译草稿而补发完整会话 `GET`。
|
||||
- `publish_puzzle_work` 发布后仍由服务端重新读取一次最新 session 并放入同一个 action response,前端只保留作品架与广场详情的必要刷新。
|
||||
- 该改动只收敛 Rust api-server 与前端 contract,不引入 server-node 兼容逻辑。
|
||||
|
||||
## 验收口径
|
||||
|
||||
1. 选择拼图候选图只产生一次 `POST /actions`,不再紧跟完整 session `GET`。
|
||||
2. 选图后结果页仍立即反映选中的正式图。
|
||||
3. 发布后仍能跳转到已发布拼图详情。
|
||||
@@ -0,0 +1,46 @@
|
||||
# 拼图与大鱼吃小鱼草稿生成进度页落地方案(2026-04-25)
|
||||
|
||||
## 背景
|
||||
|
||||
RPG 在点击生成草稿后会离开聊天工作区,进入独立的生成进度页,并在该页展示生成链路的阶段、锚点与最终草稿内容。拼图与大鱼吃小鱼此前点击“生成结果页”后直接跳到结果页,正式图片、动作与背景仍分散在结果页工坊里逐个生成,导致用户无法看到“正在一次性准备完整草稿”的过程。
|
||||
|
||||
## 落地边界
|
||||
|
||||
- 前端只负责展示生成进度与触发已有后端动作,不新增 server-node 或 PostgreSQL 链路。
|
||||
- 后端继续沿用 `server-rs` + SpacetimeDB 的会话、草稿与资产写入能力;“一次性生成所有需要的东西”必须由 `server-rs` 的 compile action 承担,前端只发起一次 action 并展示进度页。
|
||||
- 拼图生成草稿链路必须包含:结果页草稿、候选图生成、正式图确认。
|
||||
- 大鱼吃小鱼生成草稿链路必须包含:玩法草稿、关卡主图、动作素材、场地背景。
|
||||
- 生成过程中展示的“角色描述、角色图片、动作”等,统一映射为锚点、草稿蓝图与资产步骤,不把规则说明类文本写成默认 UI 文案。
|
||||
|
||||
## 交互设计
|
||||
|
||||
1. 用户在拼图或大鱼吃小鱼 Agent 工作区点击生成按钮。
|
||||
2. 页面立即切换到独立生成进度页,同时只向 `server-rs` 发起一次 compile action,返回按钮在生成中禁用,避免中途回退造成状态漂移。
|
||||
3. 进度页左侧展示阶段进度、步骤卡片与错误信息;右侧展示当前锚点与已成形的草稿结构。
|
||||
4. 全量生成成功后自动进入对应结果页,结果页直接展示已生成的资产。
|
||||
5. 生成失败时停留在进度页,用户可返回工作区补充设定,或点击重试重新执行完整草稿链路。
|
||||
|
||||
## 阶段映射
|
||||
|
||||
### 拼图
|
||||
|
||||
- `compile_puzzle_draft`:在 `server-rs` 内整理主题、主体、构图与标签,写入结果页草稿。
|
||||
- `compile_puzzle_draft`:同一次后端 action 内根据草稿摘要生成候选图。
|
||||
- `compile_puzzle_draft`:同一次后端 action 内自动选择第一张候选图作为正式图。
|
||||
- `ready`:进入拼图结果页。
|
||||
|
||||
### 大鱼吃小鱼
|
||||
|
||||
- `big_fish_compile_draft`:在 `server-rs` 内生成玩法草稿、关卡角色描述、背景蓝图与运行参数。
|
||||
- `big_fish_compile_draft`:同一次后端 action 内按每个关卡生成主角色/鱼群图片。
|
||||
- `big_fish_compile_draft`:同一次后端 action 内按每个关卡生成 `idle_float` 与 `move_swim` 动作素材。
|
||||
- `big_fish_compile_draft`:同一次后端 action 内生成玩法场地背景。
|
||||
- `ready`:进入大鱼吃小鱼结果页。
|
||||
|
||||
## 验收点
|
||||
|
||||
- 拼图和大鱼吃小鱼点击生成草稿后不再直接停留在聊天工作区等待。
|
||||
- 生成中可看到独立进度页,且进度步骤随 action 完成逐步推进。
|
||||
- 拼图结果页打开时已有正式图;大鱼结果页打开时主图、动作和背景资产均已写入 `assetSlots`。
|
||||
- 前端点击生成草稿时不串行调用多个资产 action;多阶段业务编排收敛在 `server-rs`。
|
||||
- 不新增 server-node 依赖,不复活 legacy public 静态资产路径。
|
||||
@@ -15,7 +15,7 @@
|
||||
2. 交换拼图块、拖动拼图块、关卡是否拼完,全部由前端本地计算。
|
||||
3. 本地运行态不调用 `/api/runtime/puzzle/runs/*` 写回当前过程状态。
|
||||
4. 关闭玩法后,这次运行态直接失效,不做断点续玩,不做跨端同步。
|
||||
5. 通关后的第一版接续只保证单次游玩闭环:本地生成一个临时 `recommendedNextProfileId`,点击“下一关”后沿用当前作品图片、作者和标签,重建下一关棋盘;正式的广场推荐池仍留给后端运行态版本恢复。
|
||||
5. 通关后的第一版接续按“广场作品优先”执行:先从拼图广场读取未玩过且有正式图的作品;广场没有可用作品时,再使用当前草稿期间已生成但未消费的候选图;候选图仍不足时,现场调用 `generate_puzzle_images` 生成候选图,并在运行页弹出等待面板。
|
||||
6. 后端仍然负责:
|
||||
- Agent 会话
|
||||
- 结果页草稿编译
|
||||
@@ -59,8 +59,11 @@
|
||||
1. 进入玩法时从作品详情构造本地 `run`
|
||||
2. 交换 / 拖动 / 通关时由前端工具函数返回新的 `run`
|
||||
3. 通关时本地写入临时下一关 id,用于显示“下一关”按钮
|
||||
4. 点击下一关时重置棋盘、推进关卡序号,并按已通关数量切换 `3x3 / 4x4`
|
||||
5. 当前不依赖后端 `start/swap/drag/next-level` 接口完成主链
|
||||
4. 点击下一关时前端只提交当前 `run` 与可选 `sourceSessionId` 到 Rust `api-server`,不在前端判断图片来源
|
||||
5. `api-server` 优先用广场作品详情构造下一关;如果广场没有可用作品,则把草稿候选图包装成一次本地关卡来源
|
||||
6. 草稿候选图仍不足时,`api-server` 现场调用真实生图链生成候选图;前端只展示等待弹窗并接收最终 `run`
|
||||
7. 每次进入下一关都会重置棋盘、推进关卡序号,并按已通关数量切换 `3x3 / 4x4`
|
||||
8. 当前不依赖后端 `start/swap/drag/next-level` 接口保存过程状态
|
||||
|
||||
## 5. 当前实现判断标准
|
||||
|
||||
@@ -70,5 +73,7 @@
|
||||
2. 返回路径切到 `/generated-puzzle-assets/*`。
|
||||
3. 未配置 DashScope 或 OSS 时,接口明确返回 provider 级错误,而不是静默回退占位图。
|
||||
4. 玩家进入拼图玩法后,即使后端运行态接口不可用,也能在本地完成交换与拖动。
|
||||
5. 玩家完成整张图后能看到通关态与“下一关”入口,点击后进入新棋盘。
|
||||
6. 关闭玩法后不保留当前 run 进度。
|
||||
5. 玩家完成整张图后能看到通关态与“下一关”入口。
|
||||
6. 广场有可用作品时,下一关内容来自广场作品。
|
||||
7. 广场没有可用作品时,下一关内容来自草稿候选图;候选图不足时现场生成并显示等待面板。
|
||||
8. 关闭玩法后不保留当前 run 进度。
|
||||
|
||||
@@ -7,10 +7,12 @@
|
||||
- [CURRENT_BACKEND_IMPLEMENTATION_BASELINE_2026-04-25.md](./CURRENT_BACKEND_IMPLEMENTATION_BASELINE_2026-04-25.md):冻结当前后端唯一落地口径,明确新功能以 `server-rs + Axum + SpacetimeDB` 为准,旧 `server-node` / Express / PostgreSQL 与 Go 方向只允许作为迁移参考。
|
||||
- [API_SERVER_DEV_STACK_COLD_BUILD_TIMEOUT_FIX_2026-04-25.md](./API_SERVER_DEV_STACK_COLD_BUILD_TIMEOUT_FIX_2026-04-25.md):记录 `npm run dev:rust` 在 Windows 冷编译/链接阶段误把 `api-server` `/healthz` 等待判定为超时并杀掉 `cargo run` 的根因,以及将 SpacetimeDB 与 api-server 等待窗口拆分的脚本口径。
|
||||
- [API_ERROR_DETAILS_MESSAGE_DISPLAY_FIX_2026-04-25.md](./API_ERROR_DETAILS_MESSAGE_DISPLAY_FIX_2026-04-25.md):记录统一 API envelope 错误展示优先读取 `error.details.message` 的修复口径,避免 Big Fish 发布校验等业务错误只显示通用“请求参数不合法”。
|
||||
- [PUZZLE_BIG_FISH_DRAFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md](./PUZZLE_BIG_FISH_DRAFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md):冻结拼图与大鱼吃小鱼点击生成草稿后进入独立进度页,并一次性生成草稿、图片与动作资产的前端编排边界。
|
||||
- [BIG_FISH_DIRECTION_TOUCH_CONTROL_2026-04-24.md](./BIG_FISH_DIRECTION_TOUCH_CONTROL_2026-04-24.md):记录大鱼吃小鱼从固定摇杆改为屏幕首触点方向控制,并要求本地直达局在未操作时保持对象运动。
|
||||
- [RUST_WORKSPACE_DEFAULT_BUILD_SCOPE_FIX_2026-04-25.md](./RUST_WORKSPACE_DEFAULT_BUILD_SCOPE_FIX_2026-04-25.md):记录 `server-rs` 无参数 `cargo build` 链接 `spacetime-module` 失败的根因,并冻结默认只构建原生 `api-server`、模块产物继续走 `spacetime build` 的命令边界。
|
||||
- [BIG_FISH_DIRECT_ROUTE_PLAYGROUND_2026-04-24.md](./BIG_FISH_DIRECT_ROUTE_PLAYGROUND_2026-04-24.md):记录 `/big-fish` 大鱼吃小鱼玩法直达入口,明确复用现有 `BigFishRuntimeShell` 和本地占位运行态的调试边界。
|
||||
- [PUZZLE_DIRECT_ROUTE_PLAYGROUND_2026-04-24.md](./PUZZLE_DIRECT_ROUTE_PLAYGROUND_2026-04-24.md):记录 `/puzzle` 拼图玩法直达入口,明确复用现有 `PuzzleRuntimeShell` 和本地占位图运行态的调试边界。
|
||||
- [PUZZLE_AGENT_ACTION_RESPONSE_SESSION_2026-04-25.md](./PUZZLE_AGENT_ACTION_RESPONSE_SESSION_2026-04-25.md):记录拼图 Agent `actions` 回包直接携带最新 session,避免选图后额外拉取完整会话大包的接口收口规则。
|
||||
- [CREATION_AGENT_PUBLISH_GATE_NORMALIZE_WRITEBACK_FIX_2026-04-24.md](./CREATION_AGENT_PUBLISH_GATE_NORMALIZE_WRITEBACK_FIX_2026-04-24.md):记录结果页 profile 归一化回写丢失顶层 `worldHook / playerPremise` 导致 publish gate 继续误报结构 blocker 的根因,并冻结前端归一化保留发布字段的修复口径。
|
||||
|
||||
- [CUSTOM_WORLD_RESULT_ENTITY_GENERATION_FIX_2026-04-24.md](./CUSTOM_WORLD_RESULT_ENTITY_GENERATION_FIX_2026-04-24.md):记录世界结果页在 Agent 草稿模式下新增场景、新增 NPC 生成成功但结果页字段不可用的根因,并冻结 `api-server` 生成归一化层补齐 profile 字段的修复口径。
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { PuzzleAgentSessionSnapshot } from './puzzleAgentSession';
|
||||
|
||||
export type PuzzleAgentSuggestedActionType =
|
||||
| 'request_summary'
|
||||
| 'compile_puzzle_draft'
|
||||
@@ -54,6 +56,10 @@ export type PuzzleAgentActionRequest =
|
||||
themeTags?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 拼图操作接口直接返回最新会话,避免前端在选图等轻操作后再额外 GET 大体积快照。
|
||||
*/
|
||||
export interface PuzzleAgentActionResponse {
|
||||
operation: PuzzleAgentOperationRecord;
|
||||
session: PuzzleAgentSessionSnapshot;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,11 @@ export interface StartPuzzleRunRequest {
|
||||
profileId: string;
|
||||
}
|
||||
|
||||
export interface AdvanceLocalPuzzleNextLevelRequest {
|
||||
run: PuzzleRunSnapshot;
|
||||
sourceSessionId?: string | null;
|
||||
}
|
||||
|
||||
export interface PuzzleRunResponse {
|
||||
run: PuzzleRunSnapshot;
|
||||
}
|
||||
|
||||
@@ -89,6 +89,39 @@ wait_for_spacetime() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
is_spacetime_ready() {
|
||||
local server="$1"
|
||||
local root_dir="$2"
|
||||
|
||||
spacetime --root-dir="${root_dir}" server ping "${server}" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
describe_spacetime_root_owner() {
|
||||
local root_dir="$1"
|
||||
local windows_root_dir="${root_dir}"
|
||||
|
||||
if [[ "${windows_root_dir}" =~ ^/([a-zA-Z])/(.*)$ ]]; then
|
||||
windows_root_dir="${BASH_REMATCH[1]}:/${BASH_REMATCH[2]}"
|
||||
fi
|
||||
|
||||
# Windows 本地开发最常见的失败是同一个 root-dir 下已有 standalone 持有 spacetime.pid;
|
||||
# 启动前先打印占用进程,避免用户只看到底层 os error 33 而不知道该停哪个实例。
|
||||
if command -v powershell.exe >/dev/null 2>&1; then
|
||||
ROOT_DIR_FOR_POWERSHELL="${windows_root_dir}" powershell.exe -NoProfile -Command '
|
||||
$rootDir = $env:ROOT_DIR_FOR_POWERSHELL
|
||||
$normalized = $rootDir.Replace("/", "\")
|
||||
Get-CimInstance Win32_Process |
|
||||
Where-Object { $_.Name -match "spacetime" -and $_.CommandLine -and $_.CommandLine.Replace("/", "\") -like "*$normalized*" } |
|
||||
ForEach-Object { "pid=$($_.ProcessId) name=$($_.Name) command=$($_.CommandLine)" }
|
||||
' 2>/dev/null || true
|
||||
return
|
||||
fi
|
||||
|
||||
if command -v ps >/dev/null 2>&1; then
|
||||
ps -ef 2>/dev/null | grep '[s]pacetime' | grep -F "${root_dir}" || true
|
||||
fi
|
||||
}
|
||||
|
||||
wait_for_api_server() {
|
||||
local health_url="$1"
|
||||
local timeout_seconds="$2"
|
||||
@@ -333,17 +366,29 @@ echo "[dev:rust] api timeout: ${API_SERVER_TIMEOUT_SECONDS}s"
|
||||
if [[ "${SKIP_SPACETIME}" -ne 1 ]]; then
|
||||
mkdir -p "${SPACETIME_ROOT_DIR}"
|
||||
sync_local_spacetime_install "${SPACETIME_ROOT_DIR}"
|
||||
echo "[dev:rust] 启动 spacetimedb"
|
||||
(
|
||||
cd "${SERVER_RS_DIR}"
|
||||
exec spacetime \
|
||||
--root-dir="${SPACETIME_ROOT_DIR}" \
|
||||
start \
|
||||
--edition standalone \
|
||||
--listen-addr "${SPACETIME_HOST}:${SPACETIME_PORT}"
|
||||
) &
|
||||
PIDS+=("$!")
|
||||
NAMES+=("spacetimedb")
|
||||
if is_spacetime_ready "${SPACETIME_SERVER}" "${SPACETIME_ROOT_DIR}"; then
|
||||
echo "[dev:rust] 复用已运行的 SpacetimeDB: ${SPACETIME_SERVER}"
|
||||
else
|
||||
SPACETIME_ROOT_OWNER="$(describe_spacetime_root_owner "${SPACETIME_ROOT_DIR}")"
|
||||
if [[ -n "${SPACETIME_ROOT_OWNER}" ]]; then
|
||||
echo "[dev:rust] 当前 root-dir 已被其他 SpacetimeDB 实例占用,无法再次启动。" >&2
|
||||
echo "[dev:rust] 目标地址未就绪: ${SPACETIME_SERVER}" >&2
|
||||
echo "[dev:rust] 如需复用,请传入占用实例实际端口,例如 --spacetime-port 3199;如需重启,请先停止下列进程。" >&2
|
||||
echo "${SPACETIME_ROOT_OWNER}" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "[dev:rust] 启动 spacetimedb"
|
||||
(
|
||||
cd "${SERVER_RS_DIR}"
|
||||
exec spacetime \
|
||||
--root-dir="${SPACETIME_ROOT_DIR}" \
|
||||
start \
|
||||
--edition standalone \
|
||||
--listen-addr "${SPACETIME_HOST}:${SPACETIME_PORT}"
|
||||
) &
|
||||
PIDS+=("$!")
|
||||
NAMES+=("spacetimedb")
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "${SKIP_PUBLISH}" -ne 1 ]]; then
|
||||
|
||||
@@ -77,11 +77,12 @@ use crate::{
|
||||
password_management::{change_password, reset_password},
|
||||
phone_auth::{phone_login, send_phone_code},
|
||||
puzzle::{
|
||||
advance_puzzle_next_level, create_puzzle_agent_session, delete_puzzle_work,
|
||||
drag_puzzle_piece_or_group, execute_puzzle_agent_action, get_puzzle_agent_session,
|
||||
get_puzzle_gallery_detail, get_puzzle_run, get_puzzle_work_detail, get_puzzle_works,
|
||||
list_puzzle_gallery, put_puzzle_work, start_puzzle_run, stream_puzzle_agent_message,
|
||||
submit_puzzle_agent_message, swap_puzzle_pieces,
|
||||
advance_local_puzzle_next_level, advance_puzzle_next_level, create_puzzle_agent_session,
|
||||
delete_puzzle_work, drag_puzzle_piece_or_group, execute_puzzle_agent_action,
|
||||
get_puzzle_agent_session, get_puzzle_gallery_detail, get_puzzle_run,
|
||||
get_puzzle_work_detail, get_puzzle_works, list_puzzle_gallery, put_puzzle_work,
|
||||
start_puzzle_run, stream_puzzle_agent_message, submit_puzzle_agent_message,
|
||||
swap_puzzle_pieces,
|
||||
},
|
||||
refresh_session::refresh_session,
|
||||
request_context::{attach_request_context, resolve_request_id},
|
||||
@@ -634,6 +635,13 @@ pub fn build_router(state: AppState) -> Router {
|
||||
require_bearer_auth,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/runtime/puzzle/runs/local-next-level",
|
||||
post(advance_local_puzzle_next_level).route_layer(middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
require_bearer_auth,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/runtime/puzzle/runs/{run_id}",
|
||||
get(get_puzzle_run).route_layer(middleware::from_fn_with_state(
|
||||
|
||||
@@ -434,10 +434,13 @@ pub async fn execute_big_fish_action(
|
||||
let now = current_utc_micros();
|
||||
let session = match payload.action.trim() {
|
||||
"big_fish_compile_draft" => {
|
||||
state
|
||||
.spacetime_client()
|
||||
.compile_big_fish_draft(session_id, owner_user_id, now)
|
||||
.await
|
||||
compile_big_fish_draft_with_all_assets(
|
||||
&state,
|
||||
session_id,
|
||||
owner_user_id,
|
||||
now,
|
||||
)
|
||||
.await
|
||||
}
|
||||
"big_fish_generate_level_main_image" => {
|
||||
let asset_url = generate_big_fish_formal_asset(
|
||||
@@ -766,6 +769,98 @@ fn map_big_fish_asset_coverage_response(
|
||||
}
|
||||
}
|
||||
|
||||
async fn compile_big_fish_draft_with_all_assets(
|
||||
state: &AppState,
|
||||
session_id: String,
|
||||
owner_user_id: String,
|
||||
now: i64,
|
||||
) -> Result<BigFishSessionRecord, SpacetimeClientError> {
|
||||
let session = state
|
||||
.spacetime_client()
|
||||
.compile_big_fish_draft(session_id.clone(), owner_user_id.clone(), now)
|
||||
.await?;
|
||||
let draft = session
|
||||
.draft
|
||||
.clone()
|
||||
.ok_or_else(|| SpacetimeClientError::Runtime("大鱼吃小鱼玩法草稿尚未生成".to_string()))?;
|
||||
// 点击生成草稿时一次性生成所有首版玩法资产,前端只负责展示进度和最终 session。
|
||||
for level in &draft.levels {
|
||||
let asset_url = generate_big_fish_formal_asset(
|
||||
state,
|
||||
&owner_user_id,
|
||||
&session_id,
|
||||
"level_main_image",
|
||||
Some(level.level),
|
||||
None,
|
||||
current_utc_micros(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| SpacetimeClientError::Runtime(error.message().to_string()))?;
|
||||
state
|
||||
.spacetime_client()
|
||||
.generate_big_fish_asset(BigFishAssetGenerateRecordInput {
|
||||
session_id: session_id.clone(),
|
||||
owner_user_id: owner_user_id.clone(),
|
||||
asset_kind: "level_main_image".to_string(),
|
||||
level: Some(level.level),
|
||||
motion_key: None,
|
||||
asset_url: Some(asset_url),
|
||||
generated_at_micros: current_utc_micros(),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
for level in &draft.levels {
|
||||
for motion_key in ["idle_float", "move_swim"] {
|
||||
let asset_url = generate_big_fish_formal_asset(
|
||||
state,
|
||||
&owner_user_id,
|
||||
&session_id,
|
||||
"level_motion",
|
||||
Some(level.level),
|
||||
Some(motion_key),
|
||||
current_utc_micros(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| SpacetimeClientError::Runtime(error.message().to_string()))?;
|
||||
state
|
||||
.spacetime_client()
|
||||
.generate_big_fish_asset(BigFishAssetGenerateRecordInput {
|
||||
session_id: session_id.clone(),
|
||||
owner_user_id: owner_user_id.clone(),
|
||||
asset_kind: "level_motion".to_string(),
|
||||
level: Some(level.level),
|
||||
motion_key: Some(motion_key.to_string()),
|
||||
asset_url: Some(asset_url),
|
||||
generated_at_micros: current_utc_micros(),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let asset_url = generate_big_fish_formal_asset(
|
||||
state,
|
||||
&owner_user_id,
|
||||
&session_id,
|
||||
"stage_background",
|
||||
None,
|
||||
None,
|
||||
current_utc_micros(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| SpacetimeClientError::Runtime(error.message().to_string()))?;
|
||||
state
|
||||
.spacetime_client()
|
||||
.generate_big_fish_asset(BigFishAssetGenerateRecordInput {
|
||||
session_id,
|
||||
owner_user_id,
|
||||
asset_kind: "stage_background".to_string(),
|
||||
level: None,
|
||||
motion_key: None,
|
||||
asset_url: Some(asset_url),
|
||||
generated_at_micros: current_utc_micros(),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn map_big_fish_agent_message_response(
|
||||
message: BigFishAgentMessageRecord,
|
||||
) -> BigFishAgentMessageResponse {
|
||||
|
||||
@@ -32,10 +32,10 @@ use shared_contracts::{
|
||||
},
|
||||
puzzle_gallery::{PuzzleGalleryDetailResponse, PuzzleGalleryResponse},
|
||||
puzzle_runtime::{
|
||||
DragPuzzlePieceRequest, PuzzleBoardSnapshotResponse, PuzzleCellPositionResponse,
|
||||
PuzzleMergedGroupStateResponse, PuzzlePieceStateResponse, PuzzleRunResponse,
|
||||
PuzzleRunSnapshotResponse, PuzzleRuntimeLevelSnapshotResponse, StartPuzzleRunRequest,
|
||||
SwapPuzzlePiecesRequest,
|
||||
AdvanceLocalPuzzleNextLevelRequest, DragPuzzlePieceRequest, PuzzleBoardSnapshotResponse,
|
||||
PuzzleCellPositionResponse, PuzzleMergedGroupStateResponse, PuzzlePieceStateResponse,
|
||||
PuzzleRunResponse, PuzzleRunSnapshotResponse, PuzzleRuntimeLevelSnapshotResponse,
|
||||
StartPuzzleRunRequest, SwapPuzzlePiecesRequest,
|
||||
},
|
||||
puzzle_works::{
|
||||
PutPuzzleWorkRequest, PuzzleWorkDetailResponse, PuzzleWorkMutationResponse,
|
||||
@@ -50,9 +50,10 @@ use spacetime_client::{
|
||||
PuzzleCreatorIntentRecord, PuzzleGeneratedImageCandidateRecord,
|
||||
PuzzleGeneratedImagesSaveRecordInput, PuzzlePublishRecordInput, PuzzleResultDraftRecord,
|
||||
PuzzleResultPreviewBlockerRecord, PuzzleResultPreviewFindingRecord, PuzzleResultPreviewRecord,
|
||||
PuzzleBoardRecord, PuzzleCellPositionRecord, PuzzleMergedGroupRecord, PuzzlePieceStateRecord,
|
||||
PuzzleRunDragRecordInput, PuzzleRunRecord, PuzzleRunStartRecordInput, PuzzleRunSwapRecordInput,
|
||||
PuzzleSelectCoverImageRecordInput, PuzzleWorkProfileRecord, PuzzleWorkUpsertRecordInput,
|
||||
SpacetimeClientError,
|
||||
PuzzleRuntimeLevelRecord, PuzzleSelectCoverImageRecordInput, PuzzleWorkProfileRecord,
|
||||
PuzzleWorkUpsertRecordInput, SpacetimeClientError,
|
||||
};
|
||||
use std::convert::Infallible;
|
||||
use tokio::time::sleep;
|
||||
@@ -435,14 +436,17 @@ pub async fn execute_puzzle_agent_action(
|
||||
|
||||
let (operation_type, phase_label, phase_detail, session) = match payload.action.trim() {
|
||||
"compile_puzzle_draft" => {
|
||||
let session = state
|
||||
.spacetime_client()
|
||||
.compile_puzzle_agent_draft(session_id, owner_user_id, now)
|
||||
.await;
|
||||
let session = compile_puzzle_draft_with_initial_cover(
|
||||
&state,
|
||||
session_id.clone(),
|
||||
owner_user_id.clone(),
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
(
|
||||
"compile_puzzle_draft",
|
||||
"结果页草稿",
|
||||
"已根据当前锚点编译结果页草稿。",
|
||||
"完整拼图草稿",
|
||||
"已编译草稿、生成候选图并应用正式图片。",
|
||||
session,
|
||||
)
|
||||
}
|
||||
@@ -572,6 +576,18 @@ pub async fn execute_puzzle_agent_action(
|
||||
)
|
||||
})?;
|
||||
|
||||
let session = state
|
||||
.spacetime_client()
|
||||
.get_puzzle_agent_session(session_id.clone(), owner_user_id.clone())
|
||||
.await
|
||||
.map_err(|error| {
|
||||
puzzle_error_response(
|
||||
&request_context,
|
||||
PUZZLE_AGENT_API_BASE_PROVIDER,
|
||||
map_puzzle_client_error(error),
|
||||
)
|
||||
})?;
|
||||
|
||||
return Ok(json_success_body(
|
||||
Some(&request_context),
|
||||
PuzzleAgentActionResponse {
|
||||
@@ -584,6 +600,7 @@ pub async fn execute_puzzle_agent_action(
|
||||
progress: 100,
|
||||
error: None,
|
||||
},
|
||||
session: map_puzzle_agent_session_response(session),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -616,6 +633,7 @@ pub async fn execute_puzzle_agent_action(
|
||||
progress: 100,
|
||||
error: None,
|
||||
},
|
||||
session: map_puzzle_agent_session_response(session),
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -1046,6 +1064,36 @@ pub async fn advance_puzzle_next_level(
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn advance_local_puzzle_next_level(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
Extension(authenticated): Extension<AuthenticatedAccessToken>,
|
||||
payload: Result<Json<AdvanceLocalPuzzleNextLevelRequest>, JsonRejection>,
|
||||
) -> Result<Json<Value>, Response> {
|
||||
let Json(payload) = payload.map_err(|error| {
|
||||
puzzle_error_response(
|
||||
&request_context,
|
||||
PUZZLE_RUNTIME_PROVIDER,
|
||||
AppError::from_status(StatusCode::BAD_REQUEST).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": error.body_text(),
|
||||
})),
|
||||
)
|
||||
})?;
|
||||
|
||||
let owner_user_id = authenticated.claims().user_id().to_string();
|
||||
let run = build_local_next_puzzle_run(&state, payload, owner_user_id.as_str())
|
||||
.await
|
||||
.map_err(|error| puzzle_error_response(&request_context, PUZZLE_RUNTIME_PROVIDER, error))?;
|
||||
|
||||
Ok(json_success_body(
|
||||
Some(&request_context),
|
||||
PuzzleRunResponse {
|
||||
run: map_puzzle_run_response(run),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn map_puzzle_agent_session_response(
|
||||
session: PuzzleAgentSessionRecord,
|
||||
) -> PuzzleAgentSessionSnapshotResponse {
|
||||
@@ -1248,6 +1296,74 @@ fn map_puzzle_run_response(run: PuzzleRunRecord) -> PuzzleRunSnapshotResponse {
|
||||
}
|
||||
}
|
||||
|
||||
fn map_puzzle_run_request_record(run: PuzzleRunSnapshotResponse) -> PuzzleRunRecord {
|
||||
PuzzleRunRecord {
|
||||
run_id: run.run_id,
|
||||
entry_profile_id: run.entry_profile_id,
|
||||
cleared_level_count: run.cleared_level_count,
|
||||
current_level_index: run.current_level_index,
|
||||
current_grid_size: run.current_grid_size,
|
||||
played_profile_ids: run.played_profile_ids,
|
||||
previous_level_tags: run.previous_level_tags,
|
||||
current_level: run.current_level.map(map_puzzle_level_request_record),
|
||||
recommended_next_profile_id: run.recommended_next_profile_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_puzzle_level_request_record(
|
||||
level: PuzzleRuntimeLevelSnapshotResponse,
|
||||
) -> PuzzleRuntimeLevelRecord {
|
||||
PuzzleRuntimeLevelRecord {
|
||||
run_id: level.run_id,
|
||||
level_index: level.level_index,
|
||||
grid_size: level.grid_size,
|
||||
profile_id: level.profile_id,
|
||||
level_name: level.level_name,
|
||||
author_display_name: level.author_display_name,
|
||||
theme_tags: level.theme_tags,
|
||||
cover_image_src: level.cover_image_src,
|
||||
board: map_puzzle_board_request_record(level.board),
|
||||
status: level.status,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_puzzle_board_request_record(board: PuzzleBoardSnapshotResponse) -> PuzzleBoardRecord {
|
||||
PuzzleBoardRecord {
|
||||
rows: board.rows,
|
||||
cols: board.cols,
|
||||
pieces: board
|
||||
.pieces
|
||||
.into_iter()
|
||||
.map(|piece| PuzzlePieceStateRecord {
|
||||
piece_id: piece.piece_id,
|
||||
correct_row: piece.correct_row,
|
||||
correct_col: piece.correct_col,
|
||||
current_row: piece.current_row,
|
||||
current_col: piece.current_col,
|
||||
merged_group_id: piece.merged_group_id,
|
||||
})
|
||||
.collect(),
|
||||
merged_groups: board
|
||||
.merged_groups
|
||||
.into_iter()
|
||||
.map(|group| PuzzleMergedGroupRecord {
|
||||
group_id: group.group_id,
|
||||
piece_ids: group.piece_ids,
|
||||
occupied_cells: group
|
||||
.occupied_cells
|
||||
.into_iter()
|
||||
.map(|cell| PuzzleCellPositionRecord {
|
||||
row: cell.row,
|
||||
col: cell.col,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
selected_piece_id: board.selected_piece_id,
|
||||
all_tiles_resolved: board.all_tiles_resolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_puzzle_runtime_level_response(
|
||||
level: spacetime_client::PuzzleRuntimeLevelRecord,
|
||||
) -> PuzzleRuntimeLevelSnapshotResponse {
|
||||
@@ -1336,6 +1452,64 @@ fn build_stable_puzzle_work_ids(session_id: &str) -> (String, String) {
|
||||
)
|
||||
}
|
||||
|
||||
async fn compile_puzzle_draft_with_initial_cover(
|
||||
state: &AppState,
|
||||
session_id: String,
|
||||
owner_user_id: String,
|
||||
now: i64,
|
||||
) -> Result<PuzzleAgentSessionRecord, SpacetimeClientError> {
|
||||
let compiled_session = state
|
||||
.spacetime_client()
|
||||
.compile_puzzle_agent_draft(session_id.clone(), owner_user_id.clone(), now)
|
||||
.await?;
|
||||
let draft = compiled_session
|
||||
.draft
|
||||
.clone()
|
||||
.ok_or_else(|| SpacetimeClientError::Runtime("拼图结果页草稿尚未生成".to_string()))?;
|
||||
// 点击生成草稿时一次性完成首图生成与正式图选定,前端只展示进度,不再承担业务编排。
|
||||
let candidates = generate_puzzle_image_candidates(
|
||||
state,
|
||||
owner_user_id.as_str(),
|
||||
&compiled_session.session_id,
|
||||
&draft.level_name,
|
||||
&draft.summary,
|
||||
2,
|
||||
)
|
||||
.await
|
||||
.map_err(SpacetimeClientError::Runtime)?;
|
||||
let selected_candidate_id = candidates
|
||||
.iter()
|
||||
.find(|candidate| candidate.selected)
|
||||
.or_else(|| candidates.first())
|
||||
.map(|candidate| candidate.candidate_id.clone())
|
||||
.ok_or_else(|| SpacetimeClientError::Runtime("拼图候选图生成结果为空".to_string()))?;
|
||||
let candidates_json = serde_json::to_string(
|
||||
&candidates
|
||||
.iter()
|
||||
.map(to_puzzle_generated_image_candidate)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.map_err(|error| SpacetimeClientError::Runtime(format!("拼图候选图序列化失败:{error}")))?;
|
||||
state
|
||||
.spacetime_client()
|
||||
.save_puzzle_generated_images(PuzzleGeneratedImagesSaveRecordInput {
|
||||
session_id: compiled_session.session_id.clone(),
|
||||
owner_user_id: owner_user_id.clone(),
|
||||
candidates_json,
|
||||
saved_at_micros: current_utc_micros(),
|
||||
})
|
||||
.await?;
|
||||
state
|
||||
.spacetime_client()
|
||||
.select_puzzle_cover_image(PuzzleSelectCoverImageRecordInput {
|
||||
session_id,
|
||||
owner_user_id,
|
||||
candidate_id: selected_candidate_id,
|
||||
selected_at_micros: current_utc_micros(),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn ensure_non_empty(
|
||||
request_context: &RequestContext,
|
||||
provider: &str,
|
||||
@@ -1499,6 +1673,248 @@ async fn generate_puzzle_image_candidates(
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn build_local_next_puzzle_run(
|
||||
state: &AppState,
|
||||
payload: AdvanceLocalPuzzleNextLevelRequest,
|
||||
owner_user_id: &str,
|
||||
) -> Result<PuzzleRunRecord, AppError> {
|
||||
let run = map_puzzle_run_request_record(payload.run);
|
||||
let current_level = run.current_level.clone().ok_or_else(|| {
|
||||
AppError::from_status(StatusCode::BAD_REQUEST).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": "currentLevel is required",
|
||||
}))
|
||||
})?;
|
||||
if current_level.status != "cleared" {
|
||||
return Err(AppError::from_status(StatusCode::BAD_REQUEST).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": "current level is not cleared",
|
||||
})));
|
||||
}
|
||||
|
||||
if let Some(gallery_item) = resolve_gallery_next_puzzle_work(state, &run).await? {
|
||||
return Ok(build_next_run_from_puzzle_work(run, gallery_item));
|
||||
}
|
||||
|
||||
let source_session_id = payload.source_session_id.unwrap_or_default();
|
||||
if source_session_id.trim().is_empty() {
|
||||
return Err(AppError::from_status(StatusCode::BAD_REQUEST).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": "sourceSessionId is required when gallery has no next puzzle work",
|
||||
})));
|
||||
}
|
||||
let session = state
|
||||
.spacetime_client()
|
||||
.get_puzzle_agent_session(source_session_id, owner_user_id.to_string())
|
||||
.await
|
||||
.map_err(map_puzzle_client_error)?;
|
||||
if let Some(candidate) = session
|
||||
.draft
|
||||
.as_ref()
|
||||
.and_then(|draft| pick_unused_puzzle_candidate(&draft.candidates, &run.played_profile_ids))
|
||||
{
|
||||
return Ok(build_next_run_from_candidate(run, &session, candidate));
|
||||
}
|
||||
|
||||
let draft = session.draft.clone().ok_or_else(|| {
|
||||
AppError::from_status(StatusCode::BAD_REQUEST).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": "puzzle draft is required when gallery has no next puzzle work",
|
||||
}))
|
||||
})?;
|
||||
let candidates = generate_puzzle_image_candidates(
|
||||
state,
|
||||
owner_user_id,
|
||||
&session.session_id,
|
||||
&draft.level_name,
|
||||
&draft.summary,
|
||||
2,
|
||||
)
|
||||
.await
|
||||
.map_err(|message| {
|
||||
AppError::from_status(StatusCode::BAD_GATEWAY).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": message,
|
||||
}))
|
||||
})?;
|
||||
let candidates_json = serde_json::to_string(
|
||||
&candidates
|
||||
.iter()
|
||||
.map(to_puzzle_generated_image_candidate)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.map_err(|error| {
|
||||
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": format!("拼图候选图序列化失败:{error}"),
|
||||
}))
|
||||
})?;
|
||||
let updated_session = state
|
||||
.spacetime_client()
|
||||
.save_puzzle_generated_images(PuzzleGeneratedImagesSaveRecordInput {
|
||||
session_id: session.session_id,
|
||||
owner_user_id: owner_user_id.to_string(),
|
||||
candidates_json,
|
||||
saved_at_micros: current_utc_micros(),
|
||||
})
|
||||
.await
|
||||
.map_err(map_puzzle_client_error)?;
|
||||
let candidate = updated_session
|
||||
.draft
|
||||
.as_ref()
|
||||
.and_then(|draft| draft.candidates.iter().find(|candidate| !candidate.image_src.is_empty()))
|
||||
.ok_or_else(|| {
|
||||
AppError::from_status(StatusCode::BAD_GATEWAY).with_details(json!({
|
||||
"provider": PUZZLE_RUNTIME_PROVIDER,
|
||||
"message": "现场生成后没有可用候选图",
|
||||
}))
|
||||
})?;
|
||||
Ok(build_next_run_from_candidate(run, &updated_session, candidate))
|
||||
}
|
||||
|
||||
async fn resolve_gallery_next_puzzle_work(
|
||||
state: &AppState,
|
||||
run: &PuzzleRunRecord,
|
||||
) -> Result<Option<PuzzleWorkProfileRecord>, AppError> {
|
||||
let items = state
|
||||
.spacetime_client()
|
||||
.list_puzzle_gallery()
|
||||
.await
|
||||
.map_err(map_puzzle_client_error)?;
|
||||
Ok(items.into_iter().find(|item| {
|
||||
item.publication_status == "published"
|
||||
&& item.cover_image_src.as_ref().is_some_and(|value| !value.is_empty())
|
||||
&& !run.played_profile_ids.contains(&item.profile_id)
|
||||
}))
|
||||
}
|
||||
|
||||
fn pick_unused_puzzle_candidate<'a>(
|
||||
candidates: &'a [PuzzleGeneratedImageCandidateRecord],
|
||||
played_profile_ids: &[String],
|
||||
) -> Option<&'a PuzzleGeneratedImageCandidateRecord> {
|
||||
candidates.iter().find(|candidate| {
|
||||
!candidate.image_src.is_empty()
|
||||
&& !played_profile_ids
|
||||
.iter()
|
||||
.any(|profile_id| profile_id.contains(&candidate.candidate_id))
|
||||
})
|
||||
}
|
||||
|
||||
fn build_next_run_from_puzzle_work(
|
||||
run: PuzzleRunRecord,
|
||||
item: PuzzleWorkProfileRecord,
|
||||
) -> PuzzleRunRecord {
|
||||
build_next_run_from_parts(
|
||||
run,
|
||||
item.profile_id,
|
||||
item.level_name,
|
||||
item.author_display_name,
|
||||
item.theme_tags,
|
||||
item.cover_image_src,
|
||||
)
|
||||
}
|
||||
|
||||
fn build_next_run_from_candidate(
|
||||
run: PuzzleRunRecord,
|
||||
session: &PuzzleAgentSessionRecord,
|
||||
candidate: &PuzzleGeneratedImageCandidateRecord,
|
||||
) -> PuzzleRunRecord {
|
||||
let draft = session.draft.as_ref();
|
||||
let level_index = run.current_level_index + 1;
|
||||
build_next_run_from_parts(
|
||||
run,
|
||||
format!(
|
||||
"{}-{}-level-{}",
|
||||
session.session_id, candidate.candidate_id, level_index
|
||||
),
|
||||
draft
|
||||
.map(|draft| format!("{} · 候选 {}", draft.level_name, level_index))
|
||||
.unwrap_or_else(|| format!("候选拼图 {level_index}")),
|
||||
"当前草稿".to_string(),
|
||||
draft.map(|draft| draft.theme_tags.clone()).unwrap_or_default(),
|
||||
Some(candidate.image_src.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
fn build_next_run_from_parts(
|
||||
run: PuzzleRunRecord,
|
||||
profile_id: String,
|
||||
level_name: String,
|
||||
author_display_name: String,
|
||||
theme_tags: Vec<String>,
|
||||
cover_image_src: Option<String>,
|
||||
) -> PuzzleRunRecord {
|
||||
let next_level_index = run.current_level_index + 1;
|
||||
let grid_size = if run.cleared_level_count >= 3 { 4 } else { 3 };
|
||||
let mut played_profile_ids = run.played_profile_ids.clone();
|
||||
if !played_profile_ids.contains(&profile_id) {
|
||||
played_profile_ids.push(profile_id.clone());
|
||||
}
|
||||
PuzzleRunRecord {
|
||||
run_id: run.run_id.clone(),
|
||||
entry_profile_id: run.entry_profile_id,
|
||||
cleared_level_count: run.cleared_level_count,
|
||||
current_level_index: next_level_index,
|
||||
current_grid_size: grid_size,
|
||||
played_profile_ids,
|
||||
previous_level_tags: theme_tags.clone(),
|
||||
current_level: Some(PuzzleRuntimeLevelRecord {
|
||||
run_id: run.run_id,
|
||||
level_index: next_level_index,
|
||||
grid_size,
|
||||
profile_id,
|
||||
level_name,
|
||||
author_display_name,
|
||||
theme_tags,
|
||||
cover_image_src,
|
||||
board: build_local_puzzle_board(grid_size),
|
||||
status: "playing".to_string(),
|
||||
}),
|
||||
recommended_next_profile_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_local_puzzle_board(grid_size: u32) -> PuzzleBoardRecord {
|
||||
let total = grid_size * grid_size;
|
||||
let mut positions = (0..total)
|
||||
.map(|index| PuzzleCellPositionRecord {
|
||||
row: index / grid_size,
|
||||
col: index % grid_size,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !positions.is_empty() {
|
||||
let first = positions.remove(0);
|
||||
positions.push(first);
|
||||
}
|
||||
let pieces = (0..total)
|
||||
.map(|index| {
|
||||
let current = positions
|
||||
.get(index as usize)
|
||||
.cloned()
|
||||
.unwrap_or(PuzzleCellPositionRecord {
|
||||
row: index / grid_size,
|
||||
col: index % grid_size,
|
||||
});
|
||||
PuzzlePieceStateRecord {
|
||||
piece_id: format!("piece-{index}"),
|
||||
correct_row: index / grid_size,
|
||||
correct_col: index % grid_size,
|
||||
current_row: current.row,
|
||||
current_col: current.col,
|
||||
merged_group_id: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
PuzzleBoardRecord {
|
||||
rows: grid_size,
|
||||
cols: grid_size,
|
||||
pieces,
|
||||
merged_groups: Vec::new(),
|
||||
selected_piece_id: None,
|
||||
all_tiles_resolved: false,
|
||||
}
|
||||
}
|
||||
|
||||
struct PuzzleDashScopeSettings {
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
|
||||
@@ -187,4 +187,6 @@ pub struct PuzzleAgentOperationResponse {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PuzzleAgentActionResponse {
|
||||
pub operation: PuzzleAgentOperationResponse,
|
||||
/// 操作完成后的最新会话快照,供前端直接更新界面,避免重复拉取完整 session。
|
||||
pub session: PuzzleAgentSessionSnapshotResponse,
|
||||
}
|
||||
|
||||
@@ -6,6 +6,14 @@ pub struct StartPuzzleRunRequest {
|
||||
pub profile_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdvanceLocalPuzzleNextLevelRequest {
|
||||
pub run: PuzzleRunSnapshotResponse,
|
||||
#[serde(default)]
|
||||
pub source_session_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SwapPuzzlePiecesRequest {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import {
|
||||
lazy,
|
||||
Suspense,
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
import type { PublicUserSummary } from '../../../packages/shared/src/contracts/auth';
|
||||
import type {
|
||||
BigFishRuntimeSnapshotResponse,
|
||||
BigFishSessionSnapshotResponse,
|
||||
@@ -31,7 +33,6 @@ import type {
|
||||
CustomWorldGalleryCard,
|
||||
CustomWorldLibraryEntry,
|
||||
} from '../../../packages/shared/src/contracts/runtime';
|
||||
import type { PublicUserSummary } from '../../../packages/shared/src/contracts/auth';
|
||||
import { buildCustomWorldPlayableCharacters } from '../../data/characterPresets';
|
||||
import {
|
||||
getPublicAuthUserByCode,
|
||||
@@ -43,15 +44,22 @@ import {
|
||||
getBigFishCreationSession,
|
||||
streamBigFishCreationMessage,
|
||||
} from '../../services/big-fish-creation';
|
||||
import {
|
||||
deleteBigFishWork,
|
||||
listBigFishWorks,
|
||||
} from '../../services/big-fish-works';
|
||||
import {
|
||||
startBigFishRuntimeRun,
|
||||
submitBigFishRuntimeInput,
|
||||
} from '../../services/big-fish-runtime';
|
||||
import {
|
||||
deleteBigFishWork,
|
||||
listBigFishWorks,
|
||||
} from '../../services/big-fish-works';
|
||||
import { readCustomWorldAgentUiState } from '../../services/customWorldAgentUiState';
|
||||
import {
|
||||
buildBigFishGenerationAnchorEntries,
|
||||
buildMiniGameDraftGenerationProgress,
|
||||
buildPuzzleGenerationAnchorEntries,
|
||||
createMiniGameDraftGenerationState,
|
||||
type MiniGameDraftGenerationState,
|
||||
} from '../../services/miniGameDraftGenerationProgress';
|
||||
import { getPlatformProfileDashboard } from '../../services/platform-entry';
|
||||
import {
|
||||
createPuzzleAgentSession,
|
||||
@@ -60,17 +68,17 @@ import {
|
||||
streamPuzzleAgentMessage,
|
||||
} from '../../services/puzzle-agent';
|
||||
import { getPuzzleGalleryDetail } from '../../services/puzzle-gallery';
|
||||
import { advanceLocalPuzzleNextLevel } from '../../services/puzzle-runtime';
|
||||
import {
|
||||
advanceLocalPuzzleLevel,
|
||||
dragLocalPuzzlePiece,
|
||||
startLocalPuzzleRun,
|
||||
swapLocalPuzzlePieces,
|
||||
} from '../../services/puzzle-runtime/puzzleLocalRuntime';
|
||||
import { deletePuzzleWork, listPuzzleWorks } from '../../services/puzzle-works';
|
||||
import { deleteRpgEntryWorldProfile } from '../../services/rpg-entry';
|
||||
import { getRpgEntryWorldGalleryDetailByCode } from '../../services/rpg-entry/rpgEntryLibraryClient';
|
||||
import { deleteRpgCreationAgentSession } from '../../services/rpg-creation';
|
||||
import { rpgCreationPreviewAdapter } from '../../services/rpg-creation/rpgCreationPreviewAdapter';
|
||||
import { deleteRpgEntryWorldProfile } from '../../services/rpg-entry';
|
||||
import { getRpgEntryWorldGalleryDetailByCode } from '../../services/rpg-entry/rpgEntryLibraryClient';
|
||||
import type { CustomWorldProfile } from '../../types';
|
||||
import { useAuthUi } from '../auth/AuthUiContext';
|
||||
import { CustomWorldCreationHub } from '../custom-world-home/CustomWorldCreationHub';
|
||||
@@ -83,13 +91,13 @@ import { useRpgCreationEnterWorld } from '../rpg-entry/useRpgCreationEnterWorld'
|
||||
import { useRpgCreationResultAutosave } from '../rpg-entry/useRpgCreationResultAutosave';
|
||||
import { useRpgCreationSessionController } from '../rpg-entry/useRpgCreationSessionController';
|
||||
import { PlatformEntryCreationTypeModal } from './PlatformEntryCreationTypeModal';
|
||||
import type { PlatformCreationTypeId } from './platformEntryCreationTypes';
|
||||
import { PlatformEntryHomeView } from './PlatformEntryHomeView';
|
||||
import {
|
||||
buildCreationHubFallbackItems,
|
||||
normalizeAgentBackedProfile,
|
||||
resolveRpgCreationErrorMessage,
|
||||
} from './platformEntryShared';
|
||||
import type { PlatformCreationTypeId } from './platformEntryCreationTypes';
|
||||
import type { PlatformEntryFlowShellProps } from './platformEntryTypes';
|
||||
import { PlatformEntryWorldDetailView } from './PlatformEntryWorldDetailView';
|
||||
import { usePlatformEntryBootstrap } from './usePlatformEntryBootstrap';
|
||||
@@ -312,6 +320,8 @@ export function PlatformEntryFlowShellImpl({
|
||||
const [bigFishError, setBigFishError] = useState<string | null>(null);
|
||||
const [isBigFishBusy, setIsBigFishBusy] = useState(false);
|
||||
const [isBigFishLoadingLibrary, setIsBigFishLoadingLibrary] = useState(false);
|
||||
const [bigFishGenerationState, setBigFishGenerationState] =
|
||||
useState<MiniGameDraftGenerationState | null>(null);
|
||||
const [streamingBigFishReplyText, setStreamingBigFishReplyText] =
|
||||
useState('');
|
||||
const [isStreamingBigFishReply, setIsStreamingBigFishReply] = useState(false);
|
||||
@@ -327,6 +337,10 @@ export function PlatformEntryFlowShellImpl({
|
||||
const [puzzleError, setPuzzleError] = useState<string | null>(null);
|
||||
const [isPuzzleBusy, setIsPuzzleBusy] = useState(false);
|
||||
const [isPuzzleLoadingLibrary, setIsPuzzleLoadingLibrary] = useState(false);
|
||||
const [puzzleGenerationState, setPuzzleGenerationState] =
|
||||
useState<MiniGameDraftGenerationState | null>(null);
|
||||
const [isPuzzleNextLevelGenerating, setIsPuzzleNextLevelGenerating] =
|
||||
useState(false);
|
||||
const [isSearchingPublicCode, setIsSearchingPublicCode] = useState(false);
|
||||
const [publicSearchError, setPublicSearchError] = useState<string | null>(null);
|
||||
const [searchedPublicUser, setSearchedPublicUser] =
|
||||
@@ -791,6 +805,7 @@ export function PlatformEntryFlowShellImpl({
|
||||
const leaveBigFishFlow = useCallback(() => {
|
||||
setBigFishError(null);
|
||||
setBigFishRun(null);
|
||||
setBigFishGenerationState(null);
|
||||
setStreamingBigFishReplyText('');
|
||||
setIsStreamingBigFishReply(false);
|
||||
enterCreateTab();
|
||||
@@ -801,6 +816,8 @@ export function PlatformEntryFlowShellImpl({
|
||||
setPuzzleError(null);
|
||||
setPuzzleOperation(null);
|
||||
setPuzzleRun(null);
|
||||
setPuzzleGenerationState(null);
|
||||
setIsPuzzleNextLevelGenerating(false);
|
||||
setStreamingPuzzleReplyText('');
|
||||
setIsStreamingPuzzleReply(false);
|
||||
enterCreateTab();
|
||||
@@ -913,15 +930,45 @@ export function PlatformEntryFlowShellImpl({
|
||||
setBigFishError(null);
|
||||
|
||||
try {
|
||||
if (payload.action === 'big_fish_compile_draft') {
|
||||
setSelectionStage('big-fish-generating');
|
||||
setBigFishGenerationState(createMiniGameDraftGenerationState('big-fish'));
|
||||
const { session } = await executeBigFishCreationAction(
|
||||
bigFishSession.sessionId,
|
||||
payload,
|
||||
);
|
||||
setBigFishSession(session);
|
||||
setBigFishGenerationState((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
phase: 'ready',
|
||||
completedAssetCount: session.assetSlots.filter(
|
||||
(slot) => slot.status === 'ready',
|
||||
).length,
|
||||
totalAssetCount: session.assetSlots.length,
|
||||
}
|
||||
: current,
|
||||
);
|
||||
setSelectionStage('big-fish-result');
|
||||
return;
|
||||
}
|
||||
|
||||
const { session } = await executeBigFishCreationAction(
|
||||
bigFishSession.sessionId,
|
||||
payload,
|
||||
);
|
||||
setBigFishSession(session);
|
||||
if (payload.action === 'big_fish_compile_draft') {
|
||||
setSelectionStage('big-fish-result');
|
||||
}
|
||||
} catch (error) {
|
||||
setBigFishGenerationState((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
phase: 'failed',
|
||||
error: resolveBigFishErrorMessage(error, '执行大鱼吃小鱼操作失败。'),
|
||||
}
|
||||
: current,
|
||||
);
|
||||
setBigFishError(
|
||||
resolveBigFishErrorMessage(error, '执行大鱼吃小鱼操作失败。'),
|
||||
);
|
||||
@@ -947,7 +994,30 @@ export function PlatformEntryFlowShellImpl({
|
||||
setPuzzleError(null);
|
||||
|
||||
try {
|
||||
const { operation } = await executePuzzleAgentAction(
|
||||
if (payload.action === 'compile_puzzle_draft') {
|
||||
setSelectionStage('puzzle-generating');
|
||||
setPuzzleGenerationState(createMiniGameDraftGenerationState('puzzle'));
|
||||
const { operation, session } = await executePuzzleAgentAction(
|
||||
puzzleSession.sessionId,
|
||||
payload,
|
||||
);
|
||||
setPuzzleOperation(operation);
|
||||
setPuzzleSession(session);
|
||||
setPuzzleGenerationState((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
phase: 'ready',
|
||||
completedAssetCount: 1,
|
||||
totalAssetCount: 1,
|
||||
}
|
||||
: current,
|
||||
);
|
||||
setSelectionStage('puzzle-result');
|
||||
return;
|
||||
}
|
||||
|
||||
const { operation, session } = await executePuzzleAgentAction(
|
||||
puzzleSession.sessionId,
|
||||
payload,
|
||||
);
|
||||
@@ -957,14 +1027,8 @@ export function PlatformEntryFlowShellImpl({
|
||||
await refreshPuzzleShelf();
|
||||
}
|
||||
|
||||
const { session } = await getPuzzleAgentSession(
|
||||
puzzleSession.sessionId,
|
||||
);
|
||||
setPuzzleSession(session);
|
||||
|
||||
if (payload.action === 'compile_puzzle_draft') {
|
||||
setSelectionStage('puzzle-result');
|
||||
}
|
||||
if (
|
||||
payload.action === 'publish_puzzle_work' &&
|
||||
session.publishedProfileId
|
||||
@@ -976,6 +1040,15 @@ export function PlatformEntryFlowShellImpl({
|
||||
setSelectionStage('puzzle-gallery-detail');
|
||||
}
|
||||
} catch (error) {
|
||||
setPuzzleGenerationState((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
phase: 'failed',
|
||||
error: resolvePuzzleErrorMessage(error, '执行拼图操作失败。'),
|
||||
}
|
||||
: current,
|
||||
);
|
||||
setPuzzleError(resolvePuzzleErrorMessage(error, '执行拼图操作失败。'));
|
||||
} finally {
|
||||
setIsPuzzleBusy(false);
|
||||
@@ -1095,9 +1168,35 @@ export function PlatformEntryFlowShellImpl({
|
||||
return;
|
||||
}
|
||||
|
||||
const currentLevel = puzzleRun.currentLevel;
|
||||
if (!currentLevel || currentLevel.status !== 'cleared') {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPuzzleBusy(true);
|
||||
setIsPuzzleNextLevelGenerating(true);
|
||||
setPuzzleError(null);
|
||||
setPuzzleRun(advanceLocalPuzzleLevel(puzzleRun));
|
||||
}, [isPuzzleBusy, puzzleRun]);
|
||||
|
||||
try {
|
||||
const { run } = await advanceLocalPuzzleNextLevel({
|
||||
run: puzzleRun,
|
||||
sourceSessionId:
|
||||
selectedPuzzleDetail?.sourceSessionId ?? puzzleSession?.sessionId ?? null,
|
||||
});
|
||||
setPuzzleRun(run);
|
||||
} catch (error) {
|
||||
setPuzzleError(resolvePuzzleErrorMessage(error, '准备下一关失败。'));
|
||||
} finally {
|
||||
setIsPuzzleNextLevelGenerating(false);
|
||||
setIsPuzzleBusy(false);
|
||||
}
|
||||
}, [
|
||||
isPuzzleBusy,
|
||||
puzzleRun,
|
||||
puzzleSession,
|
||||
resolvePuzzleErrorMessage,
|
||||
selectedPuzzleDetail,
|
||||
]);
|
||||
|
||||
const leaveAgentWorkspace = useCallback(() => {
|
||||
enterCreateTab();
|
||||
@@ -1802,6 +1901,49 @@ export function PlatformEntryFlowShellImpl({
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{selectionStage === 'big-fish-generating' && (
|
||||
<motion.div
|
||||
key="big-fish-generating"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -12 }}
|
||||
className="flex h-full min-h-0 flex-col"
|
||||
>
|
||||
<Suspense
|
||||
fallback={<LazyPanelFallback label="正在加载大鱼吃小鱼生成面板..." />}
|
||||
>
|
||||
<CustomWorldGenerationView
|
||||
settingText={
|
||||
bigFishSession?.lastAssistantReply ?? '正在整理当前玩法草稿。'
|
||||
}
|
||||
anchorEntries={buildBigFishGenerationAnchorEntries(bigFishSession)}
|
||||
progress={buildMiniGameDraftGenerationProgress(
|
||||
bigFishGenerationState,
|
||||
)}
|
||||
isGenerating={isBigFishBusy}
|
||||
error={bigFishError}
|
||||
onBack={leaveBigFishFlow}
|
||||
onEditSetting={() => {
|
||||
setSelectionStage('big-fish-agent-workspace');
|
||||
}}
|
||||
onRetry={() => {
|
||||
void executeBigFishAction({ action: 'big_fish_compile_draft' });
|
||||
}}
|
||||
onInterrupt={undefined}
|
||||
backLabel="返回创作中心"
|
||||
settingActionLabel={null}
|
||||
retryLabel="重新生成草稿"
|
||||
settingTitle="当前玩法信息"
|
||||
settingDescription={null}
|
||||
progressTitle="大鱼吃小鱼草稿生成进度"
|
||||
activeBadgeLabel="草稿生成中"
|
||||
pausedBadgeLabel="草稿生成已暂停"
|
||||
idleBadgeLabel="等待返回工作区"
|
||||
/>
|
||||
</Suspense>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{selectionStage === 'big-fish-result' && bigFishSession?.draft && (
|
||||
<motion.div
|
||||
key="big-fish-result"
|
||||
@@ -1884,6 +2026,49 @@ export function PlatformEntryFlowShellImpl({
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{selectionStage === 'puzzle-generating' && (
|
||||
<motion.div
|
||||
key="puzzle-generating"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -12 }}
|
||||
className="flex h-full min-h-0 flex-col"
|
||||
>
|
||||
<Suspense
|
||||
fallback={<LazyPanelFallback label="正在加载拼图生成面板..." />}
|
||||
>
|
||||
<CustomWorldGenerationView
|
||||
settingText={
|
||||
puzzleSession?.lastAssistantReply ?? '正在整理当前拼图草稿。'
|
||||
}
|
||||
anchorEntries={buildPuzzleGenerationAnchorEntries(puzzleSession)}
|
||||
progress={buildMiniGameDraftGenerationProgress(
|
||||
puzzleGenerationState,
|
||||
)}
|
||||
isGenerating={isPuzzleBusy}
|
||||
error={puzzleError}
|
||||
onBack={leavePuzzleFlow}
|
||||
onEditSetting={() => {
|
||||
setSelectionStage('puzzle-agent-workspace');
|
||||
}}
|
||||
onRetry={() => {
|
||||
void executePuzzleAction({ action: 'compile_puzzle_draft' });
|
||||
}}
|
||||
onInterrupt={undefined}
|
||||
backLabel="返回创作中心"
|
||||
settingActionLabel={null}
|
||||
retryLabel="重新生成草稿"
|
||||
settingTitle="当前拼图信息"
|
||||
settingDescription={null}
|
||||
progressTitle="拼图草稿生成进度"
|
||||
activeBadgeLabel="草稿生成中"
|
||||
pausedBadgeLabel="草稿生成已暂停"
|
||||
idleBadgeLabel="等待返回工作区"
|
||||
/>
|
||||
</Suspense>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{selectionStage === 'puzzle-result' && puzzleSession?.draft && (
|
||||
<motion.div
|
||||
key="puzzle-result"
|
||||
@@ -1940,7 +2125,7 @@ export function PlatformEntryFlowShellImpl({
|
||||
>
|
||||
<PuzzleRuntimeShell
|
||||
run={puzzleRun}
|
||||
isBusy={isPuzzleBusy}
|
||||
isBusy={isPuzzleBusy || isPuzzleNextLevelGenerating}
|
||||
error={puzzleError}
|
||||
onBack={() => {
|
||||
setSelectionStage('puzzle-gallery-detail');
|
||||
@@ -1955,6 +2140,17 @@ export function PlatformEntryFlowShellImpl({
|
||||
void advancePuzzleLevel();
|
||||
}}
|
||||
/>
|
||||
{isPuzzleNextLevelGenerating ? (
|
||||
<div className="fixed inset-0 z-[120] flex items-center justify-center bg-slate-950/62 px-5 backdrop-blur-sm">
|
||||
<div className="flex max-w-[18rem] flex-col items-center gap-3 rounded-[1.5rem] border border-white/12 bg-slate-950/92 px-6 py-5 text-center text-white shadow-[0_28px_80px_rgba(0,0,0,0.35)]">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-amber-200" />
|
||||
<div className="text-sm font-bold">正在准备下一关</div>
|
||||
<div className="text-xs leading-5 text-white/68">
|
||||
广场暂无可接续作品,正在生成新的候选图。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ export type SelectionStage =
|
||||
| 'detail'
|
||||
| 'agent-workspace'
|
||||
| 'big-fish-agent-workspace'
|
||||
| 'big-fish-generating'
|
||||
| 'big-fish-result'
|
||||
| 'big-fish-runtime'
|
||||
| 'puzzle-agent-workspace'
|
||||
| 'puzzle-generating'
|
||||
| 'puzzle-result'
|
||||
| 'puzzle-gallery-detail'
|
||||
| 'puzzle-runtime'
|
||||
|
||||
283
src/services/miniGameDraftGenerationProgress.ts
Normal file
283
src/services/miniGameDraftGenerationProgress.ts
Normal file
@@ -0,0 +1,283 @@
|
||||
import type { BigFishSessionSnapshotResponse } from '../../packages/shared/src/contracts/bigFish';
|
||||
import type { PuzzleAgentSessionSnapshot } from '../../packages/shared/src/contracts/puzzleAgentSession';
|
||||
import type {
|
||||
CustomWorldGenerationProgress,
|
||||
CustomWorldGenerationStep,
|
||||
} from '../../packages/shared/src/contracts/runtime';
|
||||
import type { CustomWorldStructuredAnchorEntry } from './customWorldAgentGenerationProgress';
|
||||
|
||||
export type MiniGameDraftGenerationKind = 'puzzle' | 'big-fish';
|
||||
|
||||
export type MiniGameDraftGenerationPhase =
|
||||
| 'idle'
|
||||
| 'compile'
|
||||
| 'puzzle-images'
|
||||
| 'puzzle-select-image'
|
||||
| 'big-fish-main-images'
|
||||
| 'big-fish-motions'
|
||||
| 'big-fish-background'
|
||||
| 'ready'
|
||||
| 'failed';
|
||||
|
||||
export type MiniGameDraftGenerationState = {
|
||||
kind: MiniGameDraftGenerationKind;
|
||||
phase: MiniGameDraftGenerationPhase;
|
||||
startedAtMs: number;
|
||||
completedAssetCount: number;
|
||||
totalAssetCount: number;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
type MiniGameStepDefinition = {
|
||||
id: MiniGameDraftGenerationPhase;
|
||||
label: string;
|
||||
detail: string;
|
||||
weight: number;
|
||||
};
|
||||
|
||||
type MiniGameAnchorSource = {
|
||||
key: string;
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
const PUZZLE_STEPS = [
|
||||
{
|
||||
id: 'compile',
|
||||
label: '编译拼图草稿',
|
||||
detail: '整理主题、主体、构图与标签。',
|
||||
weight: 34,
|
||||
},
|
||||
{
|
||||
id: 'puzzle-images',
|
||||
label: '生成拼图图片',
|
||||
detail: '根据草稿生成候选图。',
|
||||
weight: 33,
|
||||
},
|
||||
{
|
||||
id: 'puzzle-select-image',
|
||||
label: '确认正式图片',
|
||||
detail: '选择候选图写入结果页。',
|
||||
weight: 33,
|
||||
},
|
||||
] as const satisfies ReadonlyArray<MiniGameStepDefinition>;
|
||||
|
||||
const BIG_FISH_STEPS = [
|
||||
{
|
||||
id: 'compile',
|
||||
label: '编译玩法草稿',
|
||||
detail: '生成关卡角色描述、生态背景与运行参数。',
|
||||
weight: 25,
|
||||
},
|
||||
{
|
||||
id: 'big-fish-main-images',
|
||||
label: '生成角色图片',
|
||||
detail: '为每个成长阶段生成主形象。',
|
||||
weight: 30,
|
||||
},
|
||||
{
|
||||
id: 'big-fish-motions',
|
||||
label: '生成动作素材',
|
||||
detail: '补齐漂浮与游动动作素材。',
|
||||
weight: 30,
|
||||
},
|
||||
{
|
||||
id: 'big-fish-background',
|
||||
label: '生成场地背景',
|
||||
detail: '生成玩法场地背景图。',
|
||||
weight: 15,
|
||||
},
|
||||
] as const satisfies ReadonlyArray<MiniGameStepDefinition>;
|
||||
|
||||
function clampProgress(value: number) {
|
||||
return Math.max(0, Math.min(100, Math.round(value)));
|
||||
}
|
||||
|
||||
function getStepDefinitions(kind: MiniGameDraftGenerationKind) {
|
||||
return kind === 'puzzle' ? PUZZLE_STEPS : BIG_FISH_STEPS;
|
||||
}
|
||||
|
||||
function getActiveStepIndex(
|
||||
steps: ReadonlyArray<MiniGameStepDefinition>,
|
||||
phase: MiniGameDraftGenerationPhase,
|
||||
) {
|
||||
if (phase === 'ready') {
|
||||
return steps.length - 1;
|
||||
}
|
||||
const index = steps.findIndex((step) => step.id === phase);
|
||||
return index >= 0 ? index : 0;
|
||||
}
|
||||
|
||||
function buildMiniGameProgressSteps(
|
||||
steps: ReadonlyArray<MiniGameStepDefinition>,
|
||||
activeStepIndex: number,
|
||||
state: MiniGameDraftGenerationState,
|
||||
) {
|
||||
return steps.map((step, index) => {
|
||||
const isCompleted = state.phase === 'ready' || index < activeStepIndex;
|
||||
const isActive = state.phase !== 'failed' && !isCompleted && index === activeStepIndex;
|
||||
const isAssetStep = step.id === state.phase && state.totalAssetCount > 0;
|
||||
|
||||
return {
|
||||
id: step.id,
|
||||
label: step.label,
|
||||
detail: step.detail,
|
||||
completed: isCompleted
|
||||
? 1
|
||||
: isAssetStep
|
||||
? state.completedAssetCount
|
||||
: 0,
|
||||
total: isAssetStep ? state.totalAssetCount : 1,
|
||||
status: isCompleted ? 'completed' : isActive ? 'active' : 'pending',
|
||||
} satisfies CustomWorldGenerationStep;
|
||||
});
|
||||
}
|
||||
|
||||
export function createMiniGameDraftGenerationState(
|
||||
kind: MiniGameDraftGenerationKind,
|
||||
): MiniGameDraftGenerationState {
|
||||
return {
|
||||
kind,
|
||||
phase: 'compile',
|
||||
startedAtMs: Date.now(),
|
||||
completedAssetCount: 0,
|
||||
totalAssetCount: 0,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildMiniGameDraftGenerationProgress(
|
||||
state: MiniGameDraftGenerationState | null,
|
||||
nowMs = Date.now(),
|
||||
): CustomWorldGenerationProgress | null {
|
||||
if (!state) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const steps = getStepDefinitions(state.kind);
|
||||
const activeStepIndex = getActiveStepIndex(steps, state.phase);
|
||||
const completedWeight = steps
|
||||
.slice(0, state.phase === 'ready' ? steps.length : activeStepIndex)
|
||||
.reduce((sum, step) => sum + step.weight, 0);
|
||||
const activeStep = steps[activeStepIndex] ?? steps[0];
|
||||
const assetRatio =
|
||||
state.totalAssetCount > 0
|
||||
? Math.min(1, state.completedAssetCount / state.totalAssetCount)
|
||||
: state.phase === 'ready'
|
||||
? 1
|
||||
: 0;
|
||||
const overallProgress =
|
||||
state.phase === 'failed'
|
||||
? Math.max(1, completedWeight)
|
||||
: state.phase === 'ready'
|
||||
? 100
|
||||
: completedWeight + activeStep.weight * assetRatio;
|
||||
|
||||
return {
|
||||
phaseId: state.phase,
|
||||
phaseLabel:
|
||||
state.phase === 'failed'
|
||||
? '生成失败'
|
||||
: state.phase === 'ready'
|
||||
? '生成完成'
|
||||
: activeStep.label,
|
||||
phaseDetail:
|
||||
state.error ??
|
||||
(state.phase === 'ready'
|
||||
? '完整草稿与资产已准备完成。'
|
||||
: activeStep.detail),
|
||||
batchLabel: activeStep.label,
|
||||
overallProgress: clampProgress(overallProgress),
|
||||
completedWeight: clampProgress(overallProgress),
|
||||
totalWeight: 100,
|
||||
elapsedMs: Math.max(0, nowMs - state.startedAtMs),
|
||||
estimatedRemainingMs: state.phase === 'ready' ? 0 : null,
|
||||
activeStepIndex,
|
||||
steps: buildMiniGameProgressSteps(steps, activeStepIndex, state),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPuzzleGenerationAnchorEntries(
|
||||
session: PuzzleAgentSessionSnapshot | null | undefined,
|
||||
): CustomWorldStructuredAnchorEntry[] {
|
||||
if (!session) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const draft = session.draft;
|
||||
const entries: Array<MiniGameAnchorSource | null> = [
|
||||
session.anchorPack.themePromise,
|
||||
session.anchorPack.visualSubject,
|
||||
session.anchorPack.visualMood,
|
||||
session.anchorPack.compositionHooks,
|
||||
session.anchorPack.tagsAndForbidden,
|
||||
draft
|
||||
? {
|
||||
key: 'draft-summary',
|
||||
label: '草稿摘要',
|
||||
value: draft.summary,
|
||||
}
|
||||
: null,
|
||||
draft?.coverImageSrc
|
||||
? {
|
||||
key: 'cover-image',
|
||||
label: '正式图片',
|
||||
value: '已生成并应用',
|
||||
}
|
||||
: null,
|
||||
];
|
||||
|
||||
return entries
|
||||
.filter((entry): entry is MiniGameAnchorSource => Boolean(entry))
|
||||
.map((entry) => ({
|
||||
id: entry.key,
|
||||
label: entry.label,
|
||||
value: entry.value,
|
||||
}))
|
||||
.filter((entry) => entry.value.trim());
|
||||
}
|
||||
|
||||
export function buildBigFishGenerationAnchorEntries(
|
||||
session: BigFishSessionSnapshotResponse | null | undefined,
|
||||
): CustomWorldStructuredAnchorEntry[] {
|
||||
if (!session) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const draft = session.draft;
|
||||
const assetReadyCount = session.assetSlots.filter(
|
||||
(slot) => slot.status === 'ready',
|
||||
).length;
|
||||
|
||||
const entries: Array<MiniGameAnchorSource | null> = [
|
||||
session.anchorPack.gameplayPromise,
|
||||
session.anchorPack.ecologyVisualTheme,
|
||||
session.anchorPack.growthLadder,
|
||||
session.anchorPack.riskTempo,
|
||||
draft
|
||||
? {
|
||||
key: 'level-characters',
|
||||
label: '角色描述',
|
||||
value: draft.levels
|
||||
.map((level) => `Lv.${level.level} ${level.name}:${level.oneLineFantasy}`)
|
||||
.join('\n'),
|
||||
}
|
||||
: null,
|
||||
draft
|
||||
? {
|
||||
key: 'asset-coverage',
|
||||
label: '图片与动作',
|
||||
value: `已生成 ${assetReadyCount}/${session.assetSlots.length} 个资产`,
|
||||
}
|
||||
: null,
|
||||
];
|
||||
|
||||
return entries
|
||||
.filter((entry): entry is MiniGameAnchorSource => Boolean(entry))
|
||||
.map((entry) => ({
|
||||
id: entry.key,
|
||||
label: entry.label,
|
||||
value: entry.value,
|
||||
}))
|
||||
.filter((entry) => entry.value.trim());
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export {
|
||||
advanceLocalPuzzleNextLevel,
|
||||
advancePuzzleNextLevel,
|
||||
dragPuzzlePieceOrGroup,
|
||||
getPuzzleRun,
|
||||
|
||||
@@ -112,13 +112,13 @@ function buildLocalNextProfileId(entryProfileId: string, levelIndex: number) {
|
||||
return `${entryProfileId}::local-level-${levelIndex}`;
|
||||
}
|
||||
|
||||
// 第一版单机玩法没有后端推荐池,本地沿用当前作品图片并生成可推进的临时关卡名。
|
||||
// 第一版单机兜底没有后端推荐池时,才沿用当前作品图片生成可推进的临时关卡名。
|
||||
function buildLocalLevelName(previousLevelName: string, levelIndex: number) {
|
||||
return `${previousLevelName.replace(/ · 第 \d+ 关$/, '')} · 第 ${levelIndex} 关`;
|
||||
}
|
||||
|
||||
// 本地运行态只保证单次游玩闭环:通关后立即重建下一关棋盘,不写回后端。
|
||||
function buildNextLocalLevel(run: PuzzleRunSnapshot): PuzzleRunSnapshot {
|
||||
// 本地兜底只保证单次游玩闭环:通关后立即重建下一关棋盘,不写回后端。
|
||||
function buildFallbackLocalLevel(run: PuzzleRunSnapshot): PuzzleRunSnapshot {
|
||||
const currentLevel = run.currentLevel;
|
||||
if (!currentLevel || currentLevel.status !== 'cleared') {
|
||||
return run;
|
||||
@@ -240,5 +240,5 @@ export function dragLocalPuzzlePiece(
|
||||
}
|
||||
|
||||
export function advanceLocalPuzzleLevel(run: PuzzleRunSnapshot): PuzzleRunSnapshot {
|
||||
return buildNextLocalLevel(run);
|
||||
return buildFallbackLocalLevel(run);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
AdvanceLocalPuzzleNextLevelRequest,
|
||||
DragPuzzlePieceRequest,
|
||||
PuzzleRunResponse,
|
||||
StartPuzzleRunRequest,
|
||||
@@ -111,7 +112,28 @@ export async function advancePuzzleNextLevel(runId: string) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单机运行态进入下一关,图片来源选择全部由后端裁决。
|
||||
*/
|
||||
export async function advanceLocalPuzzleNextLevel(
|
||||
payload: AdvanceLocalPuzzleNextLevelRequest,
|
||||
) {
|
||||
return requestJson<PuzzleRunResponse>(
|
||||
`${PUZZLE_RUNTIME_API_BASE}/local-next-level`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
'进入下一关失败',
|
||||
{
|
||||
retry: PUZZLE_RUNTIME_WRITE_RETRY,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export const puzzleRuntimeClient = {
|
||||
advanceLocalNextLevel: advanceLocalPuzzleNextLevel,
|
||||
advanceNextLevel: advancePuzzleNextLevel,
|
||||
drag: dragPuzzlePieceOrGroup,
|
||||
getRun: getPuzzleRun,
|
||||
|
||||
Reference in New Issue
Block a user