From 9cb3c6a27eb422d6eea2b1ca2fead7cb8cfc0165 Mon Sep 17 00:00:00 2001 From: kdletters Date: Sat, 25 Apr 2026 15:17:01 +0800 Subject: [PATCH 1/4] feat: add puzzle and big fish draft generation progress --- ...GENT_ACTION_RESPONSE_SESSION_2026-04-25.md | 18 + ...AFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md | 46 +++ docs/technical/README.md | 2 + .../src/contracts/puzzleAgentActions.ts | 6 + server-rs/crates/api-server/src/big_fish.rs | 103 ++++- server-rs/crates/api-server/src/puzzle.rs | 87 +++- .../shared-contracts/src/puzzle_agent.rs | 2 + .../PlatformEntryFlowShellImpl.tsx | 382 ++++++++++++++++-- .../platform-entry/platformEntryTypes.ts | 2 + .../miniGameDraftGenerationProgress.ts | 283 +++++++++++++ 10 files changed, 898 insertions(+), 33 deletions(-) create mode 100644 docs/technical/PUZZLE_AGENT_ACTION_RESPONSE_SESSION_2026-04-25.md create mode 100644 docs/technical/PUZZLE_BIG_FISH_DRAFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md create mode 100644 src/services/miniGameDraftGenerationProgress.ts diff --git a/docs/technical/PUZZLE_AGENT_ACTION_RESPONSE_SESSION_2026-04-25.md b/docs/technical/PUZZLE_AGENT_ACTION_RESPONSE_SESSION_2026-04-25.md new file mode 100644 index 00000000..2b3c7a8d --- /dev/null +++ b/docs/technical/PUZZLE_AGENT_ACTION_RESPONSE_SESSION_2026-04-25.md @@ -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. 发布后仍能跳转到已发布拼图详情。 diff --git a/docs/technical/PUZZLE_BIG_FISH_DRAFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md b/docs/technical/PUZZLE_BIG_FISH_DRAFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md new file mode 100644 index 00000000..f6fc2d94 --- /dev/null +++ b/docs/technical/PUZZLE_BIG_FISH_DRAFT_PROGRESS_AND_ASSET_CHAIN_2026-04-25.md @@ -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 静态资产路径。 diff --git a/docs/technical/README.md b/docs/technical/README.md index 71b524d2..94cf0eb0 100644 --- a/docs/technical/README.md +++ b/docs/technical/README.md @@ -5,10 +5,12 @@ ## 文档列表 - [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 字段的修复口径。 diff --git a/packages/shared/src/contracts/puzzleAgentActions.ts b/packages/shared/src/contracts/puzzleAgentActions.ts index 183ec46a..2cc6c2c4 100644 --- a/packages/shared/src/contracts/puzzleAgentActions.ts +++ b/packages/shared/src/contracts/puzzleAgentActions.ts @@ -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; } diff --git a/server-rs/crates/api-server/src/big_fish.rs b/server-rs/crates/api-server/src/big_fish.rs index 3079bcec..dbc9acee 100644 --- a/server-rs/crates/api-server/src/big_fish.rs +++ b/server-rs/crates/api-server/src/big_fish.rs @@ -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 { + 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 { diff --git a/server-rs/crates/api-server/src/puzzle.rs b/server-rs/crates/api-server/src/puzzle.rs index 5f665ed3..5a216bd5 100644 --- a/server-rs/crates/api-server/src/puzzle.rs +++ b/server-rs/crates/api-server/src/puzzle.rs @@ -435,14 +435,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 +575,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 +599,7 @@ pub async fn execute_puzzle_agent_action( progress: 100, error: None, }, + session: map_puzzle_agent_session_response(session), }, )); } @@ -616,6 +632,7 @@ pub async fn execute_puzzle_agent_action( progress: 100, error: None, }, + session: map_puzzle_agent_session_response(session), }, )) } @@ -1336,6 +1353,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 { + 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::>(), + ) + .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, diff --git a/server-rs/crates/shared-contracts/src/puzzle_agent.rs b/server-rs/crates/shared-contracts/src/puzzle_agent.rs index 8275c885..42a6c279 100644 --- a/server-rs/crates/shared-contracts/src/puzzle_agent.rs +++ b/server-rs/crates/shared-contracts/src/puzzle_agent.rs @@ -187,4 +187,6 @@ pub struct PuzzleAgentOperationResponse { #[serde(rename_all = "camelCase")] pub struct PuzzleAgentActionResponse { pub operation: PuzzleAgentOperationResponse, + /// 操作完成后的最新会话快照,供前端直接更新界面,避免重复拉取完整 session。 + pub session: PuzzleAgentSessionSnapshotResponse, } diff --git a/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx b/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx index b4ee6fb0..51b2f5ac 100644 --- a/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx +++ b/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx @@ -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, @@ -21,6 +23,7 @@ import type { PuzzleAgentActionRequest, PuzzleAgentOperationRecord, } from '../../../packages/shared/src/contracts/puzzleAgentActions'; +import type { PuzzleGeneratedImageCandidate } from '../../../packages/shared/src/contracts/puzzleAgentDraft'; import type { PuzzleAgentSessionSnapshot, SendPuzzleAgentMessageRequest, @@ -31,7 +34,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 +45,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, @@ -59,18 +68,22 @@ import { getPuzzleAgentSession, streamPuzzleAgentMessage, } from '../../services/puzzle-agent'; -import { getPuzzleGalleryDetail } from '../../services/puzzle-gallery'; +import { + getPuzzleGalleryDetail, + listPuzzleGallery, +} from '../../services/puzzle-gallery'; import { advanceLocalPuzzleLevel, + advanceLocalPuzzleLevelWithWork, 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 +96,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'; @@ -101,6 +114,53 @@ type AgentResultPublishGateView = { publishReady: boolean; }; +function buildPuzzleCandidateWorkSummary( + candidate: PuzzleGeneratedImageCandidate, + session: PuzzleAgentSessionSnapshot, + levelIndex: number, +): PuzzleWorkSummary { + const draft = session.draft; + const nowIso = new Date().toISOString(); + return { + workId: `${session.sessionId}-${candidate.candidateId}-level-${levelIndex}-runtime-work`, + profileId: `${session.sessionId}-${candidate.candidateId}-level-${levelIndex}-runtime-profile`, + ownerUserId: 'local-runtime', + sourceSessionId: session.sessionId, + authorDisplayName: '当前草稿', + levelName: draft?.levelName + ? `${draft.levelName} · 候选 ${levelIndex}` + : `候选拼图 ${levelIndex}`, + summary: draft?.summary ?? candidate.prompt, + themeTags: draft?.themeTags ?? [], + coverImageSrc: candidate.imageSrc, + coverAssetId: candidate.assetId, + publicationStatus: 'published', + updatedAt: nowIso, + publishedAt: nowIso, + playCount: 0, + publishReady: true, + }; +} + +function pickPuzzleCandidateForLevel( + candidates: PuzzleGeneratedImageCandidate[], + playedProfileIds: string[], +) { + return candidates.find( + (candidate) => + candidate.imageSrc && + !playedProfileIds.some((profileId) => + profileId.includes(candidate.candidateId), + ), + ); +} + +function pickFreshGeneratedPuzzleCandidate( + candidates: PuzzleGeneratedImageCandidate[], +) { + return candidates.find((candidate) => candidate.imageSrc); +} + type AgentResultBlockerView = { code?: string; message: string; @@ -312,6 +372,8 @@ export function PlatformEntryFlowShellImpl({ const [bigFishError, setBigFishError] = useState(null); const [isBigFishBusy, setIsBigFishBusy] = useState(false); const [isBigFishLoadingLibrary, setIsBigFishLoadingLibrary] = useState(false); + const [bigFishGenerationState, setBigFishGenerationState] = + useState(null); const [streamingBigFishReplyText, setStreamingBigFishReplyText] = useState(''); const [isStreamingBigFishReply, setIsStreamingBigFishReply] = useState(false); @@ -327,6 +389,10 @@ export function PlatformEntryFlowShellImpl({ const [puzzleError, setPuzzleError] = useState(null); const [isPuzzleBusy, setIsPuzzleBusy] = useState(false); const [isPuzzleLoadingLibrary, setIsPuzzleLoadingLibrary] = useState(false); + const [puzzleGenerationState, setPuzzleGenerationState] = + useState(null); + const [isPuzzleNextLevelGenerating, setIsPuzzleNextLevelGenerating] = + useState(false); const [isSearchingPublicCode, setIsSearchingPublicCode] = useState(false); const [publicSearchError, setPublicSearchError] = useState(null); const [searchedPublicUser, setSearchedPublicUser] = @@ -791,6 +857,7 @@ export function PlatformEntryFlowShellImpl({ const leaveBigFishFlow = useCallback(() => { setBigFishError(null); setBigFishRun(null); + setBigFishGenerationState(null); setStreamingBigFishReplyText(''); setIsStreamingBigFishReply(false); enterCreateTab(); @@ -801,6 +868,8 @@ export function PlatformEntryFlowShellImpl({ setPuzzleError(null); setPuzzleOperation(null); setPuzzleRun(null); + setPuzzleGenerationState(null); + setIsPuzzleNextLevelGenerating(false); setStreamingPuzzleReplyText(''); setIsStreamingPuzzleReply(false); enterCreateTab(); @@ -913,15 +982,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 +1046,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 +1079,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 +1092,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 +1220,123 @@ export function PlatformEntryFlowShellImpl({ return; } + const currentLevel = puzzleRun.currentLevel; + if (!currentLevel || currentLevel.status !== 'cleared') { + return; + } + + setIsPuzzleBusy(true); setPuzzleError(null); - setPuzzleRun(advanceLocalPuzzleLevel(puzzleRun)); - }, [isPuzzleBusy, puzzleRun]); + + try { + const galleryResponse = await listPuzzleGallery(); + setPuzzleWorks(galleryResponse.items); + const galleryNext = galleryResponse.items.find( + (item) => + item.publicationStatus === 'published' && + item.coverImageSrc && + !puzzleRun.playedProfileIds.includes(item.profileId), + ); + if (galleryNext) { + const { item } = await getPuzzleGalleryDetail(galleryNext.profileId); + setSelectedPuzzleDetail(item); + setPuzzleRun(advanceLocalPuzzleLevelWithWork(puzzleRun, item)); + return; + } + + const existingCandidate = pickPuzzleCandidateForLevel( + puzzleSession?.draft?.candidates ?? [], + puzzleRun.playedProfileIds, + ); + if (existingCandidate && puzzleSession) { + setPuzzleRun( + advanceLocalPuzzleLevelWithWork( + puzzleRun, + buildPuzzleCandidateWorkSummary( + existingCandidate, + puzzleSession, + puzzleRun.currentLevelIndex + 1, + ), + ), + ); + return; + } + + if (!puzzleSession?.draft) { + const sourceSessionId = selectedPuzzleDetail?.sourceSessionId?.trim(); + if (sourceSessionId) { + const { session } = await getPuzzleAgentSession(sourceSessionId); + setPuzzleSession(session); + if (session.draft) { + setIsPuzzleNextLevelGenerating(true); + const response = await executePuzzleAgentAction(session.sessionId, { + action: 'generate_puzzle_images', + candidateCount: 2, + }); + setPuzzleOperation(response.operation); + setPuzzleSession(response.session); + const sourceSessionCandidate = pickPuzzleCandidateForLevel( + response.session.draft?.candidates ?? [], + puzzleRun.playedProfileIds, + ); + if (sourceSessionCandidate) { + setPuzzleRun( + advanceLocalPuzzleLevelWithWork( + puzzleRun, + buildPuzzleCandidateWorkSummary( + sourceSessionCandidate, + response.session, + puzzleRun.currentLevelIndex + 1, + ), + ), + ); + return; + } + } + } + throw new Error('当前拼图缺少可用于生成下一关的草稿会话。'); + } + + setIsPuzzleNextLevelGenerating(true); + const response = await executePuzzleAgentAction(puzzleSession.sessionId, { + action: 'generate_puzzle_images', + candidateCount: 2, + }); + setPuzzleOperation(response.operation); + setPuzzleSession(response.session); + + const generatedCandidate = pickPuzzleCandidateForLevel( + response.session.draft?.candidates ?? [], + puzzleRun.playedProfileIds, + ); + if (generatedCandidate) { + setPuzzleRun( + advanceLocalPuzzleLevelWithWork( + puzzleRun, + buildPuzzleCandidateWorkSummary( + generatedCandidate, + response.session, + puzzleRun.currentLevelIndex + 1, + ), + ), + ); + return; + } + + setPuzzleRun(advanceLocalPuzzleLevel(puzzleRun)); + } catch (error) { + setPuzzleError(resolvePuzzleErrorMessage(error, '准备下一关失败。')); + } finally { + setIsPuzzleNextLevelGenerating(false); + setIsPuzzleBusy(false); + } + }, [ + isPuzzleBusy, + puzzleRun, + puzzleSession, + resolvePuzzleErrorMessage, + selectedPuzzleDetail, + ]); const leaveAgentWorkspace = useCallback(() => { enterCreateTab(); @@ -1802,6 +2041,49 @@ export function PlatformEntryFlowShellImpl({ )} + {selectionStage === 'big-fish-generating' && ( + + } + > + { + 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="等待返回工作区" + /> + + + )} + {selectionStage === 'big-fish-result' && bigFishSession?.draft && ( )} + {selectionStage === 'puzzle-generating' && ( + + } + > + { + setSelectionStage('puzzle-agent-workspace'); + }} + onRetry={() => { + void executePuzzleAction({ action: 'compile_puzzle_draft' }); + }} + onInterrupt={undefined} + backLabel="返回创作中心" + settingActionLabel={null} + retryLabel="重新生成草稿" + settingTitle="当前拼图信息" + settingDescription={null} + progressTitle="拼图草稿生成进度" + activeBadgeLabel="草稿生成中" + pausedBadgeLabel="草稿生成已暂停" + idleBadgeLabel="等待返回工作区" + /> + + + )} + {selectionStage === 'puzzle-result' && puzzleSession?.draft && ( { setSelectionStage('puzzle-gallery-detail'); @@ -1955,6 +2280,17 @@ export function PlatformEntryFlowShellImpl({ void advancePuzzleLevel(); }} /> + {isPuzzleNextLevelGenerating ? ( +
+
+ +
正在准备下一关
+
+ 广场暂无可接续作品,正在生成新的候选图。 +
+
+
+ ) : null}
)} diff --git a/src/components/platform-entry/platformEntryTypes.ts b/src/components/platform-entry/platformEntryTypes.ts index d7d76c5c..081c98a8 100644 --- a/src/components/platform-entry/platformEntryTypes.ts +++ b/src/components/platform-entry/platformEntryTypes.ts @@ -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' diff --git a/src/services/miniGameDraftGenerationProgress.ts b/src/services/miniGameDraftGenerationProgress.ts new file mode 100644 index 00000000..07b7da1f --- /dev/null +++ b/src/services/miniGameDraftGenerationProgress.ts @@ -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; + +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; + +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, + 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, + 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 = [ + 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 = [ + 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()); +} From 4e04679ba4036bf30c3881f95f3608bab356918a Mon Sep 17 00:00:00 2001 From: kdletters Date: Sat, 25 Apr 2026 15:55:05 +0800 Subject: [PATCH 2/4] fix: move puzzle next level source selection server side --- ...E_PLAYER_AND_REAL_IMAGE_PLAN_2026-04-24.md | 15 +- .../src/contracts/puzzleRuntimeSession.ts | 5 + server-rs/crates/api-server/src/app.rs | 18 +- server-rs/crates/api-server/src/puzzle.rs | 353 +++++++++++++++++- .../shared-contracts/src/puzzle_runtime.rs | 8 + .../PlatformEntryFlowShellImpl.tsx | 156 +------- src/services/puzzle-runtime/index.ts | 1 + .../puzzle-runtime/puzzleLocalRuntime.ts | 8 +- .../puzzle-runtime/puzzleRuntimeClient.ts | 22 ++ 9 files changed, 418 insertions(+), 168 deletions(-) diff --git a/docs/technical/PUZZLE_SINGLE_PLAYER_AND_REAL_IMAGE_PLAN_2026-04-24.md b/docs/technical/PUZZLE_SINGLE_PLAYER_AND_REAL_IMAGE_PLAN_2026-04-24.md index 9fb0373d..f945798c 100644 --- a/docs/technical/PUZZLE_SINGLE_PLAYER_AND_REAL_IMAGE_PLAN_2026-04-24.md +++ b/docs/technical/PUZZLE_SINGLE_PLAYER_AND_REAL_IMAGE_PLAN_2026-04-24.md @@ -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 进度。 diff --git a/packages/shared/src/contracts/puzzleRuntimeSession.ts b/packages/shared/src/contracts/puzzleRuntimeSession.ts index de8cf815..22ebcf83 100644 --- a/packages/shared/src/contracts/puzzleRuntimeSession.ts +++ b/packages/shared/src/contracts/puzzleRuntimeSession.ts @@ -58,6 +58,11 @@ export interface StartPuzzleRunRequest { profileId: string; } +export interface AdvanceLocalPuzzleNextLevelRequest { + run: PuzzleRunSnapshot; + sourceSessionId?: string | null; +} + export interface PuzzleRunResponse { run: PuzzleRunSnapshot; } diff --git a/server-rs/crates/api-server/src/app.rs b/server-rs/crates/api-server/src/app.rs index 7e19a372..6305d190 100644 --- a/server-rs/crates/api-server/src/app.rs +++ b/server-rs/crates/api-server/src/app.rs @@ -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}, @@ -626,6 +627,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( diff --git a/server-rs/crates/api-server/src/puzzle.rs b/server-rs/crates/api-server/src/puzzle.rs index 5a216bd5..c2a2bb33 100644 --- a/server-rs/crates/api-server/src/puzzle.rs +++ b/server-rs/crates/api-server/src/puzzle.rs @@ -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; @@ -1063,6 +1064,36 @@ pub async fn advance_puzzle_next_level( )) } +pub async fn advance_local_puzzle_next_level( + State(state): State, + Extension(request_context): Extension, + Extension(authenticated): Extension, + payload: Result, JsonRejection>, +) -> Result, 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 { @@ -1265,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 { @@ -1574,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 { + 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::>(), + ) + .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, 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, + cover_image_src: Option, +) -> 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::>(); + 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, diff --git a/server-rs/crates/shared-contracts/src/puzzle_runtime.rs b/server-rs/crates/shared-contracts/src/puzzle_runtime.rs index 62caa0b1..1c3d6452 100644 --- a/server-rs/crates/shared-contracts/src/puzzle_runtime.rs +++ b/server-rs/crates/shared-contracts/src/puzzle_runtime.rs @@ -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, +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SwapPuzzlePiecesRequest { diff --git a/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx b/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx index 51b2f5ac..7197eb0a 100644 --- a/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx +++ b/src/components/platform-entry/PlatformEntryFlowShellImpl.tsx @@ -23,7 +23,6 @@ import type { PuzzleAgentActionRequest, PuzzleAgentOperationRecord, } from '../../../packages/shared/src/contracts/puzzleAgentActions'; -import type { PuzzleGeneratedImageCandidate } from '../../../packages/shared/src/contracts/puzzleAgentDraft'; import type { PuzzleAgentSessionSnapshot, SendPuzzleAgentMessageRequest, @@ -68,13 +67,9 @@ import { getPuzzleAgentSession, streamPuzzleAgentMessage, } from '../../services/puzzle-agent'; +import { getPuzzleGalleryDetail } from '../../services/puzzle-gallery'; +import { advanceLocalPuzzleNextLevel } from '../../services/puzzle-runtime'; import { - getPuzzleGalleryDetail, - listPuzzleGallery, -} from '../../services/puzzle-gallery'; -import { - advanceLocalPuzzleLevel, - advanceLocalPuzzleLevelWithWork, dragLocalPuzzlePiece, startLocalPuzzleRun, swapLocalPuzzlePieces, @@ -114,53 +109,6 @@ type AgentResultPublishGateView = { publishReady: boolean; }; -function buildPuzzleCandidateWorkSummary( - candidate: PuzzleGeneratedImageCandidate, - session: PuzzleAgentSessionSnapshot, - levelIndex: number, -): PuzzleWorkSummary { - const draft = session.draft; - const nowIso = new Date().toISOString(); - return { - workId: `${session.sessionId}-${candidate.candidateId}-level-${levelIndex}-runtime-work`, - profileId: `${session.sessionId}-${candidate.candidateId}-level-${levelIndex}-runtime-profile`, - ownerUserId: 'local-runtime', - sourceSessionId: session.sessionId, - authorDisplayName: '当前草稿', - levelName: draft?.levelName - ? `${draft.levelName} · 候选 ${levelIndex}` - : `候选拼图 ${levelIndex}`, - summary: draft?.summary ?? candidate.prompt, - themeTags: draft?.themeTags ?? [], - coverImageSrc: candidate.imageSrc, - coverAssetId: candidate.assetId, - publicationStatus: 'published', - updatedAt: nowIso, - publishedAt: nowIso, - playCount: 0, - publishReady: true, - }; -} - -function pickPuzzleCandidateForLevel( - candidates: PuzzleGeneratedImageCandidate[], - playedProfileIds: string[], -) { - return candidates.find( - (candidate) => - candidate.imageSrc && - !playedProfileIds.some((profileId) => - profileId.includes(candidate.candidateId), - ), - ); -} - -function pickFreshGeneratedPuzzleCandidate( - candidates: PuzzleGeneratedImageCandidate[], -) { - return candidates.find((candidate) => candidate.imageSrc); -} - type AgentResultBlockerView = { code?: string; message: string; @@ -1226,104 +1174,16 @@ export function PlatformEntryFlowShellImpl({ } setIsPuzzleBusy(true); + setIsPuzzleNextLevelGenerating(true); setPuzzleError(null); try { - const galleryResponse = await listPuzzleGallery(); - setPuzzleWorks(galleryResponse.items); - const galleryNext = galleryResponse.items.find( - (item) => - item.publicationStatus === 'published' && - item.coverImageSrc && - !puzzleRun.playedProfileIds.includes(item.profileId), - ); - if (galleryNext) { - const { item } = await getPuzzleGalleryDetail(galleryNext.profileId); - setSelectedPuzzleDetail(item); - setPuzzleRun(advanceLocalPuzzleLevelWithWork(puzzleRun, item)); - return; - } - - const existingCandidate = pickPuzzleCandidateForLevel( - puzzleSession?.draft?.candidates ?? [], - puzzleRun.playedProfileIds, - ); - if (existingCandidate && puzzleSession) { - setPuzzleRun( - advanceLocalPuzzleLevelWithWork( - puzzleRun, - buildPuzzleCandidateWorkSummary( - existingCandidate, - puzzleSession, - puzzleRun.currentLevelIndex + 1, - ), - ), - ); - return; - } - - if (!puzzleSession?.draft) { - const sourceSessionId = selectedPuzzleDetail?.sourceSessionId?.trim(); - if (sourceSessionId) { - const { session } = await getPuzzleAgentSession(sourceSessionId); - setPuzzleSession(session); - if (session.draft) { - setIsPuzzleNextLevelGenerating(true); - const response = await executePuzzleAgentAction(session.sessionId, { - action: 'generate_puzzle_images', - candidateCount: 2, - }); - setPuzzleOperation(response.operation); - setPuzzleSession(response.session); - const sourceSessionCandidate = pickPuzzleCandidateForLevel( - response.session.draft?.candidates ?? [], - puzzleRun.playedProfileIds, - ); - if (sourceSessionCandidate) { - setPuzzleRun( - advanceLocalPuzzleLevelWithWork( - puzzleRun, - buildPuzzleCandidateWorkSummary( - sourceSessionCandidate, - response.session, - puzzleRun.currentLevelIndex + 1, - ), - ), - ); - return; - } - } - } - throw new Error('当前拼图缺少可用于生成下一关的草稿会话。'); - } - - setIsPuzzleNextLevelGenerating(true); - const response = await executePuzzleAgentAction(puzzleSession.sessionId, { - action: 'generate_puzzle_images', - candidateCount: 2, + const { run } = await advanceLocalPuzzleNextLevel({ + run: puzzleRun, + sourceSessionId: + selectedPuzzleDetail?.sourceSessionId ?? puzzleSession?.sessionId ?? null, }); - setPuzzleOperation(response.operation); - setPuzzleSession(response.session); - - const generatedCandidate = pickPuzzleCandidateForLevel( - response.session.draft?.candidates ?? [], - puzzleRun.playedProfileIds, - ); - if (generatedCandidate) { - setPuzzleRun( - advanceLocalPuzzleLevelWithWork( - puzzleRun, - buildPuzzleCandidateWorkSummary( - generatedCandidate, - response.session, - puzzleRun.currentLevelIndex + 1, - ), - ), - ); - return; - } - - setPuzzleRun(advanceLocalPuzzleLevel(puzzleRun)); + setPuzzleRun(run); } catch (error) { setPuzzleError(resolvePuzzleErrorMessage(error, '准备下一关失败。')); } finally { diff --git a/src/services/puzzle-runtime/index.ts b/src/services/puzzle-runtime/index.ts index 18d6f801..97f3fb58 100644 --- a/src/services/puzzle-runtime/index.ts +++ b/src/services/puzzle-runtime/index.ts @@ -1,4 +1,5 @@ export { + advanceLocalPuzzleNextLevel, advancePuzzleNextLevel, dragPuzzlePieceOrGroup, getPuzzleRun, diff --git a/src/services/puzzle-runtime/puzzleLocalRuntime.ts b/src/services/puzzle-runtime/puzzleLocalRuntime.ts index 527a207f..f699c321 100644 --- a/src/services/puzzle-runtime/puzzleLocalRuntime.ts +++ b/src/services/puzzle-runtime/puzzleLocalRuntime.ts @@ -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); } diff --git a/src/services/puzzle-runtime/puzzleRuntimeClient.ts b/src/services/puzzle-runtime/puzzleRuntimeClient.ts index e1974be5..ae320a30 100644 --- a/src/services/puzzle-runtime/puzzleRuntimeClient.ts +++ b/src/services/puzzle-runtime/puzzleRuntimeClient.ts @@ -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( + `${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, From fc20c395193d5dcfc36bffe692bd7d2665aae611 Mon Sep 17 00:00:00 2001 From: kdletters Date: Sat, 25 Apr 2026 16:44:03 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + ...ND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md | 17 +++-- scripts/dev-rust-stack.sh | 67 ++++++++++++++++--- 3 files changed, 67 insertions(+), 18 deletions(-) diff --git a/.gitignore b/.gitignore index 6e5a2cbc..6634b43c 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ temp*build*/ /public/generated-animations /public/generated-character-drafts /public/generated-characters +/target/ diff --git a/docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md b/docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md index 30d307d1..d9c7fc4a 100644 --- a/docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md +++ b/docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md @@ -33,13 +33,15 @@ npm run dev:rust 1. 检查 `cargo`、`node` 与 `spacetime` CLI。 2. Windows Git Bash 下如 `server-rs/.spacetimedb/local/bin/current/spacetimedb-cli.exe` 不存在,先把本机 `spacetime` 所在安装目录的 `bin/` 与 `spacetime.exe` 同步到 `server-rs/.spacetimedb/local/`。 -3. 启动 `spacetime --root-dir=server-rs/.spacetimedb/local start --edition standalone --listen-addr 127.0.0.1:3101`,确保本地数据库与 SpacetimeDB 内部日志不会落到开发者全局目录。 -4. 等待 `spacetime --root-dir=server-rs/.spacetimedb/local server ping http://127.0.0.1:3101` 可用。 -5. 执行 `spacetime --root-dir=server-rs/.spacetimedb/local publish <本地数据库名> --server http://127.0.0.1:3101 --module-path server-rs/crates/spacetime-module -c=on-conflict --yes`,确保 publish 的签名身份与 standalone 的本地控制库一致,并在当前开发阶段允许新版模块表结构变化且发生 schema 冲突时清除旧模块数据。 -6. 注入 `GENARRATIVE_API_*` 与 `GENARRATIVE_SPACETIME_*` 后启动 `cargo run -p api-server`;直接运行 `api-server` 时,如未显式设置 `GENARRATIVE_SPACETIME_DATABASE`,服务端也会向上查找 `spacetime.local.json` 作为本地默认库名。 -7. 等待 `http://127.0.0.1:/healthz` 返回 HTTP 响应后再启动 Vite,避免前端初始化请求早于 Rust `api-server` 监听完成并在终端刷出 `ECONNREFUSED 127.0.0.1:`。 -8. 注入 `GENARRATIVE_BACKEND_STACK=rust`、`RUST_SERVER_TARGET`、`GENARRATIVE_RUNTIME_SERVER_TARGET` 后启动 Vite。 -9. 任一子进程退出时,脚本回收其余子进程。 +3. 启动前先用同一个 `--root-dir` ping `http://127.0.0.1:3101`;如果目标已就绪则直接复用,避免重复启动同一份 `server-rs/.spacetimedb/local`。 +4. 如果同一个 `root-dir` 已被其他 SpacetimeDB 进程占用但目标端口未就绪,脚本会打印占用进程与命令行并退出,避免继续撞上 `spacetime.pid` 的 Windows 文件锁。 +5. 启动 `spacetime --root-dir=server-rs/.spacetimedb/local start --edition standalone --listen-addr 127.0.0.1:3101`,确保本地数据库与 SpacetimeDB 内部日志不会落到开发者全局目录。 +6. 等待 `spacetime --root-dir=server-rs/.spacetimedb/local server ping http://127.0.0.1:3101` 可用。 +7. 执行 `spacetime --root-dir=server-rs/.spacetimedb/local publish <本地数据库名> --server http://127.0.0.1:3101 --module-path server-rs/crates/spacetime-module -c=on-conflict --yes`,确保 publish 的签名身份与 standalone 的本地控制库一致,并在当前开发阶段允许新版模块表结构变化且发生 schema 冲突时清除旧模块数据。 +8. 注入 `GENARRATIVE_API_*` 与 `GENARRATIVE_SPACETIME_*` 后启动 `cargo run -p api-server`;直接运行 `api-server` 时,如未显式设置 `GENARRATIVE_SPACETIME_DATABASE`,服务端也会向上查找 `spacetime.local.json` 作为本地默认库名。 +9. 等待 `http://127.0.0.1:/healthz` 返回 HTTP 响应后再启动 Vite,避免前端初始化请求早于 Rust `api-server` 监听完成并在终端刷出 `ECONNREFUSED 127.0.0.1:`。 +10. 注入 `GENARRATIVE_BACKEND_STACK=rust`、`RUST_SERVER_TARGET`、`GENARRATIVE_RUNTIME_SERVER_TARGET` 后启动 Vite。 +11. 任一子进程退出时,脚本回收其余子进程。 Vite 代理覆盖范围: @@ -86,6 +88,7 @@ npm run dev:rust:logs -- --follow 2. `spacetime --root-dir=server-rs/.spacetimedb/local list --server http://127.0.0.1:3101` 应能看到 `spacetime.local.json` 中的库名;若没有,执行 `spacetime --root-dir=server-rs/.spacetimedb/local publish <本地数据库名> --server http://127.0.0.1:3101 --module-path server-rs/crates/spacetime-module -c=on-conflict --yes`。 3. 发布库名与 `GENARRATIVE_SPACETIME_DATABASE` 不一致时,`/api/runtime/custom-world-gallery` 会从 Rust `api-server` 返回 `502`,前端首页只能展示空态或错误提示,无法自行修复。 4. 如果 Vite 输出 `/api/auth/refresh`、`/api/auth/login-options` 或 `/api/runtime/custom-world-gallery` 的 `ECONNREFUSED`,先确认当前脚本是否已经打印 `等待 api-server 就绪` 并通过;正常情况下 Vite 只会在 `/healthz` 可访问后启动,不应再因为 Rust 监听未完成而代理失败。 +5. 如果启动阶段提示 `当前 root-dir 已被其他 SpacetimeDB 实例占用`,先看脚本打印的进程命令行:端口就是要复用的实例时,重新执行 `npm run dev:rust -- --spacetime-port <实际端口>`;不是要复用的实例时,先停止该 SpacetimeDB 进程再启动,避免 `spacetime.pid` 文件锁报 `os error 33`。 编译警告治理: diff --git a/scripts/dev-rust-stack.sh b/scripts/dev-rust-stack.sh index e01b93bd..535a5de3 100644 --- a/scripts/dev-rust-stack.sh +++ b/scripts/dev-rust-stack.sh @@ -88,6 +88,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" @@ -326,17 +359,29 @@ echo "[dev:rust] spacetime root: ${SPACETIME_ROOT_DIR}" 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 From 7d6963980fe22369a8dfbeb7c9668255c4ce89f7 Mon Sep 17 00:00:00 2001 From: kdletters Date: Sat, 25 Apr 2026 22:03:41 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E6=8B=BC=E5=9B=BE=E5=80=99=E9=80=89?= =?UTF-8?q?=E5=9B=BE=E6=94=B9=E4=B8=BA=E5=A2=9E=E5=8A=A0=E8=80=8C=E9=9D=9E?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + .idea/Genarrative.iml | 8 --- ...ATOR_AND_GAMEPLAY_SYSTEM_PRD_2026-04-22.md | 2 + .../crates/api-server/src/custom_world_ai.rs | 24 ++++++--- server-rs/crates/api-server/src/puzzle.rs | 9 +++- .../crates/spacetime-module/src/puzzle.rs | 53 ++++++++++++++++++- 6 files changed, 80 insertions(+), 17 deletions(-) delete mode 100644 .idea/Genarrative.iml diff --git a/.gitignore b/.gitignore index f05fabe7..b95c2b1f 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ coverage/ /.codex-cargo-home-*/ /.codex-cache*/ /.tmp*/ +/.idea/ .preview.* tmp_* tmp/ diff --git a/.idea/Genarrative.iml b/.idea/Genarrative.iml deleted file mode 100644 index c956989b..00000000 --- a/.idea/Genarrative.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/docs/prd/AI_NATIVE_PUZZLE_CREATOR_AND_GAMEPLAY_SYSTEM_PRD_2026-04-22.md b/docs/prd/AI_NATIVE_PUZZLE_CREATOR_AND_GAMEPLAY_SYSTEM_PRD_2026-04-22.md index d262256c..54c436a8 100644 --- a/docs/prd/AI_NATIVE_PUZZLE_CREATOR_AND_GAMEPLAY_SYSTEM_PRD_2026-04-22.md +++ b/docs/prd/AI_NATIVE_PUZZLE_CREATOR_AND_GAMEPLAY_SYSTEM_PRD_2026-04-22.md @@ -313,6 +313,8 @@ interface PuzzleAnchorPack { 1. `api-server` 写入 SpacetimeDB 的候选图 JSON 必须使用 `module-puzzle::PuzzleGeneratedImageCandidate` 持久化结构。 2. 持久化字段名保持 Rust 侧 `snake_case`,例如 `candidate_id`、`image_src`、`asset_id`、`actual_prompt`、`source_type`。 3. 面向前端的 HTTP 响应仍由 `shared-contracts` 单独映射为 `camelCase`,不能把响应层字段名直接写入 SpacetimeDB JSON。 +4. 多次生成候选图时必须追加到当前候选池,不能清空已有候选图;已有正式选择保持不变,新追加候选图默认不抢占 `selected` 状态。 +5. 追加生成时 `candidate_id` 必须按当前候选数量续号,避免前端列表 key 与后端选择动作命中旧候选图。 ## 7.6 拼图图片资产要求 diff --git a/server-rs/crates/api-server/src/custom_world_ai.rs b/server-rs/crates/api-server/src/custom_world_ai.rs index b6819e1b..4f3c47c8 100644 --- a/server-rs/crates/api-server/src/custom_world_ai.rs +++ b/server-rs/crates/api-server/src/custom_world_ai.rs @@ -2549,12 +2549,24 @@ mod tests { description: Some("古老礁石上的半沉神殿。".to_string()), }; let manual_prompt = build_custom_world_scene_image_prompt( - &profile_input, - &landmark, - user_prompt, - false, - Some("礁石神殿"), - "雾海群岛", + SceneImagePromptParams { + profile: SceneImagePromptProfile { + name: profile_input.name.as_deref().unwrap_or_default(), + subtitle: profile_input.subtitle.as_deref().unwrap_or_default(), + tone: profile_input.tone.as_deref().unwrap_or_default(), + player_goal: profile_input.player_goal.as_deref().unwrap_or_default(), + summary: profile_input.summary.as_deref().unwrap_or_default(), + setting_text: profile_input.setting_text.as_deref().unwrap_or_default(), + }, + landmark: SceneImagePromptLandmark { + name: landmark.name.as_deref().unwrap_or_default(), + description: landmark.description.as_deref().unwrap_or_default(), + }, + user_prompt, + has_reference_image: false, + fallback_landmark_name: Some("礁石神殿"), + fallback_world_name: "雾海群岛", + }, ); let normalized = normalize_scene_image_request(CustomWorldSceneImageRequest { diff --git a/server-rs/crates/api-server/src/puzzle.rs b/server-rs/crates/api-server/src/puzzle.rs index c2a2bb33..c1ba06b7 100644 --- a/server-rs/crates/api-server/src/puzzle.rs +++ b/server-rs/crates/api-server/src/puzzle.rs @@ -468,6 +468,7 @@ pub async fn execute_puzzle_agent_action( .filter(|value| !value.trim().is_empty()) .unwrap_or_else(|| draft.summary.clone()); let candidate_count = payload.candidate_count.unwrap_or(2).clamp(1, 2); + let candidate_start_index = draft.candidates.len(); let candidates = generate_puzzle_image_candidates( &state, owner_user_id.as_str(), @@ -475,6 +476,7 @@ pub async fn execute_puzzle_agent_action( &draft.level_name, &prompt, candidate_count, + candidate_start_index, ) .await .map_err(SpacetimeClientError::Runtime); @@ -1474,6 +1476,7 @@ async fn compile_puzzle_draft_with_initial_cover( &draft.level_name, &draft.summary, 2, + draft.candidates.len(), ) .await .map_err(SpacetimeClientError::Runtime)?; @@ -1616,6 +1619,7 @@ async fn generate_puzzle_image_candidates( level_name: &str, prompt: &str, candidate_count: u32, + candidate_start_index: usize, ) -> Result, String> { let count = candidate_count.clamp(1, 2); let settings = @@ -1635,7 +1639,7 @@ async fn generate_puzzle_image_candidates( let mut items = Vec::with_capacity(generated.images.len()); for (index, image) in generated.images.into_iter().enumerate() { - let candidate_id = format!("{session_id}-candidate-{}", index + 1); + let candidate_id = format!("{session_id}-candidate-{}", candidate_start_index + index + 1); let asset = persist_puzzle_generated_asset( state, owner_user_id, @@ -1655,7 +1659,7 @@ async fn generate_puzzle_image_candidates( prompt: prompt.to_string(), actual_prompt: Some(prompt.to_string()), source_type: "generated".to_string(), - selected: index == 0, + selected: candidate_start_index == 0 && index == 0, }); } @@ -1729,6 +1733,7 @@ async fn build_local_next_puzzle_run( &draft.level_name, &draft.summary, 2, + draft.candidates.len(), ) .await .map_err(|message| { diff --git a/server-rs/crates/spacetime-module/src/puzzle.rs b/server-rs/crates/spacetime-module/src/puzzle.rs index f6a0fa14..944d8a0a 100644 --- a/server-rs/crates/spacetime-module/src/puzzle.rs +++ b/server-rs/crates/spacetime-module/src/puzzle.rs @@ -684,7 +684,7 @@ fn save_puzzle_generated_images_tx( if candidates.is_empty() { return Err("拼图候选图不能为空".to_string()); } - draft.candidates = candidates; + append_generated_candidates(&mut draft, candidates); draft.generation_status = "ready".to_string(); if let Some(selected) = draft .candidates @@ -1507,6 +1507,23 @@ fn increment_puzzle_profile_play_count( ); } +fn append_generated_candidates( + draft: &mut PuzzleResultDraft, + candidates: Vec, +) { + let has_selected_candidate = draft.candidates.iter().any(|entry| entry.selected); + // 再次生成图片是扩充候选池,不覆盖创作者已经看到或已经选择的候选图。 + // 若已有正式选择,新追加候选图保持未选中,避免同一草稿出现多个 selected。 + draft + .candidates + .extend(candidates.into_iter().map(|mut candidate| { + if has_selected_candidate { + candidate.selected = false; + } + candidate + })); +} + fn list_published_puzzle_profiles(ctx: &TxContext) -> Result, String> { ctx.db .puzzle_work_profile() @@ -1613,6 +1630,40 @@ mod tests { assert!(preview.publish_ready); } + #[test] + fn puzzle_generated_images_are_appended_without_clearing_existing_candidates() { + let anchor_pack = infer_anchor_pack("蒸汽城市雨夜猫咪", Some("蒸汽城市雨夜猫咪")); + let mut draft = compile_result_draft(&anchor_pack, &[]); + draft.candidates = vec![PuzzleGeneratedImageCandidate { + candidate_id: "session-1-candidate-1".to_string(), + image_src: "/generated-puzzle-assets/session-1/old/cover.png".to_string(), + asset_id: "asset-old".to_string(), + prompt: "旧提示词".to_string(), + actual_prompt: Some("旧提示词".to_string()), + source_type: "generated".to_string(), + selected: true, + }]; + + append_generated_candidates( + &mut draft, + vec![PuzzleGeneratedImageCandidate { + candidate_id: "session-1-candidate-2".to_string(), + image_src: "/generated-puzzle-assets/session-1/new/cover.png".to_string(), + asset_id: "asset-new".to_string(), + prompt: "新提示词".to_string(), + actual_prompt: Some("新提示词".to_string()), + source_type: "generated".to_string(), + selected: true, + }], + ); + + assert_eq!(draft.candidates.len(), 2); + assert_eq!(draft.candidates[0].candidate_id, "session-1-candidate-1"); + assert!(draft.candidates[0].selected); + assert_eq!(draft.candidates[1].candidate_id, "session-1-candidate-2"); + assert!(!draft.candidates[1].selected); + } + #[test] fn puzzle_recommendation_score_prefers_same_author_weight() { let left = PuzzleWorkProfile {