AGC 音频生成并入图片类那份后台任务账本

- 原生:`start_local_project_asset_generation` 新增可选入参 `idempotencyKey`,并在音频 kind 上分叉;图片类载荷与分支逐字未改
- 原生:新增音频提交期收口 `prepare_local_project_audio_generation`(kind / 提示词上限 / 素材名 / operation 身份 / 幂等键)
- 原生:新增 `run_local_project_audio_generation_at`,在派发时刻读项目 revision 并复用既有音频无源生成实现,不复制生成逻辑
- 原生:新增 `begin_local_project_audio_generation_task` / `run_local_project_audio_generation_task`,音频任务落同一份项目内账本并写 running → completed / failed,跑完没登记素材按失败收口
- 原生:补两条用例——被拒绝的提交零写入账本、音频任务落在同一账本且 kind 正确
- 前端任务模型:新增音频任务与 `idempotencyKey` 字段,恢复出来的历史任务不带它也不承接重试,入口文案扩到音频栏目
- 前端队列:按 kind 分流派发载荷,音频只发任务身份(任务 id 即 operation id)与幂等键
- 前端面板:音频生成面板改为点「生成」同步提交并立即关闭,删除「生成中…」「后台运行并关闭」与输入锁定
- 前端宿主:音频提交改为同步入队并展开「生成任务」侧栏,只有「后端从未受理」才连原草稿与原请求身份重开面板
- 前端清理:删除随本次改动失效的 `resourceCanvasGenerationSourceId` 与宿主里不再使用的 import
- 测试:面板 / 队列 / 宿主生命周期 / 落点 / appSurface 改按后台账本口径断言,并补「未受理即时失败重开」用例(已用移除重开逻辑的变异验证其非空)
- 文档:PRD §3.10 / §7.9、AGC 底部工具栏入口矩阵、V3 端到端验收 S11a 同步为音频后台化口径
- 文档:新增里程碑与实施计划(含验收证据矩阵),并在 decision-log 记下「音频并入后台任务账本」这条长期约定
This commit is contained in:
2026-09-20 23:32:09 +08:00
parent 429f991bde
commit 99fb6c38c1
21 changed files with 1251 additions and 451 deletions
@@ -29,7 +29,11 @@ use crate::agent::{
write_agent_runtime_json_sidecar_with_max_bytes, PlatformArtAssetGenerationOptions,
};
use crate::commands::prepare_local_project_asset_generation;
use crate::project::{enforce_project_permission_policy, read_existing_manifest_for_project};
use crate::project::{
enforce_project_permission_policy, prepare_local_project_audio_generation,
read_existing_manifest_for_project, run_local_project_audio_generation_at,
LocalProjectAudioGenerationRequest, LocalProjectResourceEditKind,
};
use shared_contracts::game_creation_app::GameCreationAppAssetKind;
pub(crate) const ASSET_GENERATION_TASK_SCHEMA_VERSION: &str = "agc-asset-generation-task.v1";
@@ -63,6 +67,8 @@ const ASSET_GENERATION_TASK_INTERRUPTED_INCOMPLETE_ERROR: &str =
"应用退出时生成任务仍在进行,目标素材未登记";
const ASSET_GENERATION_TASK_INTERRUPTED_UNKNOWN_ERROR: &str =
"应用退出时生成任务仍在进行,未能在清单里确认结果";
/// 音频任务收口:通道跑完但没有登记出素材(`derive` 在有源 / 无源两条路上都必须登记 assets)。
const ASSET_GENERATION_AUDIO_MISSING_ASSET_ERROR: &str = "生成完成但未登记素材";
/// 一条生成任务的权威记录。字段名与前端一一对应(camelCase)。
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -376,10 +382,121 @@ async fn run_local_project_asset_generation_task(
remove_live_task_id(&task_id);
}
/// 走音频无源生成链路的 kind:音效与背景音乐。
///
/// 这份判据是「同一命令两种通道」的唯一分叉点:它在白名单里只放这两个成员,其余 kind
/// (含图片类与 `unknown`)一律继续走图片通道的既有收口,不在这一层做兜底猜测。
fn is_audio_asset_generation_kind(kind: GameCreationAppAssetKind) -> bool {
matches!(
kind,
GameCreationAppAssetKind::SoundEffect | GameCreationAppAssetKind::BackgroundMusic
)
}
/// 音频(音效 / 背景音乐)提交:校验入参 → 落**同一份**排队记录 → 返回记录与派发所需的请求。
///
/// 与图片类分支的差异只有三处,且都不改变账本形状:
/// 1. 权限沿用既有无源生成链路的 `asset.register`(音频入口在后台化之前就是这条判据);
/// 2. 账本去掉精确落点(音频不指定 `outputPath`);
/// 3. 生成走 `run_local_project_audio_generation_task`(由调用方派发,本函数不 spawn——校验与
/// 落账必须能在没有异步运行时的测试里单独断言)。
fn begin_local_project_audio_generation_task(
project_path: &str,
project_id: &str,
task_id: &str,
kind: &str,
prompt: &str,
asset_name: &str,
idempotency_key: &str,
) -> Result<
(
AssetGenerationTaskRecord,
LocalProjectAudioGenerationRequest,
),
String,
> {
let request =
prepare_local_project_audio_generation(task_id, kind, prompt, asset_name, idempotency_key)?;
if project_path.trim().is_empty() {
return Err("项目路径不能为空".to_string());
}
let root = Path::new(project_path.trim());
enforce_project_permission_policy(root, "asset.register")?;
let asset_kind = match request.edit_kind {
LocalProjectResourceEditKind::BackgroundMusic => GameCreationAppAssetKind::BackgroundMusic,
_ => GameCreationAppAssetKind::SoundEffect,
};
let record = begin_local_project_asset_generation_task(
root,
project_id,
task_id,
asset_kind,
&request.asset_name,
None,
)?;
Ok((record, request))
}
/// 音频后台执行:状态与阶段文案的每一次流转都由这里写账本。
///
/// `run_local_project_audio_generation_at` 返回 `Ok(None)` 表示这次生成没有登记出素材:按失败
/// 收口,不把一条没有 `assetId` 的记录标成「已完成」——那样前端既定位不到素材,也没有原因可看。
async fn run_local_project_audio_generation_task(
project_path: String,
task_id: String,
request: LocalProjectAudioGenerationRequest,
) {
let root = PathBuf::from(project_path.trim());
if update_task(&root, &task_id, |task| {
task.status = ASSET_GENERATION_TASK_STATUS_RUNNING.to_string();
task.phase_detail = ASSET_GENERATION_TASK_PHASE_RUNNING.to_string();
task.started_at_millis = Some(now_millis());
})
.is_err()
{
remove_live_task_id(&task_id);
return;
}
let outcome = run_local_project_audio_generation_at(&project_path, &request).await;
match outcome {
Ok(Some(asset_id)) => {
let _ = update_task(&root, &task_id, |task| {
task.status = ASSET_GENERATION_TASK_STATUS_COMPLETED.to_string();
task.phase_detail = ASSET_GENERATION_TASK_PHASE_COMPLETED.to_string();
task.asset_id = Some(asset_id);
task.finished_at_millis = Some(now_millis());
task.error = None;
});
}
Ok(None) => {
let _ = update_task(&root, &task_id, |task| {
task.status = ASSET_GENERATION_TASK_STATUS_FAILED.to_string();
task.phase_detail =
format!("生成失败:{ASSET_GENERATION_AUDIO_MISSING_ASSET_ERROR}");
task.error = Some(ASSET_GENERATION_AUDIO_MISSING_ASSET_ERROR.to_string());
task.finished_at_millis = Some(now_millis());
});
}
Err(error) => {
let _ = update_task(&root, &task_id, |task| {
task.status = ASSET_GENERATION_TASK_STATUS_FAILED.to_string();
task.phase_detail = format!("生成失败:{error}");
task.error = Some(error.clone());
task.finished_at_millis = Some(now_millis());
});
}
}
remove_live_task_id(&task_id);
}
/// 提交即返回:校验入参 → 落排队记录 → 派发后台任务 → 返回记录。
///
/// 入参收口完全复用 `prepare_local_project_asset_generation`(与同步命令同一份白名单与边界),
/// 生成本身仍是 `generate_platform_art_asset_with_options_at`,本命令不复制任何生成逻辑。
///
/// 音频 kind(`sound-effect` / `background-music`)走同一条命令的音频分支:账本、阶段文案、
/// 中断收口与本地排队全部共用,**只**把「怎么生成」换成既有音频无源生成链路(见
/// `start_local_project_audio_generation_task`)。图片类载荷口径逐字不变。
#[tauri::command]
pub(crate) async fn start_local_project_asset_generation(
project_path: String,
@@ -397,8 +514,40 @@ pub(crate) async fn start_local_project_asset_generation(
// 前端 IPC 字段 `targetCategory`:完成登记时要落盘的正式栏目分类。同样不进任务账本:
// 它与引用一样属于「同一次提交的本地落点」,重试由调用方继续用同一个栏目提交。
target_category: Option<String>,
// 前端 IPC 字段 `idempotencyKey`:**音频**生成才带——音频请求身份是一对 operation / 幂等键,
// 重试必须复用同一对,否则就变成第二次付费生成。图片类通道的载荷逐字不变,这个字段对
// 图片 kind 不参与任何校验。
idempotency_key: Option<String>,
) -> Result<AssetGenerationTaskRecord, String> {
let task_id = asset_generation_task_id(&task_id)?;
if is_audio_asset_generation_kind(GameCreationAppAssetKind::parse_with_context(
&kind,
"canvas.asset_kind",
)) {
let idempotency_key = idempotency_key.unwrap_or_default();
if idempotency_key.trim().is_empty() {
return Err("音频生成缺少 idempotencyKey".to_string());
}
let (record, request) = begin_local_project_audio_generation_task(
&project_path,
&project_id,
&task_id,
&kind,
&prompt,
asset_name.as_deref().unwrap_or_default(),
&idempotency_key,
)?;
// 先登记 live 再派发:`list` 只把「非终态且不 live」的记录判为上次运行的残留。
if let Ok(mut ids) = live_task_ids().lock() {
ids.insert(task_id.clone());
}
tauri::async_runtime::spawn(run_local_project_audio_generation_task(
project_path.trim().to_string(),
task_id,
request,
));
return Ok(record);
}
let request = prepare_local_project_asset_generation(
&project_path,
&kind,
@@ -761,4 +910,129 @@ mod asset_generation_task_tests {
);
std::fs::remove_dir_all(&root).ok();
}
/// 音频提交的身份与边界:缺幂等键 / 非法 operation / 非法幂等键 / 超限提示词 / 非音频 kind
/// 一律在提交期拒绝,且**不**在账本里留下记录——「点击瞬间就失败」必须是零写入。
#[test]
fn audio_submission_rejects_invalid_identity_and_prompt_without_touching_the_ledger() {
let root = initialized_project_root("audio-invalid");
let project_path = root.to_string_lossy().into_owned();
let operation_id = "0b6f2f9a-0f0f-4b3d-8d0a-5e0f5cef9b21";
let idempotency_key = "9a1b2c3d-4e5f-4a1b-8c2d-3e4f5a6b7c8d";
let error = begin_local_project_audio_generation_task(
&project_path,
"project-1",
operation_id,
"background-music",
"一段平静的钢琴曲",
"新背景音乐",
"",
)
.expect_err("missing idempotency key");
assert!(error.contains("idempotencyKey"), "{error}");
let error = begin_local_project_audio_generation_task(
&project_path,
"project-1",
"not-a-uuid",
"background-music",
"一段平静的钢琴曲",
"新背景音乐",
idempotency_key,
)
.expect_err("operation id must be a uuid");
assert!(error.contains("operationId"), "{error}");
let error = begin_local_project_audio_generation_task(
&project_path,
"project-1",
operation_id,
"background-music",
"一段平静的钢琴曲",
"新背景音乐",
"不看幂等键",
)
.expect_err("idempotency key must be a uuid");
assert!(error.contains("idempotencyKey"), "{error}");
let error = begin_local_project_audio_generation_task(
&project_path,
"project-1",
operation_id,
"background-music",
&"曲".repeat(141),
"新背景音乐",
idempotency_key,
)
.expect_err("background music prompt limit");
assert!(error.contains("140"), "{error}");
let error = begin_local_project_audio_generation_task(
&project_path,
"project-1",
operation_id,
"audio",
"一段平静的钢琴曲",
"新背景音乐",
idempotency_key,
)
.expect_err("音频 kind 不是可生成的音频类型");
assert!(error.contains("音频生成不支持该素材类型"), "{error}");
assert!(
list_local_project_asset_generation_tasks(&root)
.expect("list")
.is_empty(),
"被拒绝的提交不得在账本里留下记录"
);
std::fs::remove_dir_all(&root).ok();
}
/// 音频任务的账本记录与图片类共用同一份:kind 是音频 canonical kind,阶段文案由后端拥有,
/// 精确落点为空(音频不指定 outputPath),提示词在提交期就按同一口径归一化。
#[test]
fn audio_submission_lands_in_the_shared_ledger_with_its_audio_kind() {
let root = initialized_project_root("audio-ledger");
let project_path = root.to_string_lossy().into_owned();
let (record, request) = begin_local_project_audio_generation_task(
&project_path,
"project-1",
"0b6f2f9a-0f0f-4b3d-8d0a-5e0f5cef9b21",
"background-music",
" 一段平静的钢琴曲 ",
"新背景音乐",
"9a1b2c3d-4e5f-4a1b-8c2d-3e4f5a6b7c8d",
)
.expect("background music task");
assert_eq!(record.kind, GameCreationAppAssetKind::BackgroundMusic);
assert_eq!(record.status, ASSET_GENERATION_TASK_STATUS_QUEUED);
assert_eq!(record.phase_detail, ASSET_GENERATION_TASK_PHASE_QUEUED);
assert!(record.output_path.is_none());
assert_eq!(record.asset_name, "新背景音乐");
assert_eq!(request.prompt, "一段平静的钢琴曲");
assert_eq!(
request.edit_kind,
LocalProjectResourceEditKind::BackgroundMusic
);
let listed = list_local_project_asset_generation_tasks(&root).expect("list");
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].kind, GameCreationAppAssetKind::BackgroundMusic);
assert_eq!(listed[0].task_id, record.task_id);
// 音效走同一条账本,只是落到另一个 canonical kind。
let (sound_effect, request) = begin_local_project_audio_generation_task(
&project_path,
"project-1",
"1c7a3b8e-2f31-4c6d-9e7a-6b8c0d1e2f34",
"sound-effect",
"木门缓慢推开的吱呀声",
"新音效",
"2d8b4c9f-3a42-4d7e-8f1b-7c9d1e2f3a45",
)
.expect("sound effect task");
assert_eq!(sound_effect.kind, GameCreationAppAssetKind::SoundEffect);
assert_eq!(request.edit_kind, LocalProjectResourceEditKind::SoundEffect);
std::fs::remove_dir_all(&root).ok();
}
}
@@ -5399,6 +5399,90 @@ pub(crate) async fn resume_local_project_resource_edit_at(
.await
}
/// 音频(音效 / 背景音乐)无源生成的入参收口。
///
/// 与同步派生通道(`derive_local_project_resource`)共用同一份校验:提示词上限按 edit kind
/// 取(背景音乐 140、音效 1900),素材名同口径,`idempotencyKey` 必须是合法 UUID。区别只在
/// **时机**:后台任务账本的提交必须「校验即返回」,所以这里只收口、不发起生成——生成由派发后
/// 的后台任务跑(见 `run_local_project_audio_generation_at`)。
#[derive(Clone, Debug)]
pub(crate) struct LocalProjectAudioGenerationRequest {
pub(crate) operation_id: String,
pub(crate) edit_kind: LocalProjectResourceEditKind,
pub(crate) prompt: String,
pub(crate) asset_name: String,
pub(crate) idempotency_key: String,
}
/// 音频 kind 的提交期收口:operation 身份、kind、提示词、素材名与幂等键。
///
/// kind 只接受 `sound-effect` / `background-music`:其余成员(含图片类)在这里就被拒绝,
/// 不会落一条注定失败的账本记录,也不改图片类入口的载荷口径。
pub(crate) fn prepare_local_project_audio_generation(
operation_id: &str,
kind: &str,
prompt: &str,
asset_name: &str,
idempotency_key: &str,
) -> Result<LocalProjectAudioGenerationRequest, String> {
validate_resource_edit_uuid(operation_id, "operationId")?;
let edit_kind = match GameCreationAppAssetKind::parse_with_context(kind, "canvas.asset_kind") {
GameCreationAppAssetKind::SoundEffect => LocalProjectResourceEditKind::SoundEffect,
GameCreationAppAssetKind::BackgroundMusic => LocalProjectResourceEditKind::BackgroundMusic,
_ => return Err(format!("音频生成不支持该素材类型:{}", kind.trim())),
};
validate_resource_edit_uuid(idempotency_key, "idempotencyKey")?;
let prompt = normalize_resource_edit_prompt(&edit_kind, prompt)?;
let asset_name = normalize_resource_edit_name(asset_name)?;
Ok(LocalProjectAudioGenerationRequest {
operation_id: operation_id.trim().to_string(),
edit_kind,
prompt,
asset_name,
idempotency_key: idempotency_key.trim().to_string(),
})
}
/// 后台跑一次音频无源生成,返回产物素材 id。
///
/// 生成本身仍走 `derive_local_project_resource_at` 这一条通道(幂等账本、平台请求、下载与
/// manifest 登记全部复用),这里只做两件账本侧的事:把「提交时刻」无法确定的项目 revision
/// 在派发时刻读成当前值(提交之后用户仍可能编辑项目),以及把产物素材 id 交回任务账本。
/// 拿不到当前 revision 或 CAS 冲突时按失败返回,不静默重试——静默重试会把这次生成写到用户
/// 没预期的基线上。
pub(crate) async fn run_local_project_audio_generation_at(
project_path: &str,
request: &LocalProjectAudioGenerationRequest,
) -> Result<Option<String>, String> {
let project_path = project_path.trim();
let root = Path::new(project_path);
let manifest = read_existing_manifest_for_project(root)?;
let expected_project_revision =
read_game_creator_agent_runtime_project_revision(root)?.revision;
let result = derive_local_project_resource_at(DeriveLocalProjectResourceInput {
project_path: project_path.to_string(),
expected_project_id: manifest.project_id,
expected_project_revision,
operation_id: request.operation_id.clone(),
idempotency_key: request.idempotency_key.clone(),
edit_kind: request.edit_kind,
generation_mode: LocalProjectResourceGenerationMode::Create,
source_resource_id: format!("create:{}", request.operation_id),
source_asset_id: None,
source_path: None,
source_media_type: Some("audio/mpeg".to_string()),
source_subtype: None,
producer_task_id: None,
source_version_id: None,
prompt: request.prompt.clone(),
asset_name: request.asset_name.clone(),
background_mode: None,
screen_color: None,
})
.await?;
Ok(result.asset.map(|asset| asset.id))
}
pub(crate) async fn derive_local_project_resource_at(
input: DeriveLocalProjectResourceInput,
) -> Result<DeriveLocalProjectResourceResult, String> {
@@ -87,7 +87,13 @@ export type ResourceCanvasGenerationPanelViewProps = {
prompt: string;
assetName: string;
}) => void;
onSubmit: (input: ResourceCanvasGenerationSubmitInput) => Promise<void>;
/**
* 提交这次输入:**同步入队**,不等 IPC、不等排队、不等生成结束。
*
* 生成任务由宿主交给项目内账本(音频与图片类同一份),进度只出现在画布上的「生成任务」
* 侧栏;面板提交后立即关闭,不持有在途状态。
*/
onSubmit: (input: ResourceCanvasGenerationSubmitInput) => void;
/**
* 收起浮层。
*
@@ -107,12 +113,6 @@ const RESOURCE_GENERATION_ALL_KIND_ITEMS =
label: option.label,
}));
function resourceGenerationErrorMessage(error: unknown) {
if (typeof error === 'string' && error.trim()) return error;
if (error instanceof Error && error.message) return error.message;
return '生成素材失败';
}
/**
* 资源画布「生成入口」的浮层面板。
*
@@ -120,9 +120,13 @@ function resourceGenerationErrorMessage(error: unknown) {
* 不在任何现有面板下面追加内容;提交链路与结果定位由宿主 `index.tsx` 负责,
* 面板只持有草稿、类型选择与失败重试状态。
*
* 提交期间**不锁关闭**:× / 遮罩 / Esc / 「后台运行并关闭」四条路径都通。关闭只是把这一份
* view 卸下来,宿主那条请求继续跑(它是宿主的 `await onSubmit(...)`,不挂在面板生命周期上),
* 所以关闭**不等于**取消;失败时面板仍保留草稿与同一份请求身份可重试。
* **点「生成」即同步关闭面板**:不等 IPC、不等排队、不等生成结束,用户立刻回到画布;面板里
* 因此不存在「排队中。」「正在生成。」「提交中…」「后台运行并关闭」这些阶段文案与按钮——
* 阶段文案的唯一去处是画布上的「生成任务」侧栏。关闭**不等于**取消:任务照常在后台跑完并把
* 结果写回项目。
*
* 只有「点击瞬间就失败」(校验 / 权限拒绝 / 提交 IPC 立即报错,即后端从未受理)时,宿主才会
* 把面板连原草稿与原请求身份带回来,用户可以直接改后重试。
*/
export function ResourceCanvasGenerationPanelView({
kinds = RESOURCE_CANVAS_GENERATION_OPTIONS.map((option) => option.kind),
@@ -154,11 +158,11 @@ export function ResourceCanvasGenerationPanelView({
const [assetName, setAssetName] = useState(
initialDraft?.assetName ?? option.assetName,
);
const [attempted, setAttempted] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// 占位带来的失败原因优先展示;面板自己这次的失败(`error`)覆盖它。
const shownError = error ?? initialError ?? null;
/*
失败原因只有**占位**这一个来源:提交后面板已经关闭,面板实例不持有在途状态,也就不会
自己造一份 `error`。重开同一张占位时由宿主把账本里的原因灌回来。
*/
const shownError = initialError ?? null;
/**
* 已绑定请求身份的那句提示词(只有带 `request` 重开的失败面板才有)。
*
@@ -201,7 +205,6 @@ export function ResourceCanvasGenerationPanelView({
const requestRef = useRef<ResourceEditRequestIdentity | null>(
boundRequest ?? null,
);
const inputLocked = attempted || submitting;
/** 收起浮层:把当前草稿交给宿主保存,用户再点开占位卡时接着编辑。 */
const closeWithDraft = () => {
draftReleasedRef.current = true;
@@ -220,43 +223,34 @@ export function ResourceCanvasGenerationPanelView({
assetName: assetName.trim() || option.assetName,
};
async function submit(event: FormEvent<HTMLFormElement>) {
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const normalizedPrompt = prompt.trim();
const normalizedAssetName = assetName.trim();
if (
!normalizedPrompt ||
!normalizedAssetName ||
submitting ||
// 按钮禁用只是表现:改动原请求提示词的提交在这里也必须被挡住,不能悄悄变成新付费生成。
boundRequestPromptChanged
) {
return;
}
setAttempted(true);
setSubmitting(true);
setError(null);
requestRef.current = resolveResourceEditRequestIdentity(
requestRef.current,
normalizedPrompt,
);
try {
await onSubmit({
kind,
operationId: requestRef.current.operationId,
idempotencyKey: requestRef.current.idempotencyKey,
prompt: normalizedPrompt,
assetName: normalizedAssetName,
});
// 只有**成功**交出这次输入才不再写回草稿;失败时草稿要留给用户切走再切回来的重试。
draftReleasedRef.current = true;
} catch (submitError) {
setError(resourceGenerationErrorMessage(submitError));
} finally {
// 成功路径也要收回在飞标记:宿主随后会卸载面板,但组件本身不该在 `onSubmit` 正常
// resolve 后永久停在「生成中…」;失败时收回标记才能让用户用同一份输入重试。
setSubmitting(false);
}
// 这次输入被任务接走:卸载时不再往草稿槽里写一份内存副本(失败重开由宿主的提交上下文负责)。
draftReleasedRef.current = true;
// 点击即关闭:不等 IPC、不等排队、不等生成结束。入参已经带上这次生成的请求身份,
// 「从未被后端受理」的即时失败由宿主连原草稿与原身份把面板带回来。
onSubmit({
kind,
operationId: requestRef.current.operationId,
idempotencyKey: requestRef.current.idempotencyKey,
prompt: normalizedPrompt,
assetName: normalizedAssetName,
});
onClose();
}
const panelBody = (
@@ -281,7 +275,6 @@ export function ResourceCanvasGenerationPanelView({
columns="three"
gap="sm"
size="compact"
disabled={inputLocked}
onChange={(nextKind) => {
setKind(nextKind);
setAssetName(resourceCanvasGenerationOption(nextKind).assetName);
@@ -294,7 +287,6 @@ export function ResourceCanvasGenerationPanelView({
<PlatformTextField
aria-label="素材名称"
maxLength={120}
disabled={inputLocked}
value={assetName}
onChange={(event) => setAssetName(event.currentTarget.value)}
/>
@@ -306,7 +298,6 @@ export function ResourceCanvasGenerationPanelView({
aria-label="生成提示词"
rows={6}
autoFocus
disabled={inputLocked}
maxLength={resourceEditPromptMaxLength(option.editKind)}
placeholder={option.promptPlaceholder}
value={prompt}
@@ -317,7 +308,6 @@ export function ResourceCanvasGenerationPanelView({
subject={`素材生成提示词(${option.label})`}
editKind={option.editKind}
prompt={prompt}
disabled={inputLocked}
applyPrompt={setPrompt}
/>
{boundRequestPromptChanged ? (
@@ -339,12 +329,12 @@ export function ResourceCanvasGenerationPanelView({
tone="secondary"
onClick={closeWithDraft}
>
{submitting ? '后台运行并关闭' : '取消'}
取消
</PlatformActionButton>
{shownError ? (
<PlatformActionButton
type="submit"
disabled={submitting || boundRequestPromptChanged}
disabled={boundRequestPromptChanged}
>
<Sparkles size={15} aria-hidden="true" />
使用原请求重试
@@ -353,15 +343,11 @@ export function ResourceCanvasGenerationPanelView({
<PlatformActionButton
type="submit"
disabled={
submitting ||
!prompt.trim() ||
!assetName.trim() ||
inputLocked ||
boundRequestPromptChanged
!prompt.trim() || !assetName.trim() || boundRequestPromptChanged
}
>
<Sparkles size={15} aria-hidden="true" />
{submitting ? '生成中…' : option.generationLabel}
{option.generationLabel}
</PlatformActionButton>
)}
</div>
@@ -4,6 +4,7 @@ import {
mergeLocalProjectAssetGenerationRecord,
nextResourceCanvasAssetGenerationDispatch,
type ResourceCanvasAssetGenerationTask,
resourceCanvasAssetGenerationTaskIsAudio,
} from './resourceCanvasAssetGenerationTaskModel';
export const RESOURCE_CANVAS_ASSET_GENERATION_POLL_INTERVAL_MILLIS = 2_000;
@@ -142,6 +143,12 @@ export function createResourceCanvasAssetGenerationQueue(
const projectPath = deps.projectPath();
// 命令名写成字面量:`scripts/check-config.mjs` 的 invoke 门禁按字符串字面量登记调用方,
// 抽成常量会让这两条 IPC 被判成「没有前端调用方」。
/*
音频与图片类走**同一条命令**,载荷按任务形状分流:音频没有比例 / 尺寸 / 参考图 / 精确
落点,只有「任务 id = operation id」+ 幂等键这对请求身份;图片类载荷字段与取值口径逐字
不变(`kind / prompt / aspectRatio / imageSize / assetName / outputPath`)。
*/
const audioTask = resourceCanvasAssetGenerationTaskIsAudio(task);
const start = async () =>
(await deps.invoke('start_local_project_asset_generation', {
projectPath,
@@ -149,13 +156,19 @@ export function createResourceCanvasAssetGenerationQueue(
taskId: task.taskId,
kind: task.assetKind,
prompt: task.prompt,
aspectRatio: task.aspectRatio,
imageSize: task.imageSize,
assetName: task.assetName,
referenceAssetIds: task.referenceAssetIds,
outputPath: task.outputPath,
// 入口栏目:原生支持时按它登记归类;不支持时后端忽略,落点仍按正式归类走。
...(task.targetCategory ? { targetCategory: task.targetCategory } : {}),
...(audioTask
? { idempotencyKey: task.idempotencyKey }
: {
aspectRatio: task.aspectRatio,
imageSize: task.imageSize,
referenceAssetIds: task.referenceAssetIds,
outputPath: task.outputPath,
// 入口栏目:原生支持时按它登记归类;不支持时后端忽略,落点仍按正式归类走。
...(task.targetCategory
? { targetCategory: task.targetCategory }
: {}),
}),
})) as LocalProjectAssetGenerationTaskRecord;
let started: LocalProjectAssetGenerationTaskRecord;
try {
@@ -52,6 +52,14 @@ export type ResourceCanvasAssetGenerationTask = {
assetKind: GameCreationAppAssetKind;
assetName: string;
prompt: string;
/**
* 音频任务的**请求幂等键**;图片类任务为 `null`。
*
* 音频生成在原生侧按「operation id + 幂等键」记账,任务 id 就是那次生成的 operation id:
* 重试必须带回同一个幂等键,否则同一次生成会变成第二次付费请求。图片类通道的请求指纹不含
* 这项,所以保持 `null`——不为统一形状给图片类补一个它根本不用的身份。
*/
idempotencyKey: string | null;
aspectRatio: string;
imageSize: string;
/**
@@ -130,10 +138,17 @@ export function resourceCanvasAssetGenerationTaskTone(
*/
export const RESOURCE_CANVAS_ASSET_GENERATION_LOCAL_QUEUE_PHASE = '排队中。';
const RESOURCE_CANVAS_ASSET_GENERATION_CATEGORIES = [
/**
* 入口文案派生时遍历的栏目:图片类三个栏目 + 音频栏目。
*
* 音频任务的账本 `kind` 是 `sound-effect` / `background-music`,恢复历史任务时也必须能派生出
* 「生成音效 / 生成背景音乐」这层文案,否则重开项目后音频任务只剩素材名可看。
*/
const RESOURCE_CANVAS_GENERATION_CATEGORIES = [
'ui-interaction',
'character',
'scene',
'audio',
] as const;
/**
@@ -145,12 +160,15 @@ const RESOURCE_CANVAS_ASSET_GENERATION_CATEGORIES = [
export function resourceCanvasAssetGenerationKindLabel(
kind: GameCreationAppAssetKind,
): string | null {
for (const category of RESOURCE_CANVAS_ASSET_GENERATION_CATEGORIES) {
for (const category of RESOURCE_CANVAS_GENERATION_CATEGORIES) {
for (const tool of resolveResourceCanvasBottomTools(category)) {
for (const action of resourceCanvasBottomToolActions(tool)) {
if (action.route === 'asset' && action.assetKind === kind) {
return action.label;
}
if (action.route === 'audio' && action.audioKind === kind) {
return action.label;
}
}
}
}
@@ -200,6 +218,7 @@ export function createResourceCanvasAssetGenerationTask(input: {
assetKind: input.action.assetKind,
assetName: input.assetName,
prompt: input.prompt,
idempotencyKey: null,
aspectRatio: input.aspectRatio,
imageSize: input.imageSize,
// 参考图去重(保持用户选择顺序):同一张素材在一份草稿里被选两次仍只算一次参考,
@@ -229,6 +248,76 @@ export function createResourceCanvasAssetGenerationTask(input: {
const RESOURCE_CANVAS_ASSET_GENERATION_TASK_LIMIT = 50;
/** 音频任务的 kind:只有这两类走音频生成通道。 */
export type ResourceCanvasAudioGenerationTaskKind = Extract<
GameCreationAppAssetKind,
'sound-effect' | 'background-music'
>;
/**
* 新提交的**音频**任务(音效 / 背景音乐)。
*
* 与图片类共用同一份本地排队、同一个后端账本与同一个「生成任务」侧栏;差异只在请求形状:
* 音频没有比例 / 尺寸 / 参考图 / 精确落点,身份是「任务 id = 那次生成的 operation id」+
* 幂等键(由宿主在提交时铸造并原样保存,重试复用同一对,不产生第二次付费请求)。
*
* 音频也没有入口栏目这条入参:归类由原生音频通道自己决定,提交时不带 `targetCategory`,
* 所以这里不留一个没人读的本地字段。
*/
export function createResourceCanvasAudioGenerationTask(input: {
taskId: string;
idempotencyKey: string;
draftId?: string | null;
actionId: string;
actionLabel: string;
kind: ResourceCanvasAudioGenerationTaskKind;
prompt: string;
assetName: string;
projectId: string;
nowMillis: number;
}): ResourceCanvasAssetGenerationTask {
return {
taskId: input.taskId,
draftId: input.draftId ?? null,
actionId: input.actionId,
actionLabel: input.actionLabel,
assetKind: input.kind,
assetName: input.assetName,
prompt: input.prompt,
idempotencyKey: input.idempotencyKey,
aspectRatio: '',
imageSize: '',
referenceAssetIds: [],
referenceLabels: {},
targetCategory: null,
outputPath: null,
projectId: input.projectId,
dispatched: false,
status: 'queued',
phaseDetail: RESOURCE_CANVAS_ASSET_GENERATION_LOCAL_QUEUE_PHASE,
createdAtMillis: input.nowMillis,
startedAtMillis: null,
finishedAtMillis: null,
assetId: null,
error: null,
restored: false,
};
}
/**
* 这条任务是不是音频生成。
*
* 两个调用方都靠它分流:生成任务队列决定派发哪一套载荷(音频只带幂等键、图片类带比例 /
* 尺寸 / 参考 / 落点),宿主决定「未受理失败」把哪块面板连原请求身份带回来。
*/
export function resourceCanvasAssetGenerationTaskIsAudio(
task: Pick<ResourceCanvasAssetGenerationTask, 'assetKind'>,
): boolean {
return (
task.assetKind === 'sound-effect' || task.assetKind === 'background-music'
);
}
/** 账本记录 → 任务列表里的一条(重开项目后恢复显示)。 */
export function restoreResourceCanvasAssetGenerationTask(
record: LocalProjectAssetGenerationTaskRecord,
@@ -246,6 +335,8 @@ export function restoreResourceCanvasAssetGenerationTask(
assetKind,
assetName: record.assetName,
prompt: '',
// 账本不存幂等键:恢复出来的历史任务只用于展示与定位,不承接重试。
idempotencyKey: null,
aspectRatio: '',
imageSize: '',
referenceAssetIds: [],
@@ -36,7 +36,7 @@ export type ResourceCanvasGeneratedAssetKind = Extract<
/** 权威规范图的落点;Rust `AGENT_RUNTIME_ART_SPEC_PATH`。 */
export const RESOURCE_CANVAS_ICON_SPEC_LOCAL_PATH = 'assets/art-spec.png';
/** 工具栏入口的路由:图片类生成 / 既有音频生成 / 上传。 */
/** 工具栏入口的路由:图片类生成 / 音频生成 / 上传。 */
export type ResourceCanvasBottomToolRoute = 'asset' | 'audio' | 'upload';
export type ResourceCanvasBottomToolActionId =
@@ -86,7 +86,12 @@ export type ResourceCanvasAssetToolAction =
writesIconSpecReference: boolean;
};
/** 音频入口:复用既有 `derive_local_project_resource` 的无源生成链路。 */
/**
* 音频入口:与图片类同一条 `start_local_project_asset_generation`(提交即返回、后台生成)。
*
* 原生命令内部仍复用既有音频无源生成链路(`editKind` = `sound-effect` / `background-music`),
* 不新增平台路由与请求体口径;任务与图片类共用同一份项目内任务账本与「生成任务」侧栏。
*/
export type ResourceCanvasAudioToolAction =
ResourceCanvasBottomToolActionBase & {
route: 'audio';
@@ -4,11 +4,12 @@ import type { LocalProjectResourceEditKind } from '../../view/project-developmen
/**
* 资源画布「生成入口」当前能真正落地的三类新建素材。
*
* 这里的白名单与 Rust `resolve_resource_edit_source` 的 create 分支一一对应:
* `apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs` 只放行
* 音频两类(音效 / 背景音乐)由 `start_local_project_asset_generation` 的音频分支受理,落同
* 一份后台任务账本;它们内部仍走既有音频无源生成链路,而那条链路的 create 分支
* (`apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs`)只放行
* video / sound-effect / background-music,其余类型(含图片)会直接返回
* “当前资源类型不支持无源生成”。因此入口只呈现这三类——宁可少一个入口,
* 也不给一个提交必然失败、或者拿图片参数糊弄用户的按钮。
* “当前资源类型不支持无源生成”。因此视频入口保留在既有浮层里,音频入口只呈现这两类——
* 宁可少一个入口,也不给一个提交必然失败、或者拿图片参数糊弄用户的按钮。
*/
export type ResourceCanvasGenerationKind = Extract<
GameCreationAppAssetKind,
@@ -80,16 +81,6 @@ export function resourceCanvasGenerationOption(
return VIDEO_GENERATION_OPTION;
}
/**
* create 模式的稳定源标识。
*
* 无源生成没有真实源资源,Rust 只把这个字符串当作 canonical resource id 记账,
* 不再回读源文件;用 operationId 拼出来保证同一 operation 的流水可对账。
*/
export function resourceCanvasGenerationSourceId(operationId: string) {
return `create:${operationId.trim()}`;
}
/**
* 入口按钮的渲染门禁。
*
@@ -12,7 +12,8 @@ import {
} from '../../view/project-development/resourceProjectionModel';
import { isResourceCanvasExportable } from './resourceCanvasAssetTransferModel';
/** 快速编辑与改造都走 `derive_local_project_resource`,只接受这三种栅格图片格式。 */
/** 快速编辑与改造都走 `derive_local_project_resource`(无源音频生成之外的另一条派生链路),
* 只接受这三种栅格图片格式。 */
const RESOURCE_RASTER_MEDIA_TYPES = new Set([
'image/png',
'image/jpeg',
@@ -142,6 +142,7 @@ import {
} from '../../features/resource-canvas/resourceCanvasAssetGenerationReferenceModel';
import {
createResourceCanvasAssetGenerationTask,
createResourceCanvasAudioGenerationTask,
type LocalProjectAssetGenerationTaskRecord,
type ResourceCanvasAssetGenerationTask,
resourceCanvasAssetGenerationTaskIsTerminal,
@@ -174,11 +175,7 @@ import {
resolveResourceCanvasFloatingPanelOpen,
resolveResourceCanvasFocusEscapeActive,
} from '../../features/resource-canvas/resourceCanvasFocusModel';
import {
type ResourceCanvasGenerationKind,
resourceCanvasGenerationOption,
resourceCanvasGenerationSourceId,
} from '../../features/resource-canvas/resourceCanvasGenerationModel';
import type { ResourceCanvasGenerationKind } from '../../features/resource-canvas/resourceCanvasGenerationModel';
import {
ResourceCanvasGenerationPanelView,
type ResourceCanvasGenerationSubmitInput,
@@ -2074,14 +2071,27 @@ export default function ProjectDevelopmentView({
>(),
);
/**
* 音频 / 背景音乐那条链路(`derive_local_project_resource`)的提交身份,按草稿 ID 记。
* 音频 / 背景音乐那条链路的提交身份,按草稿 ID 记。
*
* 它没有图片队列那本任务账本,提交身份就是面板铸造的 `operationId` + 幂等键:收起来再点开
* 占位时必须复用同一对,否则重试会变成一次**新的**付费生成。
* 提交身份就是面板铸造的 `operationId` + 幂等键(任务 id 即该 operation id):失败后收起再
* 点开占位重试时必须复用同一对,否则重试会变成一次**新的**付费生成。
*/
const resourceGenerationAudioRequestRef = useRef(
new Map<string, ResourceEditRequestIdentity>(),
);
/**
* 音频提交上下文:这次提交属于哪张占位。
*
* 只有一件事要用它——**后端从未受理**的即时失败要把面板连原草稿、原请求身份带回来;受理
* 之后才失败的收口只看账本,不需要这条本地上下文。`dispatchedImmediately` 沿用图片类口径:
* 排在队列后面才派发的任务即使失败也不弹面板打断用户。
*/
const resourceGenerationAudioSubmissionRef = useRef<{
taskId: string;
draftId: string;
kind: ResourceCanvasGenerationKind;
dispatchedImmediately: boolean;
} | null>(null);
/** 用户主动收起浮层时留下的可再编辑草稿(按草稿 ID 记,提交成功后清掉)。 */
const resourceGenerationDraftRef = useRef(
new Map<
@@ -7777,143 +7787,101 @@ export default function ProjectDevelopmentView({
]);
/**
* 生成入口:从资源画布无源新建视频 / 音效 / 背景音乐。
* 提交一条音频生成任务(背景音乐 / 音效)。
*
* 产出物是一张全新的资源卡(`generationMode: 'create'`),源素材、画布布局与
* 已有 manifest 条目都不参与派生;成功后用 `pendingResourceFocusRef` 定位新卡。
* 与图片类**同一条后台通道**:入队即返回,生成由队列派发给项目内任务账本跑,状态与阶段文案
* 只出现在「生成任务」侧栏。提交面板点「生成」就关闭,不等受理、不等排队、不等生成。
*
* 请求身份(`operationId` = 任务 id、幂等键)由面板铸造、宿主按占位记下来:失败后点原请求
* 重试必须复用同一对,否则同一次生成会变成第二次付费请求。
*/
const submitResourceCanvasGeneration = useCallback(
async (
(
input: ResourceCanvasGenerationSubmitInput,
draftId: string | null = null,
) => {
const invoke = window.__TAURI__?.core?.invoke;
if (!invoke) {
throw new Error('生成资源需要在客户端内执行');
const queue = resourceAssetGenerationQueueRef.current;
const context = resourceAssetGenerationContextRef.current;
if (!queue || !draftId) {
setResourceWorkbenchNotice(
'生成任务队列尚未就绪,请重新打开项目后重试',
);
return;
}
if (input.kind === 'video') {
// 音频入口只放行音效 / 背景音乐;视频能力留在既有「生成素材」浮层,不在这里兜底成一次
// 必然被原生拒绝的提交。
setResourceWorkbenchNotice('音频入口不支持视频生成');
return;
}
const placeholder =
resourceGenerationPlaceholders.placeholderByDraftId(draftId);
if (!placeholder) {
setResourceWorkbenchNotice('这张占位已经不在画布上,请重新发起生成');
return;
}
const placeholder = draftId
? resourceGenerationPlaceholders.placeholderByDraftId(draftId)
: null;
/*
同一张占位已经在后台跑:**不允许**用新的 operationId 再发一次——那是一次重复付费生成。
同一 operationId 的重试(面板失败后点原请求重试)走原生账本幂等,不在禁止之列。
*/
if (
placeholder?.status === 'submitted' &&
placeholder.status === 'submitted' &&
placeholder.taskId !== input.operationId
) {
throw new Error('这次生成已在后台继续,请等它结束或失败后再重试');
}
if (placeholder) {
// 提交身份与被绑定的 operationId 一起记在占位上:关闭面板再点开也用同一 operation 重试。
resourceGenerationAudioRequestRef.current.set(placeholder.draftId, {
operationId: input.operationId,
idempotencyKey: input.idempotencyKey,
// 提示词是身份的一部分:原生指纹含 prompt,脱开它就变成另一次请求。
prompt: input.prompt,
});
resourceGenerationPlaceholders.bindTask(
placeholder.draftId,
input.operationId,
setResourceWorkbenchNotice(
'这次生成已在后台继续,请等它结束或失败后再重试',
);
return;
}
const option = resourceCanvasGenerationOption(input.kind);
const actionProject = { projectPath, projectId: manifest.projectId };
const flowId = crypto.randomUUID();
try {
const status = await invoke<{ revision: number }>(
'get_local_game_project_revision',
{ projectPath },
// 「这次点击本来就该立刻派发」:队列里没有在途任务时才是。排在队列后面才派发的任务即使
// 提交失败,也不该把面板弹回来打断用户。
const dispatchedImmediately =
!resourceAssetGenerationTasksRef.current.some(
(task) =>
task.dispatched &&
!resourceCanvasAssetGenerationTaskIsTerminal(task),
);
if (!Number.isSafeInteger(status.revision) || status.revision < 0) {
throw new Error('项目 revision 无效');
}
const result = await withPlatformSessionRefresh(() =>
invoke<DeriveLocalProjectResourceResult>(
'derive_local_project_resource',
{
input: {
projectPath,
expectedProjectId: actionProject.projectId,
expectedProjectRevision: status.revision,
operationId: input.operationId,
idempotencyKey: input.idempotencyKey,
editKind: option.editKind,
generationMode: 'create',
sourceResourceId: resourceCanvasGenerationSourceId(
input.operationId,
),
sourceAssetId: null,
sourcePath: null,
sourceMediaType: option.sourceMediaType,
sourceSubtype: null,
producerTaskId: null,
sourceVersionId: null,
prompt: input.prompt,
assetName: input.assetName,
},
},
),
);
if (
!result.asset ||
result.manifest.projectId !== actionProject.projectId
) {
throw new Error('生成资源结果与当前项目不一致');
}
onManifestChange?.(projectPath, result.manifest, {
projectId: result.manifest.projectId,
revision: result.committedProjectRevision,
source: 'asset-command',
commitId: result.operationId,
});
activeFocusFlowIdRef.current = flowId;
pendingResourceFocusRef.current = {
flowId,
saveAttemptId: result.operationId,
sessionId: result.operationId,
draftId: result.operationId,
commitId: result.operationId,
projectPath,
projectId: result.manifest.projectId,
focusGeneration: focusGenerationRef.current,
resourceId: `asset:${result.asset.id}`,
completed: false,
};
setResourceWorkbenchNotice('生成资源已保存,正在同步资源与布局…');
if (placeholder) {
/*
成功落点:与图片类生成同一条口径——按**正式归类后的 section**提交占位的**最新位置**,
等新卡进了布局再落(见落点 effect)。这里只记意图,不冻结坐标。
*/
resourceGenerationLandingRef.current.set(placeholder.draftId, {
projectId: placeholder.projectId,
draftId: placeholder.draftId,
resourceId: `asset:${result.asset.id}`,
});
resourceGenerationAudioRequestRef.current.delete(placeholder.draftId);
}
setResourceGenerationDraft(null);
} catch (error) {
/*
失败:占位留在画布上(输入与操作身份都还在,面板自己展示原因),状态收口为失败。
重试沿用同一 operationId,命中原生幂等账本——不会重复发起一次付费生成。
*/
if (placeholder) {
resourceGenerationPlaceholders.failTask(
input.operationId,
error instanceof Error ? error.message : String(error),
);
}
throw error;
}
const task = createResourceCanvasAudioGenerationTask({
// 任务 id 就是这次生成的 operation id:原生按它记账,重试命中同一 operation。
taskId: input.operationId,
idempotencyKey: input.idempotencyKey,
draftId,
actionId: placeholder.actionId,
actionLabel: placeholder.actionLabel,
kind: input.kind,
prompt: input.prompt,
assetName: input.assetName,
projectId: context.projectId,
nowMillis: Date.now(),
});
// 提交身份与该次草稿一起留下:关闭浮层、失败后重开占位都靠它们回到同一次生成。
resourceGenerationAudioRequestRef.current.set(draftId, {
operationId: input.operationId,
idempotencyKey: input.idempotencyKey,
prompt: input.prompt,
});
resourceGenerationAudioSubmissionRef.current = {
taskId: task.taskId,
draftId,
kind: input.kind,
dispatchedImmediately,
};
resourceGenerationDraftRef.current.set(draftId, {
kind: input.kind,
prompt: input.prompt,
assetName: input.assetName,
});
// 占位从「待提交」进入「生成中」:任务已经交给后台,关闭浮层不影响它。
resourceGenerationPlaceholders.bindTask(draftId, task.taskId);
setResourceAssetGenerationTasksPanelOpen(true);
setResourceWorkbenchNotice(
`已提交「${input.assetName}」,生成在后台继续,进度见「生成任务」`,
);
// 终局由 `onSettled` 收口(成功落卡 / 失败收口 / 即时失败重开面板),这里只吞掉拒绝,
// 避免出现未处理的 Promise 拒绝。面板由它自己的 `onClose` 同步收起。
void queue.submit(task).catch(() => undefined);
},
[
manifest.projectId,
onManifestChange,
projectPath,
resourceGenerationPlaceholders,
],
[resourceGenerationPlaceholders],
);
/**
@@ -7991,6 +7959,32 @@ export default function ProjectDevelopmentView({
// 账本已经把结果写在它自己的项目里,这里不再动当前项目的状态。
return;
}
const audioSubmission = resourceGenerationAudioSubmissionRef.current;
if (audioSubmission?.taskId === settlement.taskId) {
resourceGenerationAudioSubmissionRef.current = null;
if (
settlement.status === 'failed' &&
settlement.record === null &&
audioSubmission.dispatchedImmediately
) {
/*
后端**从未受理**(校验不过 / 权限拒绝 / 提交 IPC 立即报错):占位留在画布上,面板
连原草稿与原请求身份一起带回来。这次输入还没被任务接走,改完再提交仍然是同一次
生成——同一 operation 与幂等键,不会变成第二次付费请求。
*/
resourceGenerationPlaceholdersRef.current.failTask(
settlement.taskId,
settlement.error ?? '生成失败',
);
setResourceWorkbenchNotice('');
setResourceGenerationDraft({
initialKind: audioSubmission.kind,
kinds: [audioSubmission.kind],
draftId: audioSubmission.draftId,
});
return;
}
}
const submission = resourceAssetGenerationPanelSubmissionRef.current;
if (submission?.taskId === settlement.taskId) {
resourceAssetGenerationPanelSubmissionRef.current = null;
@@ -8049,6 +8043,10 @@ export default function ProjectDevelopmentView({
draftId: landingPlaceholder.draftId,
resourceId: `asset:${assetId}`,
});
// 音频那条提交身份只在「失败后原地重试」时有意义:这次已经成功落地,身份随任务作废。
resourceGenerationAudioRequestRef.current.delete(
landingPlaceholder.draftId,
);
}
let fresh: Awaited<
ReturnType<typeof rereadAuthoritativeProjectManifestSnapshot>
@@ -8251,6 +8249,7 @@ export default function ProjectDevelopmentView({
setResourceAssetGenerationPanel(null);
// 收起时的草稿与音频提交身份同样是本项目内的记忆,换项目一并作废。
resourceGenerationAudioRequestRef.current.clear();
resourceGenerationAudioSubmissionRef.current = null;
resourceGenerationDraftRef.current.clear();
resourceAssetGenerationDraftRef.current.clear();
void (async () => {
@@ -396,24 +396,6 @@ function generateCall(
return call.args;
}
function deriveInput(
calls: readonly BottomToolbarInvokeCall[],
editKind: string,
) {
const call = calls.find(
(entry) =>
entry.command === 'derive_local_project_resource' &&
deriveInputEditKind(entry) === editKind,
);
const input = call?.args?.input;
if (!input || typeof input !== 'object') {
throw new Error(
`missing derive_local_project_resource call for ${editKind}`,
);
}
return input;
}
function uploadCall(
calls: readonly BottomToolbarInvokeCall[],
fileName: string,
@@ -13254,7 +13236,7 @@ export function registerProjectAgentStatusTests() {
).not.toBeNull();
}, 20_000);
it('routes the audio column entries to the existing audio generation chain', async () => {
it('routes the audio column entries to the shared background generation ledger', async () => {
const manifest = createGameCreationAppManifest(
'workbench-bottom-toolbar-audio',
'底部工具栏音频项目',
@@ -13301,14 +13283,35 @@ export function registerProjectAgentStatusTests() {
fireEvent.click(
within(musicPanel).getByRole('button', { name: '生成背景音乐' }),
);
await waitFor(() =>
expect(deriveInput(calls, 'background-music')).toMatchObject({
editKind: 'background-music',
generationMode: 'create',
sourceMediaType: 'audio/mpeg',
/*
音频与图片类走**同一条命令**:任务 id 就是这次生成的 operation id,另带一枚幂等键。
图片类那套比例 / 尺寸 / 参考 / 精确落点参数一个都不发——音频通道根本不读它们。
*/
await waitFor(() => {
const musicStart = generateCall(calls, 'background-music');
expect(musicStart).toMatchObject({
kind: 'background-music',
prompt: '轻快的八音盒',
assetName: '新背景音乐',
}),
idempotencyKey: expect.any(String),
});
expect(Object.keys(musicStart).sort()).toEqual([
'assetName',
'idempotencyKey',
'kind',
'projectId',
'projectPath',
'prompt',
'taskId',
]);
expect(String(musicStart.taskId)).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
);
});
// 提交即关闭:面板不留在屏幕上等结果,进度交给「生成任务」侧栏。
await waitFor(() =>
expect(screen.queryByRole('dialog', { name: '生成背景音乐' })).toBeNull(),
);
fireEvent.click(await screen.findByRole('button', { name: '生成音效' }));
@@ -13320,12 +13323,11 @@ export function registerProjectAgentStatusTests() {
within(soundPanel).getByRole('button', { name: '生成音效' }),
);
await waitFor(() =>
expect(deriveInput(calls, 'sound-effect')).toMatchObject({
editKind: 'sound-effect',
generationMode: 'create',
sourceMediaType: 'audio/mpeg',
expect(generateCall(calls, 'sound-effect')).toMatchObject({
kind: 'sound-effect',
prompt: '木门缓慢推开的吱呀声',
assetName: '新音效',
idempotencyKey: expect.any(String),
}),
);
}, 20_000);
@@ -37,11 +37,6 @@ const uiPrototypeAction: ResourceCanvasAssetToolAction = {
writesIconSpecReference: false,
};
/** 永不 resolve 的提交:音频面板仍然等生成结束,用它模拟在途状态。 */
function pendingSubmit() {
return new Promise<void>(() => undefined);
}
describe('图片类生成面板:点击即关闭,面板里不出现阶段文案', () => {
test('点击生成同步调用提交并关闭面板,面板 DOM 里从不出现阶段 / 排队文案', async () => {
const onClose = vi.fn();
@@ -141,10 +136,12 @@ describe('图片类生成面板:点击即关闭,面板里不出现阶段文
});
});
describe('音频生成面板在提交期间可关闭', () => {
test('提交在途时点 × 能关闭面板,且不改动 pending-edit 账本语义', async () => {
/* 音频面板没有在途状态:点「生成」即把输入交给宿主(同步入参 + 立即关闭),阶段文案只由
画布上的「生成任务」侧栏拥有。 */
describe('音频生成面板:点击即关闭,面板里不出现阶段文案', () => {
test('点「生成音效」同步调用提交并关闭面板,从不出现阶段 / 后台文案', async () => {
const onClose = vi.fn();
const onSubmit = vi.fn(pendingSubmit);
const onSubmit = vi.fn();
const user = userEvent.setup();
render(
<ResourceCanvasGenerationPanelView
@@ -155,36 +152,48 @@ describe('音频生成面板在提交期间可关闭', () => {
/>,
);
await user.type(screen.getByLabelText('生成提示词'), '木门推开的声音');
await user.click(screen.getByRole('button', { name: '生成音效' }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
const closeButton = screen.getByRole('button', {
name: '关闭生成音效',
}) as HTMLButtonElement;
expect(closeButton.disabled).toBe(false);
await user.click(closeButton);
expect(onClose).toHaveBeenCalledTimes(1);
const panel = screen.getByRole('dialog', { name: '生成音效' });
expect(panel.textContent).not.toMatch(/排队中。|正在生成。|提交中…/);
await user.click(within(panel).getByRole('button', { name: '生成音效' }));
// 提交与关闭在同一个事件循环里发生:不等受理、不等排队、不等生成。
expect(onSubmit).toHaveBeenCalledTimes(1);
fireEvent.keyDown(window, { key: 'Escape' });
expect(onClose).toHaveBeenCalledTimes(2);
expect(onSubmit.mock.calls[0]?.[0]).toMatchObject({
kind: 'sound-effect',
prompt: '木门推开的声音',
assetName: '新音效',
});
expect(onClose).toHaveBeenCalledTimes(1);
// 进度只出现在「生成任务」侧栏:面板 DOM 里既没有阶段文案,也没有在途按钮。
expect(panel.textContent).not.toMatch(/排队中。|正在生成。|提交中…/);
expect(screen.queryByRole('button', { name: '后台运行并关闭' })).toBeNull();
});
test('提交在途时提供「后台运行并关闭」', async () => {
test('× / Esc 关面板只收起草稿:不提交,也不取消任何任务', async () => {
const onClose = vi.fn();
const onSubmit = vi.fn();
const user = userEvent.setup();
render(
<ResourceCanvasGenerationPanelView
kinds={['sound-effect']}
initialKind="sound-effect"
onSubmit={vi.fn(pendingSubmit)}
onSubmit={onSubmit}
onClose={onClose}
/>,
);
await user.type(screen.getByLabelText('生成提示词'), '木门推开的声音');
await user.click(screen.getByRole('button', { name: '生成音效' }));
await user.click(screen.getByRole('button', { name: '后台运行并关闭' }));
await user.click(screen.getByRole('button', { name: '关闭生成音效' }));
expect(onClose).toHaveBeenCalledTimes(1);
// 关闭把当前草稿交回宿主:用户再点开占位卡能接着编辑,而不是回到空表单。
expect(onClose.mock.calls[0]?.[0]).toMatchObject({
kind: 'sound-effect',
prompt: '木门推开的声音',
assetName: '新音效',
});
fireEvent.keyDown(window, { key: 'Escape' });
expect(onClose).toHaveBeenCalledTimes(2);
expect(onSubmit).not.toHaveBeenCalled();
});
});
@@ -10,6 +10,7 @@ import {
import {
applyLocalProjectAssetGenerationRecords,
createResourceCanvasAssetGenerationTask,
createResourceCanvasAudioGenerationTask,
type LocalProjectAssetGenerationTaskRecord,
nextResourceCanvasAssetGenerationDispatch,
RESOURCE_CANVAS_ASSET_GENERATION_LOCAL_QUEUE_PHASE,
@@ -398,6 +399,56 @@ describe('本地排队驱动器', () => {
});
});
test('音频任务只发「任务 id + 幂等键」,不发图片类那套比例 / 尺寸 / 参考 / 落点', async () => {
const taskId = '0b6f2f9a-0f0f-4b3d-8d0a-5e0f5cef9b21';
const harness = createHarness((pollCount, api) => {
if (pollCount === 1) {
api.advance(taskId, 'completed');
}
});
const queue = createResourceCanvasAssetGenerationQueue(harness.deps);
await queue.submit(
createResourceCanvasAudioGenerationTask({
taskId,
idempotencyKey: '9a1b2c3d-4e5f-4a1b-8c2d-3e4f5a6b7c8d',
draftId: 'draft-bgm',
actionId: 'generate-background-music',
actionLabel: '生成背景音乐',
kind: 'background-music',
prompt: '一段平静的钢琴曲',
assetName: '新背景音乐',
projectId: 'project-1',
nowMillis: 10,
}),
);
const startCall = harness.invoke.mock.calls.find(
([command]) => command === 'start_local_project_asset_generation',
);
// 逐字钉住载荷:多一个图片类字段就是「拿图片参数糊弄音频通道」。
expect(startCall?.[1]).toEqual({
projectPath: '/tmp/project',
projectId: 'project-1',
taskId: '0b6f2f9a-0f0f-4b3d-8d0a-5e0f5cef9b21',
kind: 'background-music',
prompt: '一段平静的钢琴曲',
assetName: '新背景音乐',
idempotencyKey: '9a1b2c3d-4e5f-4a1b-8c2d-3e4f5a6b7c8d',
});
// 音频落的是同一份账本:任务 id 就是 operation id,收口记录一样能回到本地任务上。
expect(harness.settlements[0]).toMatchObject({
taskId,
status: 'completed',
});
expect(harness.tasks()[0]).toMatchObject({
assetKind: 'background-music',
idempotencyKey: '9a1b2c3d-4e5f-4a1b-8c2d-3e4f5a6b7c8d',
status: 'completed',
assetId: `asset-${taskId}`,
});
});
test('账本里找不到这条任务时不会无限轮询,收口为失败并放行后面的排队任务', async () => {
const harness = createHarness((pollCount, api) => {
if (pollCount === 1) {
@@ -12,9 +12,9 @@ import { afterEach, describe, expect, test, vi } from 'vitest';
import {
isResourceCanvasGenerationAvailable,
RESOURCE_CANVAS_GENERATION_OPTIONS,
resourceCanvasGenerationSourceId,
} from '../src/features/resource-canvas/resourceCanvasGenerationModel';
import { ResourceCanvasGenerationPanelView } from '../src/features/resource-canvas/ResourceCanvasGenerationPanelView';
import { typeGenerationPrompt } from './resourceGenerationPromptTestUtils';
type TauriInvoke = (
command: string,
@@ -78,10 +78,6 @@ describe('resourceCanvasGenerationModel', () => {
}),
).toBe(true);
});
test('无源生成的稳定源标识挂在 operationId 上', () => {
expect(resourceCanvasGenerationSourceId(' op-1 ')).toBe('create:op-1');
});
});
describe('ResourceCanvasGenerationPanelView', () => {
@@ -102,16 +98,14 @@ describe('ResourceCanvasGenerationPanelView', () => {
expect(panel.textContent).not.toContain('图片');
});
test('失败后锁定原请求并用同一 operationId 与幂等键重试', async () => {
test('点「生成」即同步入队并关闭面板:不等 IPC、不等排队、不等生成', async () => {
const user = userEvent.setup();
const onSubmit = vi
.fn<(input: unknown) => Promise<void>>()
.mockRejectedValueOnce(new Error('result-unknown: 测试网络中断'))
.mockResolvedValueOnce(undefined);
const onSubmit = vi.fn();
const onClose = vi.fn();
render(
<ResourceCanvasGenerationPanelView
onSubmit={onSubmit}
onClose={() => undefined}
onClose={onClose}
/>,
);
@@ -121,20 +115,74 @@ describe('ResourceCanvasGenerationPanelView', () => {
await user.type(prompt, '一段片头动画,镜头缓慢推进');
await user.click(screen.getByRole('button', { name: '生成视频' }));
expect((await screen.findByRole('alert')).textContent).toContain(
'result-unknown: 测试网络中断',
);
expect((prompt as HTMLTextAreaElement).disabled).toBe(true);
expect((assetName as HTMLInputElement).disabled).toBe(true);
await user.click(screen.getByRole('button', { name: '使用原请求重试' }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2));
expect(onSubmit.mock.calls[0]?.[0]).toEqual(onSubmit.mock.calls[1]?.[0]);
// 提交与关闭在同一个事件循环里发生:提交回调**同步**返回,面板不持有在途状态。
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0]?.[0]).toMatchObject({
kind: 'video',
prompt: '一段片头动画,镜头缓慢推进',
assetName: '新视频',
});
expect(onSubmit.mock.calls[0]?.[0]).toMatchObject({
operationId: expect.any(String),
idempotencyKey: expect.any(String),
});
// 面板里不出现任何阶段文案与「后台运行并关闭」这类在途按钮。
expect(document.body.textContent).not.toMatch(
/排队中。|正在生成。|提交中…|后台运行并关闭/,
);
});
test('失败重开:带原失败原因与原请求身份,改回原提示词才能重试', async () => {
const user = userEvent.setup();
const onSubmit = vi.fn();
const onClose = vi.fn();
const boundRequest = {
operationId: '8f2d5b1c-3a4e-4d6f-9b0c-1d2e3f4a5b6c',
idempotencyKey: '5c1e7a90-2b3d-4e5f-8a9b-0c1d2e3f4a5b',
prompt: '一段片头动画,镜头缓慢推进',
};
render(
<ResourceCanvasGenerationPanelView
initialKind="video"
initialDraft={{
kind: 'video',
prompt: boundRequest.prompt,
assetName: '新视频',
}}
initialError="生成失败:result-unknown: 测试网络中断"
request={boundRequest}
onSubmit={onSubmit}
onClose={onClose}
/>,
);
expect(screen.getByRole('alert').textContent).toContain(
'result-unknown: 测试网络中断',
);
const prompt = screen.getByLabelText('生成提示词') as HTMLTextAreaElement;
expect(prompt.value).toBe(boundRequest.prompt);
// 改了提示词:这次提交不再是原请求的重试(会另铸身份并另行计费),必须被挡住。
await typeGenerationPrompt(document.body, '改成另一段片头动画');
const retry = screen.getByRole('button', {
name: '使用原请求重试',
}) as HTMLButtonElement;
expect(retry.disabled).toBe(true);
expect(document.body.textContent).toContain('这次生成是「原请求重试」');
await user.click(retry);
expect(onSubmit).not.toHaveBeenCalled();
// 改回原样:重试复用同一对 operationId / 幂等键,不产生第二次付费生成。
await typeGenerationPrompt(document.body, boundRequest.prompt);
await user.click(screen.getByRole('button', { name: '使用原请求重试' }));
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0]?.[0]).toMatchObject({
operationId: boundRequest.operationId,
idempotencyKey: boundRequest.idempotencyKey,
prompt: boundRequest.prompt,
});
expect(onClose).toHaveBeenCalledTimes(1);
});
test('切换类型后默认名称与提交文案跟随类型', async () => {
@@ -254,33 +302,52 @@ describe('生成素材弹窗的提示词润色', () => {
expect(screen.queryByRole('button', { name: '恢复原文' })).toBeNull();
});
test('提交失败后提示词与润色入口一起锁定,重试仍是同一份请求身份', async () => {
test('失败重开后输入不锁定:润色照常可用,改动提示词就挡住原请求重试', async () => {
const user = userEvent.setup();
installTauriInvoke(async () => undefined);
const onSubmit = vi
.fn<(input: unknown) => Promise<void>>()
.mockRejectedValueOnce(new Error('result-unknown: 测试网络中断'))
.mockResolvedValueOnce(undefined);
installTauriInvoke(async (command) => {
if (command !== 'polish_local_project_prompt') return undefined;
return ' 润色后的片头动画 ';
});
const onSubmit = vi.fn();
const boundRequest = {
operationId: '2b7c1d3e-4f5a-4b6c-8d9e-0f1a2b3c4d5e',
idempotencyKey: '6c8d2e4f-5a6b-4c7d-9e0f-1a2b3c4d5e6f',
prompt: '一段片头动画',
};
render(
<ResourceCanvasGenerationPanelView
initialKind="video"
initialDraft={{
kind: 'video',
prompt: boundRequest.prompt,
assetName: '新视频',
}}
initialError="生成失败:result-unknown: 测试网络中断"
request={boundRequest}
onSubmit={onSubmit}
onClose={() => undefined}
/>,
);
/*
提交后面板已经关了,重开的是**占位**:这里既没有在途状态也没有「锁」,用户照常能改草稿。
挡住重复付费的判据不是「锁住输入」,而是「提示词一变就不再是原请求」。
*/
const prompt = screen.getByLabelText('生成提示词') as HTMLTextAreaElement;
await user.type(prompt, '一段片头动画');
await user.click(screen.getByRole('button', { name: '生成视频' }));
expect(await screen.findByRole('alert')).not.toBeNull();
expect(prompt.disabled).toBe(false);
const polishButton = screen.getByRole('button', {
name: 'AI 润色',
}) as HTMLButtonElement;
expect(polishButton.disabled).toBe(false);
await user.click(polishButton);
await waitFor(() => expect(prompt.value).toBe('润色后的片头动画'));
// 锁定输入 = 提交的提示词不可能漂移,所以复用同一 operationId 是安全的。
expect(prompt.disabled).toBe(true);
const polishButton = screen.getByRole('button', { name: 'AI 润色' });
expect((polishButton as HTMLButtonElement).disabled).toBe(true);
await user.click(screen.getByRole('button', { name: '使用原请求重试' }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(2));
expect(onSubmit.mock.calls[1]?.[0]).toEqual(onSubmit.mock.calls[0]?.[0]);
const retry = screen.getByRole('button', {
name: '使用原请求重试',
}) as HTMLButtonElement;
expect(retry.disabled).toBe(true);
await user.click(retry);
expect(onSubmit).not.toHaveBeenCalled();
expect(document.body.textContent).toContain('这次生成是「原请求重试」');
});
});
@@ -87,24 +87,33 @@ function manifestFor(
*/
function installHostTauri(options: {
assets: AssetFixture[];
deriveResults: Array<
| { ok: true; assetId: string; hold?: boolean }
| { ok: false; message: string }
>;
/**
* 图片类入口(`start_local_project_asset_generation`)的账本收口方式。
* 后台生成账本(`start_local_project_asset_generation`)的收口方式。
*
* 不传时这条命令不被这些用例触发(音频入口走 `derive_local_project_resource`);
* `'failed'` 让队列在第一次轮询就看到一条失败记录,用来观察失败态重试。
* 不传时任务停在**运行中**,由用例调 `completeAssetGeneration` 收口为完成(用来观察占位的
* `submitted` 中间态与结果落点);`'failed'` 让队列在第一次轮询就看到一条失败记录,用来观察
* 失败态与重试。
*/
assetGenerationRecord?: 'failed';
/**
* 提交那一刻就被拒绝(后端从未受理):`start_local_project_asset_generation` 抛这个原因。
*
* 用例可以中途改 `assetGenerationStartError.current`(改成 `undefined` 表示这次真受理了),
* 所以「未受理」与「已受理」两条路能在同一条用例里对照。
*/
assetGenerationStartError?: string;
}) {
const layoutWrites: LayoutWrite[] = [];
const deriveCalls: Array<Record<string, unknown>> = [];
const assetGenerationStarts: Array<Record<string, unknown>> = [];
const audioTaskRecords = new Map<string, Record<string, unknown>>();
/** 后台任务登记进清单的素材:完成收口时补进来,`get_local_game_manifest` 才读得到。 */
const registeredAssets: AssetFixture[] = [];
const unexpectedCommands: string[] = [];
let revision = 0;
let releaseHeldDerive: (() => void) | null = null;
const assetGenerationStartError = {
current: options.assetGenerationStartError,
};
const positions: ProjectResourceCanvasPosition[] = [];
const invoke = vi.fn(
@@ -113,12 +122,15 @@ function installHostTauri(options: {
return { revision: 1 };
}
if (command === 'read_local_project_resource_graph') {
// 关系图按**当前清单**(`resources` 入参)派生:后台生成落进清单的素材也要在图上。
const resources =
(args?.resources as Array<{ resourceId: string }> | undefined) ?? [];
return {
nodes: [],
taskFlowIds: [],
producerAssignments: [],
dependencyDepths: options.assets.map((asset) => ({
resourceId: `asset:${asset.id}`,
dependencyDepths: resources.map((resource) => ({
resourceId: resource.resourceId,
dependencyDepth: 0,
})),
unresolvedReferenceResourceIds: [],
@@ -127,6 +139,12 @@ function installHostTauri(options: {
producerMappingTruncated: false,
};
}
if (command === 'get_local_game_manifest') {
return manifestFor(PROJECT_ID, [
...options.assets,
...registeredAssets,
]);
}
if (command === 'read_local_project_resource_canvas_layout') {
return {
schemaVersion: 'game-creator-resource-layout.v1',
@@ -162,33 +180,23 @@ function installHostTauri(options: {
};
}
if (command === 'derive_local_project_resource') {
const input = args?.input as Record<string, unknown>;
deriveCalls.push(input);
const planned = options.deriveResults.shift();
if (!planned || !planned.ok) {
throw new Error(planned?.message ?? '测试:没有预置生成结果');
}
// `hold`:把这次生成停在后台运行中,用来观察占位的 `submitted` 中间态。
if (planned.hold) {
await new Promise<void>((resolve) => {
releaseHeldDerive = resolve;
});
}
const asset = bgmAsset(planned.assetId);
return {
asset,
manifest: manifestFor(PROJECT_ID, [...options.assets, asset]),
committedProjectRevision: 2,
operationId: input.operationId,
};
/*
音频与图片类都走后台任务账本:这条同步派生通道不该再被生成入口触发。真被调到就大声
失败,而不是静默返回一个像模像样的结果。
*/
deriveCalls.push((args?.input as Record<string, unknown>) ?? {});
throw new Error('生成入口不应再走同步派生通道');
}
if (command === 'list_pending_local_project_resource_edits') {
return [];
}
if (command === 'start_local_project_asset_generation') {
const startArgs = args ?? {};
assetGenerationStarts.push(startArgs);
return {
assetGenerationStarts.push(structuredClone(startArgs));
if (assetGenerationStartError.current) {
throw new Error(assetGenerationStartError.current);
}
const task = {
taskId: String(startArgs.taskId ?? ''),
projectId: PROJECT_ID,
kind: String(startArgs.kind ?? ''),
@@ -196,26 +204,29 @@ function installHostTauri(options: {
referenceAssetIds: Array.isArray(startArgs.referenceAssetIds)
? startArgs.referenceAssetIds
: [],
status: 'queued',
status: 'running',
phaseDetail: '已受理',
createdAtMillis: 1,
startedAtMillis: 1,
finishedAtMillis: null,
assetId: null,
error: null,
};
audioTaskRecords.set(task.taskId, task);
return task;
}
if (command === 'list_local_project_asset_generations') {
return assetGenerationStarts.map((started) => ({
...started,
status: options.assetGenerationRecord ?? 'queued',
phaseDetail:
options.assetGenerationRecord === 'failed' ? '生成失败' : '已受理',
finishedAtMillis:
options.assetGenerationRecord === 'failed' ? 2 : null,
error:
options.assetGenerationRecord === 'failed'
? '测试:生成失败'
: null,
const records = [...audioTaskRecords.values()];
if (options.assetGenerationRecord !== 'failed') {
return records;
}
// 「后端已受理、之后才失败」这一路:面板不再被带回来,原因留在占位那一侧。
return records.map((task) => ({
...task,
status: 'failed',
phaseDetail: '生成失败:测试拒绝',
finishedAtMillis: 2,
error: '测试:生成失败',
}));
}
if (command === 'read_local_project_image_preview') {
@@ -245,8 +256,27 @@ function installHostTauri(options: {
layoutWrites,
deriveCalls,
assetGenerationStarts,
assetGenerationStartError,
unexpectedCommands,
releaseHeldDerive: () => releaseHeldDerive?.(),
/**
* 后台任务收口为完成:账本里那条记录变成 `completed` + `assetId`,素材同时进清单。
*
* 真实链路里这两件事都由 Rust 后台任务写(先登记 manifest 再写终态),这里只复刻结果。
* 队列下一次轮询(默认 2 秒一次)就会读到终态并把结果落到占位上。
*/
completeAssetGeneration: (asset: AssetFixture) => {
for (const [taskId, task] of audioTaskRecords) {
audioTaskRecords.set(taskId, {
...task,
status: 'completed',
phaseDetail: '生成已完成。',
finishedAtMillis: 2,
assetId: asset.id,
error: null,
});
}
registeredAssets.push(asset);
},
};
}
@@ -518,7 +548,6 @@ describe('画布生成入口的宿主生命周期', () => {
test('音频入口:提交后占位进入 submitted,成功后结果落到占位最新位置并撤掉占位', async () => {
const tauri = installHostTauri({
assets: [seedBgmAsset('seed-bgm')],
deriveResults: [{ ok: true, assetId: NEW_ASSET_ID, hold: true }],
});
render(<HostWorkbench assets={[seedBgmAsset('seed-bgm')]} />);
await settle();
@@ -529,18 +558,39 @@ describe('画布生成入口的宿主生命周期', () => {
expect(placeholder.dataset.resourceCanvasGenerationPlaceholderStatus).toBe(
'draft',
);
expect(tauri.deriveCalls).toEqual([]);
expect(tauri.assetGenerationStarts).toEqual([]);
fireEvent.click(panelSubmitButton('生成背景音乐'));
await settle();
// 提交一次:走无源生成(create)链路;后台还在跑,占位收口为 submitted。
expect(tauri.deriveCalls).toHaveLength(1);
expect(tauri.deriveCalls[0]).toMatchObject({
editKind: 'background-music',
generationMode: 'create',
expectedProjectId: PROJECT_ID,
/*
提交一次:音频与图片类走**同一条命令**(`start_local_project_asset_generation`),载荷只有
「任务 id = operation id」+ 幂等键,没有图片类那套比例 / 尺寸 / 参考 / 落点参数。
*/
expect(tauri.assetGenerationStarts).toHaveLength(1);
const musicStart = tauri.assetGenerationStarts[0]!;
expect(musicStart).toMatchObject({
projectPath: PROJECT_PATH,
projectId: PROJECT_ID,
kind: 'background-music',
prompt: '一段平静的夜晚钢琴曲',
assetName: '新背景音乐',
});
expect(Object.keys(musicStart).sort()).toEqual([
'assetName',
'idempotencyKey',
'kind',
'projectId',
'projectPath',
'prompt',
'taskId',
]);
expect(String(musicStart.taskId)).toMatch(/^[0-9a-f-]{36}$/);
expect(String(musicStart.idempotencyKey)).toMatch(/^[0-9a-f-]{36}$/);
// 音频不再走同步派生通道。
expect(tauri.deriveCalls).toEqual([]);
// 后台还在跑:占位收口为 submitted。
await waitFor(() =>
expect(
placeholderElement(draftId)?.dataset
@@ -548,42 +598,42 @@ describe('画布生成入口的宿主生命周期', () => {
).toBe('submitted'),
);
// 放行后台任务:结果入库。
// 后台任务收口:账本记完成并登记素材(真实链路里由 Rust 任务写这两件事)。
await act(async () => {
tauri.releaseHeldDerive();
tauri.completeAssetGeneration(bgmAsset(NEW_ASSET_ID));
await Promise.resolve();
});
// 结果入库后:新卡落在占位坐标上(占位在空栏目里落在原点),占位被撤掉。
await waitFor(() => {
expect(
tauri.layoutWrites
.filter((write) =>
write.positions.some(
(position) => position.resourceId === NEW_RESOURCE_ID,
),
)
.map((write) => {
const landed = write.positions.find(
(position) => position.resourceId === NEW_RESOURCE_ID,
)!;
return `${write.mode}:${landed.section}@${landed.x},${landed.y}${
landed.manuallyPlaced ? 'M' : 'A'
}`;
})
.join(' || '),
).toContain(`type:audio@${placeholderPoint.x},${placeholderPoint.y}M`);
});
await waitFor(
() => {
expect(
tauri.layoutWrites
.filter((write) =>
write.positions.some(
(position) => position.resourceId === NEW_RESOURCE_ID,
),
)
.map((write) => {
const landed = write.positions.find(
(position) => position.resourceId === NEW_RESOURCE_ID,
)!;
return `${write.mode}:${landed.section}@${landed.x},${landed.y}${
landed.manuallyPlaced ? 'M' : 'A'
}`;
})
.join(' || '),
).toContain(`type:audio@${placeholderPoint.x},${placeholderPoint.y}M`);
},
{ timeout: 5_000 },
);
await waitFor(() => expect(allPlaceholders()).toHaveLength(0));
});
}, 20_000);
test('失败后用同一份请求重试:复用同一个 operationId 与幂等键', async () => {
test('未受理的即时失败:面板连原草稿与原请求身份自动带回来', async () => {
const tauri = installHostTauri({
assets: [seedBgmAsset('seed-bgm')],
deriveResults: [
{ ok: false, message: 'result-unknown: 测试网络中断' },
{ ok: true, assetId: NEW_ASSET_ID },
],
assetGenerationStartError: '项目权限策略拒绝执行:asset.register',
});
render(<HostWorkbench assets={[seedBgmAsset('seed-bgm')]} />);
await settle();
@@ -591,30 +641,74 @@ describe('画布生成入口的宿主生命周期', () => {
const { draftId } = await openBgmEntry();
fireEvent.click(panelSubmitButton('生成背景音乐'));
await settle();
expect(tauri.deriveCalls).toHaveLength(1);
// 失败:占位留着(输入与操作身份都还在),状态收口为 failed。
expect(tauri.assetGenerationStarts).toHaveLength(1);
/*
后端**从未受理**:这次输入没有被任务接走,所以占位留在画布上,面板连同原草稿与原请求
身份一起被带回来——用户改完可以直接重试,而不会丢掉刚写的东西。
*/
await waitFor(() => expect(floatingPanel()).not.toBeNull());
expect(floatingPanel()?.textContent ?? '').toContain(
'项目权限策略拒绝执行:asset.register',
);
expect(floatingPanelPrompt()?.value ?? '').toBe('一段平静的夜晚钢琴曲');
expect(
placeholderElement(draftId)?.dataset
.resourceCanvasGenerationPlaceholderStatus,
).toBe('failed');
// 同一张占位再提交:同一对 operation / 幂等键——这是同一次生成的重试,不是第二次付费请求。
tauri.assetGenerationStartError.current = undefined;
fireEvent.click(floatingPanelSubmit());
await settle();
await waitFor(() => expect(tauri.assetGenerationStarts).toHaveLength(2));
expect(tauri.assetGenerationStarts[1]).toMatchObject({
taskId: tauri.assetGenerationStarts[0]!.taskId,
idempotencyKey: tauri.assetGenerationStarts[0]!.idempotencyKey,
kind: 'background-music',
prompt: '一段平静的夜晚钢琴曲',
});
// 这次后端受理了:面板同步关闭且**不再**被带回来(重开只属于「从未受理」)。
await waitFor(() => expect(floatingPanel()).toBeNull());
}, 20_000);
test('失败后用同一份请求重试:复用同一个 operationId 与幂等键', async () => {
const tauri = installHostTauri({
assets: [seedBgmAsset('seed-bgm')],
assetGenerationRecord: 'failed',
});
render(<HostWorkbench assets={[seedBgmAsset('seed-bgm')]} />);
await settle();
const { draftId } = await openBgmEntry();
fireEvent.click(panelSubmitButton('生成背景音乐'));
await settle();
expect(tauri.assetGenerationStarts).toHaveLength(1);
// 失败:占位留着(输入与任务身份都还在),状态收口为 failed。
await waitFor(() =>
expect(
placeholderElement(draftId)?.dataset
.resourceCanvasGenerationPlaceholderStatus,
).toBe('failed'),
);
// 提交即关闭:面板不留在屏幕上等结果。
expect(floatingPanel()).toBeNull();
// 面板上的原请求重试:同一次生成,不该变成第二次付费请求。
const retry = screen
.getAllByRole('button')
.find((button) => button.textContent?.includes('重试'));
expect(retry).toBeDefined();
fireEvent.click(retry!);
// 点占位把面板带回来:失败原因是**那张占位**的,重试仍是同一次生成。
fireEvent.click(placeholderElement(draftId)!);
await settle();
expect(floatingPanel()?.textContent ?? '').toContain('测试:生成失败');
fireEvent.click(floatingPanelSubmit());
await settle();
await waitFor(() => expect(tauri.deriveCalls).toHaveLength(2));
expect(tauri.deriveCalls[1]).toMatchObject({
operationId: tauri.deriveCalls[0]!.operationId,
idempotencyKey: tauri.deriveCalls[0]!.idempotencyKey,
prompt: tauri.deriveCalls[0]!.prompt,
await waitFor(() => expect(tauri.assetGenerationStarts).toHaveLength(2));
expect(tauri.assetGenerationStarts[1]).toMatchObject({
taskId: tauri.assetGenerationStarts[0]!.taskId,
idempotencyKey: tauri.assetGenerationStarts[0]!.idempotencyKey,
kind: 'background-music',
prompt: tauri.assetGenerationStarts[0]!.prompt,
});
});
}, 20_000);
});
/**
@@ -630,7 +724,6 @@ describe('生成浮层按占位隔离(宿主回归)', () => {
test('同类不同草稿:切到另一条音频工具是新面板,切回来原草稿还在', async () => {
const tauri = installHostTauri({
assets: [seedBgmAsset('seed-bgm')],
deriveResults: [],
});
render(<HostWorkbench assets={[seedBgmAsset('seed-bgm')]} />);
await settle();
@@ -654,13 +747,10 @@ describe('生成浮层按占位隔离(宿主回归)', () => {
expect(floatingPanelPrompt()?.value ?? '').toBe('一段平静的夜晚钢琴曲');
});
test('失败态切换:失败原因与操作身份都不跟着换占位', async () => {
test('失败态切换:失败原因与任务身份都不跟着换占位', async () => {
const tauri = installHostTauri({
assets: [seedBgmAsset('seed-bgm')],
deriveResults: [
{ ok: false, message: 'result-unknown: 测试网络中断' },
{ ok: true, assetId: NEW_ASSET_ID },
],
assetGenerationRecord: 'failed',
});
render(<HostWorkbench assets={[seedBgmAsset('seed-bgm')]} />);
await settle();
@@ -668,37 +758,47 @@ describe('生成浮层按占位隔离(宿主回归)', () => {
const { draftId } = await openBgmEntry();
fireEvent.click(floatingPanelSubmit());
await settle();
expect(tauri.deriveCalls).toHaveLength(1);
expect(tauri.assetGenerationStarts).toHaveLength(1);
// 提交即关面板:失败由占位收口,原因留在那张占位上。
await waitFor(() =>
expect(floatingPanel()?.textContent ?? '').toContain('测试网络中断'),
expect(
placeholderElement(draftId)?.dataset
.resourceCanvasGenerationPlaceholderStatus,
).toBe('failed'),
);
expect(floatingPanel()).toBeNull();
fireEvent.click(placeholderElement(draftId)!);
await settle();
expect(floatingPanel()?.textContent ?? '').toContain('测试:生成失败');
// 切到音效:上一条的失败原因与「输入已锁定」都不得跟着它走。
// 切到音效:上一条的失败原因不得跟着它走,输入也不该被锁。
await openAudioTool('生成音效');
expect(floatingPanel()?.textContent ?? '').not.toContain('测试网络中断');
expect(floatingPanel()?.textContent ?? '').not.toContain('测试:生成失败');
expect(floatingPanelPrompt()?.disabled).toBe(false);
expect(floatingPanelPrompt()?.value ?? '').toBe('');
// 在音效面板提交:这是**新的**请求,不能复用背景音乐那条失败请求的操作身份。
// 在音效面板提交:这是**新的**请求,不能复用背景音乐那条失败请求的任务身份。
await typeGenerationPrompt(floatingPanel()!, '一段清脆的铃声');
fireEvent.click(floatingPanelSubmit());
await settle();
expect(tauri.deriveCalls).toHaveLength(2);
expect(tauri.deriveCalls[1]!.operationId).not.toBe(
tauri.deriveCalls[0]!.operationId,
await waitFor(() => expect(tauri.assetGenerationStarts).toHaveLength(2));
expect(tauri.assetGenerationStarts[1]!.taskId).not.toBe(
tauri.assetGenerationStarts[0]!.taskId,
);
expect(tauri.deriveCalls[1]).toMatchObject({ editKind: 'sound-effect' });
expect(tauri.assetGenerationStarts[1]).toMatchObject({
kind: 'sound-effect',
});
// 回到原占位重试:必须复用原请求的操作身份与幂等键(同一 operation 账本)。
// 回到原占位重试:必须复用原任务的操作身份与幂等键(同一 operation 账本)。
fireEvent.click(placeholderElement(draftId)!);
await settle();
fireEvent.click(floatingPanelSubmit());
await settle();
expect(tauri.deriveCalls).toHaveLength(3);
expect(tauri.deriveCalls[2]).toMatchObject({
operationId: tauri.deriveCalls[0]!.operationId,
idempotencyKey: tauri.deriveCalls[0]!.idempotencyKey,
prompt: tauri.deriveCalls[0]!.prompt,
await waitFor(() => expect(tauri.assetGenerationStarts).toHaveLength(3));
expect(tauri.assetGenerationStarts[2]).toMatchObject({
taskId: tauri.assetGenerationStarts[0]!.taskId,
idempotencyKey: tauri.assetGenerationStarts[0]!.idempotencyKey,
prompt: tauri.assetGenerationStarts[0]!.prompt,
});
});
@@ -706,7 +806,6 @@ describe('生成浮层按占位隔离(宿主回归)', () => {
const user = userEvent.setup();
const tauri = installHostTauri({
assets: [imageAsset('ref-img', 'ref.png')],
deriveResults: [],
assetGenerationRecord: 'failed',
});
render(
@@ -771,7 +870,6 @@ describe('生成浮层按占位隔离(宿主回归)', () => {
const user = userEvent.setup();
const tauri = installHostTauri({
assets: [imageAsset('ref-img', 'ref.png')],
deriveResults: [],
assetGenerationRecord: 'failed',
});
render(
@@ -99,10 +99,11 @@ type Mock = {
function installTauri({
assets,
deriveFails = false,
assetGenerationFailed = false,
}: {
assets: GameCreationAppAssetManifestEntry[];
deriveFails?: boolean;
/** 后台账本里那条任务是不是「已受理、之后失败」的终态。 */
assetGenerationFailed?: boolean;
}): Mock {
const layoutWrites: ProjectResourceCanvasPosition[][] = [];
const generationStarts: Record<string, unknown>[] = [];
@@ -163,20 +164,22 @@ function installTauri({
return [];
}
if (command === 'list_local_project_asset_generations') {
// 账本里的终态记录:队列轮询一次就收口为成功,并给出 manifest 资源 id。
// 账本里的终态记录:队列轮询一次就收口,成功时给出 manifest 资源 id。
return [
{
taskId: String(args?.taskId ?? '') || LAST_TASK_ID.value,
projectId: PROJECT_ID,
kind: 'image',
assetName: 'AI 生成图片',
status: 'completed',
phaseDetail: '生成已完成。',
status: assetGenerationFailed ? 'failed' : 'completed',
phaseDetail: assetGenerationFailed
? '生成失败:远端拒绝'
: '生成已完成。',
createdAtMillis: 1,
startedAtMillis: 2,
finishedAtMillis: 3,
assetId: GENERATED_ASSET_ID,
error: null,
assetId: assetGenerationFailed ? null : GENERATED_ASSET_ID,
error: assetGenerationFailed ? '远端拒绝' : null,
},
];
}
@@ -198,12 +201,14 @@ function installTauri({
};
}
if (command === 'derive_local_project_resource') {
const input = (args?.input ?? {}) as Record<string, unknown>;
deriveInputs.push(structuredClone(input));
if (deriveFails) {
throw new Error('远端拒绝');
}
return { asset: null, manifest: structuredClone(manifest) };
/*
生成入口(音频与图片类)都走后台任务账本:同步派生通道不该再被触发。真被调到就大声
失败,而不是静默返回一个像模像样的结果。
*/
deriveInputs.push(
structuredClone((args?.input ?? {}) as Record<string, unknown>),
);
throw new Error('生成入口不应再走同步派生通道');
}
if (command === 'read_local_project_image_preview') {
return {
@@ -465,9 +470,9 @@ describe('浮层按真实矩形落在画布安全带内', () => {
});
describe('音频生成身份', () => {
test('失败保留占位与草稿,重试复用同一 operationId', async () => {
test('失败保留占位与草稿,重试复用同一 operationId 与幂等键', async () => {
const assets = [pngAsset('asset-character', 'character.png')];
const tauri = installTauri({ assets, deriveFails: true });
const tauri = installTauri({ assets, assetGenerationFailed: true });
render(<Workbench assets={assets} />);
await openCategory('音频');
@@ -479,11 +484,24 @@ describe('音频生成身份', () => {
fireEvent.click(
within(panel).getByRole('button', { name: '生成背景音乐' }),
);
await waitFor(() => expect(tauri.deriveInputs).toHaveLength(1));
const firstOperationId = tauri.deriveInputs[0]?.operationId;
expect(typeof firstOperationId).toBe('string');
// 失败:占位收口为失败并保留(不是被删掉),面板仍在且带原因。
// 音频与图片类同一条后台通道:任务 id 就是这次生成的 operation id,载荷带幂等键。
await waitFor(() => expect(tauri.generationStarts).toHaveLength(1));
const firstTaskId = tauri.generationStarts[0]?.taskId;
expect(typeof firstTaskId).toBe('string');
expect(tauri.generationStarts[0]).toMatchObject({
kind: 'background-music',
prompt: '轻快的八音盒',
idempotencyKey: expect.any(String),
});
// 音频不再走同步派生通道。
expect(tauri.deriveInputs).toEqual([]);
// 提交即关闭:面板不留在屏幕上等结果。
await waitFor(() =>
expect(screen.queryByRole('dialog', { name: '生成背景音乐' })).toBeNull(),
);
// 失败:占位收口为失败并保留(不是被删掉)。
await waitFor(() =>
expect(
document.querySelector<HTMLElement>(
@@ -492,13 +510,7 @@ describe('音频生成身份', () => {
).not.toBeNull(),
);
// 收起浮层后再点占位:草稿灌回来,重试复用同一 operationId(原生幂等,不重复付费)。
fireEvent.click(
within(panel).getByRole('button', { name: '关闭生成背景音乐' }),
);
await waitFor(() =>
expect(screen.queryByRole('dialog', { name: '生成背景音乐' })).toBeNull(),
);
// 点占位:草稿灌回来,重试复用同一 operationId / 幂等键(原生幂等,不重复付费)。
fireEvent.click(
document.querySelector<HTMLElement>(
'[data-resource-canvas-generation-placeholder]',
@@ -515,10 +527,10 @@ describe('音频生成身份', () => {
fireEvent.click(
within(reopened).getByRole('button', { name: '使用原请求重试' }),
);
await waitFor(() => expect(tauri.deriveInputs).toHaveLength(2));
expect(tauri.deriveInputs[1]?.operationId).toBe(firstOperationId);
expect(tauri.deriveInputs[1]?.idempotencyKey).toBe(
tauri.deriveInputs[0]?.idempotencyKey,
await waitFor(() => expect(tauri.generationStarts).toHaveLength(2));
expect(tauri.generationStarts[1]?.taskId).toBe(firstTaskId);
expect(tauri.generationStarts[1]?.idempotencyKey).toBe(
tauri.generationStarts[0]?.idempotencyKey,
);
}, 20_000);
});
@@ -1,6 +1,6 @@
# AI 游戏创作项目开发工作台 PRD
更新时间:`2026-09-14`(同步功能画布图片类生成后台化的当前事实:入口 IPC 改为 `start_local_project_asset_generation` + 项目内任务账本 + 本地排队 + 非模态「生成任务」面板,见 §3.10 / §7.9;2026-09-13 新增的功能画布底部工具栏入口矩阵 §3.10 / §7.9,以及右侧 Supervisor 对话气泡、可访问对比度与过程卡布局收口,资源卡预览、分区布局、非破坏性资源编辑、资源替换与 Godot 双根合同保持不变)
更新时间:`2026-09-20`(同步功能画布图片类生成后台化的当前事实,以及 2026-09-20 音频生成并入同一条后台任务账本:入口 IPC 为 `start_local_project_asset_generation` + 项目内任务账本 + 本地排队 + 非模态「生成任务」面板,见 §3.10 / §7.9;2026-09-13 新增的功能画布底部工具栏入口矩阵 §3.10 / §7.9,以及右侧 Supervisor 对话气泡、可访问对比度与过程卡布局收口,资源卡预览、分区布局、非破坏性资源编辑、资源替换与 Godot 双根合同保持不变)
## 1. 产品定位
@@ -151,7 +151,7 @@
### 3.10 功能画布底部工具栏(入口矩阵)
实现状态(2026-09-13;2026-09-14 图片类生成后台化:提交即返回 + 项目内任务账本 + 本地排队 + 非模态「生成任务」面板):功能画布 = 资源栏目页(`resourceBookState.view === 'child'`)。栏目页左下角的底部工具栏按 manifest 资产的**功能分类** `category` 分流,矩阵由用户 2026-09-13 拍板,工具项顺序即下表顺序(最右一项为「上传」)。
实现状态(2026-09-13;2026-09-14 图片类生成后台化:提交即返回 + 项目内任务账本 + 本地排队 + 非模态「生成任务」面板;2026-09-20 音频生成并入同一条后台任务账本):功能画布 = 资源栏目页(`resourceBookState.view === 'child'`)。栏目页左下角的底部工具栏按 manifest 资产的**功能分类** `category` 分流,矩阵由用户 2026-09-13 拍板,工具项顺序即下表顺序(最右一项为「上传」)。
| 栏目 | 工具栏里的生成入口 |
| --- | --- |
@@ -163,7 +163,7 @@
- 位置与层级:画布左下角(`left: 14px; bottom: 14px; z-index: 40`)。右下角是既有的缩放 / 撤销 Dock(`right: 14px; bottom: 14px`),左下角是画布上唯一两者都不占的稳定空位。工具栏是管理区 `.game-resource-book-manager` 的**直接子节点**、与画本场景并列,不进带 `scale()` 的场景层;二级菜单与「入口不可用原因」都贴着工具栏上沿弹出,不做内嵌内容。
- 外壳用共享 chrome(`packages/image-canvas-react` 的 `CanvasToolbar / CanvasToolbarGroup / CanvasChromeButton`),样式落在 AGC 的 `resourceCanvasChrome.css`;共享包只承接通用表现,不含业务规则。
- 接线:图片类入口走本地 IPC `start_local_project_asset_generation`(`kind` ∈ `image / character / spec / icon-spec / ui-prototype / art-spritesheet`;**提交即返回任务记录**,生成由 Rust 后台任务跑完写回项目,进度用 `list_local_project_asset_generations` 读回项目内账本 `.agent/runtime/asset-generation-tasks/tasks.json`);音频入口复用既有的无源生成链路 `derive_local_project_resource`(`generationMode: 'create'`、`editKind` = `sound-effect` / `background-music`);「上传」复用 `upload_local_asset`。生成 / 上传成功后一律用「配对读 `(revision, manifest)`」交给 `onManifestChange`,走既有 manifest 刷新与资源投影链路,不重算依赖图、不另写布局。
- 接线:图片类入口走本地 IPC `start_local_project_asset_generation`(`kind` ∈ `image / character / spec / icon-spec / ui-prototype / art-spritesheet`;**提交即返回任务记录**,生成由 Rust 后台任务跑完写回项目,进度用 `list_local_project_asset_generations` 读回项目内账本 `.agent/runtime/asset-generation-tasks/tasks.json`);音频入口也走 `start_local_project_asset_generation`(同一份项目内任务账本;`kind` = `sound-effect` / `background-music`,并额外携带该次生成的请求身份 `idempotencyKey`,任务 id 即该次生成的 operation id;生成仍复用既有音频无源生成链路,`generationMode: 'create'`、`editKind` = `sound-effect` / `background-music`,不新增平台路由与请求体口径);「上传」复用 `upload_local_asset`。生成 / 上传成功后一律用「配对读 `(revision, manifest)`」交给 `onManifestChange`,走既有 manifest 刷新与资源投影链路,不重算依赖图、不另写布局。
- 本地排队与进度可见:AGC 本地 durable 输出槽已按**精确动作指纹**分槽(不同 prompt / 素材名各自独立成槽,具备并行能力),但本批前端仍按「同一时刻只派发一条」排队——真并行派发需要并发收口设计(配对读 + manifest CAS + 聚焦意图互不覆盖),留待下一批;所以第一条未终态时第二条提交停在**前端本地队列**里(不调用提交 IPC,显示本地排队的「排队中。」),前一条终态后自动补发;任务状态与阶段文案(后端 `phaseDetail`)由任务账本提供,前端不拼阶段、不做百分比。进度面是**画布上常驻的可折叠任务侧栏**(形态对齐网页端美术画布的任务侧栏):展开是两个分栏「排队/生成中」与「已完成」(各带条数,「已完成」封顶 20 条 + 列表滚动 + 高度有界),关闭入口只保留头部那一枚 ×(底部重复的关闭按钮与其分割线已删除)、折叠即整块让出画布且不留贴边把手,开合只走工具条上常驻的「生成任务 · N」按钮(两个页签下都在);每项显示状态徽标 / 阶段文案 / 已耗时 / 素材名,可「定位到素材」。侧栏非模态(不铺全屏遮罩、不做焦点陷阱、不参与模态遮挡判据),位置在画布左侧标题栏之下、**覆盖式**(不 reflow 挤窄画布视口),提交受理后自动展开。定位动作**每次点击都终局化**:能定位就定位并选中;素材在别的栏目先切栏目;不在投影里给「素材已不在项目里 / 已登记但尚未同步」的结论;3 秒内有界兜底,不允许提示条永久停在「正在定位生成的素材…」。
- 面板形态:独立浮层(`ThemedModal`),**不在当前面板下面追加内容**;面板内不写功能说明或规则解释文案。**点「生成」即同步关闭面板**(不等 IPC、不等排队、不等生成),面板里**不出现**「排队中。」「正在生成。」「提交中…」这类阶段文案——阶段文案的唯一去处是任务侧栏与工具栏提示条。**只有「点击瞬间就失败」**(校验不过、权限拒绝、start IPC 立即报错)才自动重开面板并带回草稿与原因;**受理之后才失败**只在侧栏把该任务收口为失败 + 原因,不重开面板。关闭 ≠ 取消请求(请求挂在任务与账本上,不挂在面板生命周期上)。
- 参数口径:比例 / 尺寸选项来自网页端美术画布的纯模型(`src/components/image-editor/ImageCanvasGenerationModel.ts`),并按本地 IPC 白名单收窄(本地通道明确拒绝 `4:3`);默认档 `1:1 · 1K`,生成 UI 设计图沿用网页端 UI 设计面板的默认 `16:9 · 1K`。本地 IPC 没有 `model` 入参,因此面板**不渲染模型选择器**(渲染一个改不了请求的控件就是假控件)。
@@ -665,9 +665,10 @@ type ProjectAgentMudPointAttribution = {
3. 每个图片类入口一次提交**一条** `start_local_project_asset_generation`,载荷字段逐字为 `{ projectPath, projectId, taskId, kind, prompt, aspectRatio, imageSize, assetName, outputPath }`——**原同步命令的生成载荷字段名与取值口径逐字不变**(`kind / prompt / aspectRatio / imageSize / assetName / outputPath` 全部原样搬过来),只多了任务身份 `projectId` 与前端每次提交新铸的本地 `taskId`;`kind` 映射:生成图片 `image`、生成角色形象 `character`、图标规范 `icon-spec`、角色规范 / 自定义规范 `spec`、生成图标素材 `art-spritesheet`、生成 UI 设计图 `ui-prototype`。命令**提交即返回**一条任务记录,生成在 Rust 后台任务里跑,状态与阶段由 `list_local_project_asset_generations` 从项目内账本读回。
4. 比例 / 尺寸选项**不含**本地通道拒绝的 `4:3`;比例与尺寸的切换都进入载荷;固定档规范入口只读展示当前规格(如 `1:1·1K`),不渲染可点比例控件。
5. 缺权威规范图时「生成图标素材 / 生成 UI 设计图」保持可点击、给出含 `assets/art-spec.png` 的原因说明,且**不发出任何生成请求**;「图标规范」此时把 `outputPath` 指向 `assets/art-spec.png`;项目已有权威规范图时 `outputPath` 为 `null`(两种状态各一条用例)。
6. 生成 / 上传成功后走既有刷新路径:`get_local_game_project_revision` + `get_local_game_manifest` 的配对读发生在**该任务收口之后**(提交命令不再等待生成,配对读由任务终态驱动,顺序仍在写入之后),结果交给 `onManifestChange`;音频入口提交的是 `derive_local_project_resource`(`editKind` = `sound-effect` / `background-music`、`generationMode: 'create'`、`sourceMediaType: 'audio/mpeg'`)。
6. 生成 / 上传成功后走既有刷新路径:`get_local_game_project_revision` + `get_local_game_manifest` 的配对读发生在**该任务收口之后**(提交命令不再等待生成,配对读由任务终态驱动,顺序仍在写入之后),结果交给 `onManifestChange`;音频入口提交同一条命令的音频载荷(`kind` = `sound-effect` / `background-music`、`idempotencyKey` = 该次生成的幂等键、任务 id 即该次生成的 operation id);原生命令内部仍复用既有音频无源生成链路(`editKind` = `sound-effect` / `background-music`、`generationMode: 'create'`、`sourceMediaType: 'audio/mpeg'`),不新增平台路由、请求体或计费口径。
7. 既有「生成素材」浮层入口只呈现视频:面板不再渲染音效 / 背景音乐类型选择器(单类型入口没有类型选择器),音频入口只出现在音频栏目工具栏。
8. 生成期间可退出与本地排队(2026-09-14):提交后点 × / 遮罩 / Esc /「后台运行并关闭」任一都能关面板,画布立即恢复可交互,关闭不取消请求;面板关闭后任务仍在「生成任务」面板(非模态浮层,无 `aria-modal`)里显示后端 `phaseDetail`;第一条未终态时提交第二条 → 第二条显示「排队中。」且生成提交 IPC 次数仍为 1,第一条终态后自动补发(次数为 2);两条各自完成后各走一次「配对读 + 落卡」,manifest revision 单调、不被后到者覆盖。
8. 提交即关闭与本地排队(2026-09-14 图片类后台化,2026-09-20 音频并入同一条通道):点「生成」就把这次输入交给后台任务账本并**同步关闭**面板(不等 IPC、不等排队、不等生成),画布立即恢复可交互,关闭不等于取消;面板里因此不出现「排队中。」「正在生成。」「提交中…」与「后台运行并关闭」这类阶段文案与在途按钮,未提交时点 × / 遮罩 / Esc 收起面板只是收起草稿、不发请求;面板关闭后任务仍在「生成任务」面板(非模态浮层,无 `aria-modal`)里显示后端 `phaseDetail`;第一条未终态时提交第二条 → 第二条显示「排队中。」且生成提交 IPC 次数仍为 1,第一条终态后自动补发(次数为 2);两条各自完成后各走一次「配对读 + 落卡」,manifest revision 单调、不被后到者覆盖。
9. 音频生成进入后台任务账本(2026-09-20):音频栏目的「生成背景音乐 / 生成音效」提交后**立即**返回一条任务记录并同步关闭面板(不等 IPC、不等排队、不等生成);任务与图片类任务在同一条本地队列里按「同一时刻只派发一条」排队,面板关闭后仍在「生成任务」侧栏显示后端 `phaseDetail`;成功走既有的「配对读 `(revision, manifest)` + 落占位最新位置」;只有「点击瞬间就失败」(未受理)才自动重开面板并带回原草稿与原请求身份,受理之后才失败只在侧栏收口为失败。同一份失败原请求的重试复用同一 operation 与幂等键,不产生第二次付费生成;重开项目后音频任务从账本恢复显示,上次运行中断的任务按中断口径收口。
## 8. 非目标
@@ -0,0 +1,51 @@
# 【实施计划】AGC 音频生成进入后台任务账本
| 字段 | 值 |
| --- | --- |
| Milestone | `docs/project-memory/plans/【里程碑】AGC音频生成进入后台任务账本-2026-09-20.md` |
| Status | implemented-awaiting-runtime-acceptance |
| Owner | 主 Agent(自审;本运行没有独立评审人) |
## 修改边界
- 允许修改:
- 主规范:`docs/prd/【AI游戏创作】项目开发工作台PRD-2026-07-20.md`(§3.10 / §7.9)、`docs/technical/【AGC】栏目画布底部工具栏入口矩阵-2026-09-13.md`。
- AGC 原生:`apps/ai-game-creator-shell/src-tauri/src/asset_generation_tasks.rs`、`commands.rs`、`project.rs`、`project/resource_editor.rs`(仅新增收口入口,不改既有派生语义)。
- AGC 前端:`apps/ai-game-creator-shell/src/features/resource-canvas/resourceCanvasAssetGenerationTaskModel.ts`、`resourceCanvasAssetGenerationQueue.ts`、`view/project-development/index.tsx`。
- 定向测试:`apps/ai-game-creator-shell/tests/resourceCanvasGenerationHostLifecycle.test.tsx`、`resourceCanvasAssetGenerationQueue.test.ts`、`appSurface/project-development.suite.ts`(仅音频相关断言)。
- 明确不修改:`/api/editor/audios/*/generations` 与 `/api/external/v1` 路由、请求体、OpenAPI、共享 DTO、SpacetimeDB schema、权限命令词汇、`derive_local_project_resource` 的同步语义与其既有无源生成入参校验。
## 实现顺序
1. 主规范:把音频入口的接线口径从「同步无源生成」改写为「与图片类同一条后台任务账本」,并补上音频提交载荷、失败重开与幂等条款(PRD §3.10 / §7.9,AGC 工具栏入口矩阵文档)。
2. 原生:在资源编辑模块新增音频入参收口与「后台跑一次音频派生」的入口(复用既有派生实现,不复制生成逻辑);在 `asset_generation_tasks` 里按 `kind` 分流,音频任务复用同一份账本、同一套阶段文案与中断收口;`start_local_project_asset_generation` 增加可选幂等键入参,音频 kind 走新分支且不改图片类载荷口径。
3. 原生测试:音频任务入参收口(kind / 提示词上限 / 幂等键 / 未知 kind 拒绝)、账本记录 kind 为音频、图像载荷口径不回归。
4. 前端模型与队列:任务模型支持音频任务(kind、请求身份、无比例 / 尺寸 / 参考字段),音频 kind 的入口文案从工具栏模型派生;队列按 kind 分流派发同一命令的音频载荷,其余排队与轮询语义不变。
5. 前端宿主:音频提交改为「入队即返回」,占位绑定任务 id、自动展开侧栏、给出提示条;收口复用既有「配对读 + 落卡」链路,未受理失败按原请求身份重开音频面板。
6. 前端测试:宿主生命周期(提交即关闭、侧栏可见、落卡、未受理失败重开并复用身份)、队列音频分支(载荷与轮询、第二条本地排队不发 IPC)、appSurface 音频载荷。
7. 验证与证据矩阵:跑定向测试、类型检查、编码 / 文档索引 / `git diff --check`,按里程碑逐条填写证据。
## 验证命令
1. `npx vitest run apps/ai-game-creator-shell/tests/resourceCanvasGenerationHostLifecycle.test.tsx apps/ai-game-creator-shell/tests/resourceCanvasAssetGenerationQueue.test.ts apps/ai-game-creator-shell/tests/resourceCanvasAssetGenerationTasksPanel.test.tsx`
2. `npx vitest run apps/ai-game-creator-shell/tests/appSurface.test.ts`
3. `cargo test -p genarrative-ai-game-creator-shell asset_generation_task`
4. `npm run agc:typecheck`(或 `npm run typecheck --workspace @genarrative/ai-game-creator-shell`)
5. `npm run check:encoding && npm run check:doc-index && git diff --check`
## 执行结果
1. 主规范:PRD(§3.10 / §7.9 / §7.9 第 8~9 条)与 AGC 工具栏入口矩阵文档改为「音频与图片类同一条后台任务账本」,同步 `【测试用例】AGC资源工作台V3端到端验收` 的 S11a 判据。
2. 原生:`prepare_local_project_audio_generation`(提交期收口)+ `run_local_project_audio_generation_at`(派发时刻读 revision,复用派生实现),`start_local_project_asset_generation` 新增可选 `idempotencyKey` 并在音频 kind 分支落同一份账本、由 `run_local_project_audio_generation_task` 写 running → completed / failed;图片类分支逐字未改。
3. 前端:任务模型新增音频任务与 `idempotencyKey`(恢复出来的历史任务不带它,也不承接重试);队列按 kind 分流派发载荷;面板提交改为同步返回并立即关闭;宿主改为同步入队 + 失败重开。
4. 测试:面板(点击即关闭、无阶段文案与在途按钮)、队列(音频载荷逐字)、宿主生命周期(提交关闭 / 侧栏 / 落卡 / 未受理重开 / 受理后不重开 / 重试身份复用 / 失败态按占位隔离)、appSurface 音频载荷。
5. 验证命令与结果:9 个定向 vitest 文件 73 项通过;`appSurface.test.ts` 552 项通过(17 项跳过);`cargo test asset_generation_task` 14 项通过;`npm run agc:typecheck`、`npm run check:encoding`、`npm run check:doc-index`、`git diff --check` 通过。
6. 与预期不一致处:音频任务不再携带 `targetCategory`(原生音频通道不消费它,前端也没有读它的地方);`restored` 任务无幂等键,只用于展示与定位,不承接重试。
7. 已知与本任务无关的既有失败:`clientAuthStorage` / `clientApi` / `clientHttp` / `chatPromptPolish` / `projectCreationDirectory` 五个文件在本机 Node v26 + vitest 0.34 的 jsdom 下 `localStorage` 为 undefined(在干净工作区同样失败);`cargo test resource_edit` 整组过滤下有 5 项既有并行干扰失败(单跑通过)。
## 风险与回滚点
- 音频任务与图片类任务共用队列:若音频任务未终态会挡住后续派发(本地排队是既有语义,接受)。回滚点是前端提交分支与原生 `kind` 分流,各自可独立回退。
- 音频自带的 operation 幂等账本与任务账本是两层身份:任务 id 取 operation id,重试复用同一对 operation / 幂等键;不得为「省事」在重试时换新的请求身份(那是一次新的付费生成)。
- 账本 `kind` 为音频时,`restore` 的入口文案若查不到工具栏模型会退化成素材名:入口文案必须由工具栏模型派生,避免恢复后文案漂移。
- 后台跑生成会让「项目 revision CAS」窗口从提交前移到派发时刻:冲突时按失败收口(不静默重试),避免把生成写到非预期基线。
@@ -0,0 +1,51 @@
# 【里程碑】AGC 音频生成进入后台任务账本
| 字段 | 值 |
| --- | --- |
| Version | 1.0 |
| Status | implemented-awaiting-runtime-acceptance |
| Date | 2026-09-20 |
| Parent Spec | `docs/prd/【AI游戏创作】项目开发工作台PRD-2026-07-20.md`(§3.10 / §7.9)、`docs/technical/【AGC】栏目画布底部工具栏入口矩阵-2026-09-13.md` |
## 目标
AGC 功能画布音频栏目的「生成背景音乐 / 生成音效」与图片类生成走**同一条后台生成任务账本**:提交即返回任务记录、生成在客户端后台跑、状态与阶段文案由账本提供,任务出现在画布「生成任务」侧栏里,重开项目后仍能看到并按中断口径收口。
## 范围
- 音频无源生成(`create`)的提交、排队、状态读回、成功落卡、失败收口与重试幂等。
- 音频任务与图片类任务共用同一份项目内任务账本、同一个前端本地排队与同一个「生成任务」侧栏。
- 音频任务的阶段文案、状态与耗时来源与图片类一致(后端账本拥有阶段文案)。
## 不在范围内
- 平台侧(api-server / external v1 / OpenAPI)路由、请求体、计费、队列与 worker 语义:本轮不改,音频仍提交既有 `/api/editor/audios/*/generations` 通道。
- 音频波形级编辑、多轨、时长 / 循环等音频参数入口:仍按现状不做。
- 视频入口、上传入口、图片类生成的参数与前置判据:行为不变。
- 真并行派发(并发收口设计):本轮仍保留「同一时刻只派发一条」的本地排队。
## 依赖与前置条件
- 现有图片类后台任务的账本、轮询、落点与聚焦链路可复用;音频生成通道(资源编辑派生)已具备 operation 幂等账本。
- 音频提交需要携带请求身份(operation 与幂等键),否则重试会变成一次新的付费生成。
## 验收标准与证据
| 验收标准 | 结论 | 证据 |
| --- | --- | --- |
| 音频栏目的「生成背景音乐 / 生成音效」提交后**立即**返回一条任务记录;面板同步关闭,不等 IPC、不等排队、不等生成结束 | 自动化通过 | `resourceCanvasAssetGenerationBackgroundClose.test.tsx`(点「生成音效」同步提交 + 关闭,面板 DOM 里没有阶段文案与「后台运行并关闭」)、`resourceCanvasGenerationEntry.test.tsx`、`resourceCanvasGenerationHostLifecycle.test.tsx`(音频载荷逐字为 `projectPath / projectId / taskId / kind / prompt / assetName / idempotencyKey`) |
| 提交受理后任务出现在「生成任务」侧栏,状态与阶段文案来自后端账本,前端不拼阶段、不做百分比 | 自动化通过 | `resourceCanvasAssetGenerationQueue.test.ts`(音频收口复用同一份账本记录)、`resourceCanvasAssetGenerationTasksPanel.test.tsx`、`resourceCanvasGenerationHostLifecycle.test.tsx`(提交后自动展开侧栏) |
| 音频任务与图片类任务在同一条本地队列里按「同一时刻只派发一条」排队;第二条在本地排队期间不发提交 IPC | 自动化通过 | `resourceCanvasAssetGenerationQueue.test.ts`(音频载荷逐字断言 + 既有本地排队用例) |
| 成功:走既有的「配对读 `(revision, manifest)`」交给 `onManifestChange`,结果落到该占位的最新位置并定位新卡 | 自动化通过 | `resourceCanvasGenerationHostLifecycle.test.tsx`(账本收口为 completed 后新卡落在占位坐标、占位被撤掉) |
| 失败:只有「点击瞬间就失败」(未受理)才自动重开面板并带回原草稿与原请求身份;受理之后才失败只在侧栏收口为失败并给出原因,不重开面板 | 自动化通过 | `resourceCanvasGenerationHostLifecycle.test.tsx`「未受理的即时失败」(重开 + 草稿还原;同一用例里受理后不再重开)与「失败后用同一份请求重试」 |
| 幂等:同一份失败原请求的重试复用同一 operation 与幂等键,不产生第二次付费生成 | 自动化通过 | `resourceCanvasGenerationHostLifecycle.test.tsx`(重试的 `taskId` = operation id 与 `idempotencyKey` 与首次逐字相同)、`resourceCanvasGenerationLanding.test.tsx` |
| 重开项目:音频任务从账本恢复显示;上次运行中断的任务按中断口径收口,不假装还在跑 | 自动化通过(恢复路径) | 音频 kind 的入口文案由工具栏模型派生(`resourceCanvasAssetGenerationTaskModel` + `resourceCanvasAssetGenerationQueue.test.ts`);中断收口沿用既有账本口径 |
| 音频提交失败(校验 / 权限 / 通道拒绝)时 manifest、revision 与任务账本都不出现半途写入 | 自动化通过 | Rust `asset_generation_tasks` 的 `audio_submission_rejects_invalid_identity_and_prompt_without_touching_the_ledger`(提交期拒绝零写入)、`audio_submission_lands_in_the_shared_ledger_with_its_audio_kind` |
运行时验收(未做):没有跑真实付费音频生成,也没有在真实客户端里做手感验收;全链以模拟原生接口的宿主用例覆盖。
## 证据要求
- 自动化:AGC 前端定向 vitest(音频入口宿主生命周期、生成任务队列与侧栏、appSurface 载荷)+ Rust 定向 `cargo test`(账本与音频任务入参收口)+ 类型检查 + 编码 / 文档索引 / `git diff --check`。
- 运行时:无真实付费生成;以模拟原生接口的宿主用例覆盖提交 → 排队 → 收口 → 落卡全链。
- 边界:未受理失败的即时重开与身份复用、账本读不到 / 记录缺失的收口、跨项目切换不串任务。
@@ -9013,3 +9013,14 @@ CI 上 `background_agent_runtime_recovers_stale_running_before_pending_task` 在
- 发号顺序固定「先写总号 → 再构建 → 再发渠道清单」,失败不回滚只烧号;统一构建发一次号供 `dev-win` / `dev-mac` 共用,单渠道热修只作用于该渠道。
- 发号收口到 Jenkins Job `Genarrative-Agc-Global-Version-Issue`(`disableConcurrentBuilds()`;集群无 `lockable-resources`,以写后回读不一致即失败关闭兜底并发)。
- 原渠道高水位逻辑降级为断言:请求号低于本渠道清单版本即失败关闭;`AGC_RELEASE_DRY_RUN` 只预览不烧号。
## 2026-09-20 AGC 音频生成并入图片类那份后台任务账本
- 背景:音频栏目的「生成背景音乐 / 生成音效」原先走同步派生通道(`derive_local_project_resource`),提交后前端一直等到生成结束(最长 35 分钟),所以它不出现在画布「生成任务」侧栏里,也没有本地排队;图片类早已改成「提交即返回 + 项目内任务账本」。
- 决策:音频改走**同一条命令** `start_local_project_asset_generation`(新增可选入参 `idempotencyKey`,音频 kind 必带);原生在 `kind` 上分叉一次(`is_audio_asset_generation_kind` 只放行 `sound-effect` / `background-music`),音频分支落**同一份**项目内账本 `.agent/runtime/asset-generation-tasks/tasks.json`,生成由 `run_local_project_audio_generation_task` 在后台跑并写 running → completed / failed。图片类载荷与分支逐字未改。
- 决策:音频的**任务 id 就是这次生成的 operation id**,请求身份 = 面板铸造的 `operationId` + 幂等键。重试(含失败后点占位重开)必须复用同一对,否则会同一次生成变成第二次付费请求。账本不存幂等键,所以重开项目恢复出来的音频任务只用于展示与定位,不承接重试。
- 决策(UI 口径):音频面板与图片类一致——点「生成」**同步关闭**,面板里不存在「排队中。」「正在生成。」「提交中…」与「后台运行并关闭」这类阶段文案与在途按钮,阶段文案的唯一来源是后端账本、唯一去处是「生成任务」侧栏。只有「点击瞬间就失败」(校验 / 权限 / 提交 IPC 立即报错,即后端从未受理)才由宿主把面板连原草稿与原请求身份带回来;受理之后才失败只在侧栏收口为失败。
- 决策(时机):项目 revision 的 CAS 由「提交前读」改为「派发时刻读」(`run_local_project_audio_generation_at`);冲突按失败收口,不静默重试,避免把生成写到用户没预期的基线上。
- 不变口径:平台侧 `/api/editor/audios/*/generations` 路由、请求体、计费与 `/api/external/v1`、OpenAPI、共享 DTO、SpacetimeDB schema 一律未动;音频仍复用既有资源编辑派生实现,不复制生成逻辑。
- 关联规范:`docs/prd/【AI游戏创作】项目开发工作台PRD-2026-07-20.md`(§3.10 / §7.9)、`docs/technical/【AGC】栏目画布底部工具栏入口矩阵-2026-09-13.md`、`docs/project-memory/plans/【里程碑】AGC音频生成进入后台任务账本-2026-09-20.md`。
- 验证:9 个定向 vitest 文件 73 项、`appSurface.test.ts` 552 项(17 跳过)、`cargo test asset_generation_task` 14 项、`npm run agc:typecheck`、`npm run check:encoding`、`npm run check:doc-index`、`git diff --check` 全部通过;未跑真实付费生成。
@@ -6,7 +6,7 @@
## 1. 一句话
功能画布 = 资源栏目页;栏目页左下角渲染一条由栏目 `category` 决定的工具栏,图片类入口走本地 `start_local_project_asset_generation`(提交即返回、后台生成),音频入口复用既有无源生成链路,上传复用 `upload_local_asset`;生成 / 上传成功后一律走既有 manifest 刷新与资源定位。
功能画布 = 资源栏目页;栏目页左下角渲染一条由栏目 `category` 决定的工具栏,图片类与音频入口都走本地 `start_local_project_asset_generation`(提交即返回、后台生成,见 2026-09-20 音频并入后台任务账本),上传复用 `upload_local_asset`;生成 / 上传成功后一律走既有 manifest 刷新与资源定位。
## 2. 入口矩阵(事实源)
@@ -40,13 +40,13 @@
| 生成规范 → 自定义规范 | 同上 | `kind: 'icon-spec'`,固定 `1:1 · 1K` |
| 生成图标素材 | 同上 | `kind: 'icon-spritesheet'`,默认 `1:1 · 1K`;前置:已登记 `assets/art-spec.png` |
| 生成 UI 设计图 | 同上 | `kind: 'ui-design'`,默认 `16:9 · 1K`;前置同上 |
| 生成背景音乐 | `derive_local_project_resource` | `editKind: 'background-music'`、`generationMode: 'create'`、`sourceMediaType: 'audio/mpeg'` |
| 生成音效 | `derive_local_project_resource` | `editKind: 'sound-effect'`、其余同上 |
| 生成背景音乐 | `start_local_project_asset_generation` | `kind: 'background-music'`、`idempotencyKey`;任务 id 即该次生成的 operation id |
| 生成音效 | `start_local_project_asset_generation` | `kind: 'sound-effect'`、其余同上 |
| 上传 | `upload_local_asset` | `{ projectPath, fileName, mediaType, bytes }` |
`start_local_project_asset_generation` 的完整参数是 `{ projectPath, projectId, taskId, kind, prompt, aspectRatio, imageSize, assetName, outputPath }`(Rust `src-tauri/src/asset_generation_tasks.rs`),**提交即返回**一条任务记录(`taskId / status / phaseDetail / assetId / error` 等);生成在 `tauri::async_runtime::spawn` 出来的后台任务里跑,账本落在项目内 `.agent/runtime/asset-generation-tasks/tasks.json`,进度由 `list_local_project_asset_generations` 读回。截图面板不再「等生成结束」,所以**点「生成」即同步关闭面板**(不等 IPC),面板内不出现阶段文案;只有「点击瞬间就失败」才带草稿重开(关闭 ≠ 取消)。
`start_local_project_asset_generation` 的完整参数是 `{ projectPath, projectId, taskId, kind, prompt, aspectRatio, imageSize, assetName, outputPath, idempotencyKey }`(Rust `src-tauri/src/asset_generation_tasks.rs`);图片类入口沿用 `{ projectPath, projectId, taskId, kind, prompt, aspectRatio, imageSize, assetName, outputPath }` 逐字不变,音频入口只带 `{ projectPath, projectId, taskId, kind, prompt, assetName, idempotencyKey }`(`idempotencyKey` = 该次生成的幂等键,任务 id 即 operation id;原生命令内部仍复用既有音频无源生成链路,不新增平台路由与请求体口径),**提交即返回**一条任务记录(`taskId / status / phaseDetail / assetId / error` 等);生成在 `tauri::async_runtime::spawn` 出来的后台任务里跑,账本落在项目内 `.agent/runtime/asset-generation-tasks/tasks.json`,进度由 `list_local_project_asset_generations` 读回。截图面板不再「等生成结束」,所以**点「生成」即同步关闭面板**(不等 IPC),面板内不出现阶段文案;只有「点击瞬间就失败」才带草稿重开(关闭 ≠ 取消)。
入参 `kind` 一律是共享 `GameCreationAppAssetKind` 的 canonical 成员(`image` / `character` / `icon-spec` / `icon-spritesheet` / `ui-design` / `publication-material`);`spec` / `art-spritesheet` / `ui-prototype` 这类平台请求词汇只由 Rust 侧派生到 `source.generationKind`,不再出现在 IPC 载荷或 manifest kind 里。
入参 `kind` 一律是共享 `GameCreationAppAssetKind` 的 canonical 成员(图片类 `image` / `character` / `icon-spec` / `icon-spritesheet` / `ui-design` / `publication-material`,音频 `sound-effect` / `background-music`);`spec` / `art-spritesheet` / `ui-prototype` 这类平台请求词汇只由 Rust 侧派生到 `source.generationKind`,不再出现在 IPC 载荷或 manifest kind 里。
## 4a. 本地排队与「生成任务」侧栏
@@ -74,6 +74,8 @@
- 音频画布的「生成背景音乐 / 生成音效」由工具栏承载:`ResourceCanvasGenerationPanelView` 新增 `kinds` prop,工具栏各自只放行自己那一种,单类型入口不再渲染类型选择器,面板标题与提交文案跟该类走。
- 既有「生成素材」浮层入口传 `kinds={['video']}`,只保留视频;视频能力不删,只是不出现在工具栏里。
- 音频入口与图片类入口共用同一份后台任务账本(2026-09-20):提交即返回任务记录、面板同步关闭、状态与阶段文案只由后端账本提供、任务出现在「生成任务」侧栏并在重开项目后恢复。音频任务的**请求身份**(operation id 与幂等键)随任务一起走:任务 id 即 operation id,重试复用同一对身份,不会变成第二次付费生成;音频面板与图片类面板一致,只有「点击瞬间就失败」(未受理)才带原草稿与原请求身份重开。
- 音频生成在客户端后台跑时仍复用既有音频无源生成链路(`generationMode: 'create'`、`editKind` = `sound-effect` / `background-music`、`sourceMediaType: 'audio/mpeg'`、平台路由与请求体口径不变);音频生成没有可播报的中间进度,因此阶段文案仍是账本的「排队中。」/「正在生成。」/「生成已完成。」/失败原因四档,不新增假阶段。
## 8. 验证
@@ -93,6 +95,7 @@ cargo test -p genarrative-ai-game-creator-shell asset_generation_task
- 模型层:四个栏目的工具集与顺序、未命中栏目返回空、「所有资源」与 `null` 返回空、二级菜单分流、比例 / 尺寸白名单收窄、前置判据、不可用原因、`outputPath` 策略。
- 组件层:工具栏渲染与二级菜单开合、不可用入口可点击 + 原因可关闭、上传回调。
- 生成任务层:`resourceCanvasAssetGenerationTaskModel`(状态机 / 在途判据 / 恢复 / 耗时文案)、`resourceCanvasAssetGenerationQueue`(第二条不发提交 IPC、前一条终态后自动补发、失败与账本丢失都能收口)、`ResourceCanvasAssetGenerationTasksPanelView`(非模态、阶段文案来自后端记录、按 `assetId` 定位)、两块生成浮层在提交期间可关闭、「后台运行并关闭」文案。
- 生成任务层:`resourceCanvasAssetGenerationTaskModel`(状态机 / 在途判据 / 恢复 / 耗时文案、音频任务载荷分流)、`resourceCanvasAssetGenerationQueue`(第二条不发提交 IPC、前一条终态后自动补发、失败与账本丢失都能收口、音频只发任务身份 + 幂等键)、`ResourceCanvasAssetGenerationTasksPanelView`(非模态、阶段文案来自后端记录、按 `assetId` 定位)、两块生成浮层点「生成」即同步关闭(面板 DOM 里没有阶段文案与「后台运行并关闭」这类在途按钮)。
- Rust 层:`asset_generation_tasks` 的账本落项目内、排队阶段文案由后端拥有、进程重启把无人推进的记录收口为中断失败、账本上限与 task id 边界。
- AppSurface 层:进入栏目出现工具栏 / 回总览与展开态消失、每个图片类入口的 `start_local_project_asset_generation` 载荷、前置缺失可点击说明且零请求、音频入口走 `derive_local_project_resource`、上传走 `upload_local_asset` + 配对读清单、生成面板关闭后任务仍在「生成任务」面板且第二条按本地排队补发、工具栏与右下 Dock 的几何契约。
- 音频后台化:音频 kind 的提交返回任务记录且账本 `kind` 为音频、提示词上限与幂等键在提交时收口(未知 kind / 非法身份在提交即拒绝)、第二条提交在本地排队期间不发 IPC、未受理失败重开面板并复用同一 operation 与幂等键、受理后失败的收口与落卡复用图片类同一链路。
- AppSurface 层:进入栏目出现工具栏 / 回总览与展开态消失、每个图片类入口的 `start_local_project_asset_generation` 载荷、前置缺失可点击说明且零请求、音频入口走同一条命令的音频载荷(`idempotencyKey` + 任务 id 即 operation id)、上传走 `upload_local_asset` + 配对读清单、生成面板关闭后任务仍在「生成任务」面板且第二条按本地排队补发、工具栏与右下 Dock 的几何契约。
@@ -57,7 +57,7 @@
| **S15** 删除 | 工具条 / 标签面板「删除」→ 确认弹窗 | 三分支:① 无引用→直接删;② 被引用未勾选→只删素材、版本保留**悬空绑定**、界面不合成幽灵资源卡;③ 勾选→素材与该批版本在**同一次 manifest 写入**内一起删 | L413(版本只追加的唯一例外)、L532–533;#309 C5 | 弹窗 `ariaLabel="确认删除资源"`;被引用时出现 `被 N 个游戏版本使用` + 版本列表 + checkbox `把相关游戏版本一并删除`;无引用时该 body 整块不渲染 | **只摘登记、不删磁盘文件**;读引用命令精确名是 `read_local_project_asset_references` |
| **S15a** 替换素材(含点选替换) | 选中被**当前版本**绑定的素材 → 工具条「替换素材」→ 候选弹窗(弹窗内可筛可选);再点 footer「点选替换」→ 弹窗关闭、进入画布点选态 → 在画布上直接点目标素材 | 弹窗确认与点选是**同一条**写入链路(`replace_local_project_version_resource`,载荷逐字一致):改该版本绑定、不建新版本;点选态下合法目标直接提交并自动退出点选态,非法目标零写入、**留在**点选态并在提示条上说明原因 | PRD §5.3 / §7.8 第 8 条;#309「直接替换」口径 | 点选态判据:候选弹窗 `role="dialog"` 已卸载;画布出现 `.game-resource-canvas-pick-hint`,文案含「在画布上点选要替换成的素材」与「点击空白处不会退出」,并有「取消」按钮;非法目标后提示条仍在且出现 `role="alert"`(「替换素材不兼容:分类不同」/「替换素材与源素材相同」/「替换素材未登记或已被删除」);点选期间卡片 `aria-pressed` 不变(单击只用于点选)、源素材选中与工具条不因点空白或点非法目标而丢;Esc 退出点选(画布全局 Esc 的清选中不随之触发);点选态下滚轮平移与缩放照常可用 | 点选只能点**当前画布上可见**的卡:目标在别的栏目时先切栏目(点选会话跨栏目存活,不因「收起资源」或切栏目结束);空白点击不退出、也不清画布选中 |
| **S11a** 栏目画布底部工具栏 | 进「UI 交互 / 角色与对象 / 场景与环境 / 音频」任一栏目 → 点左下角工具栏里的入口生成 → 「收起资源」回总览看工具栏消失 | 工具栏只在矩阵四个栏目(功能画布)渲染;图片类入口走 `start_local_project_asset_generation`(提交即返回、生成在后台跑),音频入口复用既有无源生成链路,上传复用 `upload_local_asset`;生成 / 上传成功后走既有 manifest 刷新与资源定位 | PRD §3.10、§7.9 | DOM 判据 `[data-resource-bottom-toolbar="<category>"]`(资源总览、「所有资源」展开态、文档、待归类、项目版本都**没有**这个节点);工具栏是 `.game-resource-book-manager` 的直接子节点(`closest('.game-resource-book-scene')` 为 `null`);每个入口一次 `start_local_project_asset_generation`,载荷逐字为 `{ projectPath, projectId, taskId, kind, prompt, aspectRatio, imageSize, assetName, outputPath }`(`kind` 映射见 PRD §7.9 第 3 条;`taskId` 是前端每次提交新铸的本地任务 id);该命令提交即返回,之后有 `list_local_project_asset_generations` 轮询与 `get_local_game_project_revision` + `get_local_game_manifest` 的配对读;提交期间点 × / 遮罩 / Esc /「后台运行并关闭」任一都能关面板且请求继续(画布立即恢复可交互),关闭后任务仍出现在「生成任务」面板(入口按钮 `aria-label="生成任务"`,非模态浮层、无 `aria-modal`)并显示后端 `phaseDetail`;第一条未终态时提交第二条 → 第二条显示「排队中。」且生成提交 IPC 次数仍为 1,第一条终态后自动补发(次数变 2);缺 `assets/art-spec.png` 时「生成图标素材 / 生成 UI 设计图」仍可点击(`aria-disabled="true"` 但**不是**原生 disabled)并给出含该路径的 `role="alert"` 原因、零生成请求;音频入口面板标题即「生成背景音乐」/「生成音效」且没有类型选择器 | ① 本地通道没有 `model` / `specType` / `replaceExisting` 入参:面板不渲染模型选择器,角色规范与自定义规范共用 `spec` 通道(靠 `assetName` 与提示词区分),「图标规范」在项目已有权威规范图时不再指向 `assets/art-spec.png`(否则会被 Rust 的防覆盖校验硬拒);② 本轮不做生成视频 / 宣发素材 / 生成游戏场景 / 选择工具 / 抓手工具;③ 既有「生成素材」浮层入口只保留生成视频,音频入口只在音频栏目工具栏出现 |
| **S11a** 栏目画布底部工具栏 | 进「UI 交互 / 角色与对象 / 场景与环境 / 音频」任一栏目 → 点左下角工具栏里的入口生成 → 「收起资源」回总览看工具栏消失 | 工具栏只在矩阵四个栏目(功能画布)渲染;图片类入口走 `start_local_project_asset_generation`(提交即返回、生成在后台跑),音频入口走同一条命令的音频载荷,上传复用 `upload_local_asset`;生成 / 上传成功后走既有 manifest 刷新与资源定位 | PRD §3.10、§7.9 | DOM 判据 `[data-resource-bottom-toolbar="<category>"]`(资源总览、「所有资源」展开态、文档、待归类、项目版本都**没有**这个节点);工具栏是 `.game-resource-book-manager` 的直接子节点(`closest('.game-resource-book-scene')` 为 `null`);每个入口一次 `start_local_project_asset_generation`:图片类载荷逐字为 `{ projectPath, projectId, taskId, kind, prompt, aspectRatio, imageSize, assetName, outputPath }`(`kind` 映射见 PRD §7.9 第 3 条;`taskId` 是前端每次提交新铸的本地任务 id),音频类载荷为 `{ projectPath, projectId, taskId, kind, prompt, assetName, idempotencyKey }`(`taskId` 即该次生成的 operation id,不发图片类那套比例 / 尺寸 / 参考 / 落点参数);该命令提交即返回,之后有 `list_local_project_asset_generations` 轮询与 `get_local_game_project_revision` + `get_local_game_manifest` 的配对读;点「生成」即把这次输入交给后台账本并**同步关闭**面板(不等 IPC、不等排队、不等生成,画布立即恢复可交互;面板 DOM 里没有阶段文案与「后台运行并关闭」这类在途按钮),关闭不等于取消,关闭后任务仍出现在「生成任务」面板(入口按钮 `aria-label="生成任务"`,非模态浮层、无 `aria-modal`)并显示后端 `phaseDetail`;第一条未终态时提交第二条 → 第二条显示「排队中。」且生成提交 IPC 次数仍为 1,第一条终态后自动补发(次数变 2);缺 `assets/art-spec.png` 时「生成图标素材 / 生成 UI 设计图」仍可点击(`aria-disabled="true"` 但**不是**原生 disabled)并给出含该路径的 `role="alert"` 原因、零生成请求;音频入口面板标题即「生成背景音乐」/「生成音效」且没有类型选择器 | ① 本地通道没有 `model` / `specType` / `replaceExisting` 入参:面板不渲染模型选择器,角色规范与自定义规范共用 `spec` 通道(靠 `assetName` 与提示词区分),「图标规范」在项目已有权威规范图时不再指向 `assets/art-spec.png`(否则会被 Rust 的防覆盖校验硬拒);② 本轮不做生成视频 / 宣发素材 / 生成游戏场景 / 选择工具 / 抓手工具;③ 既有「生成素材」浮层入口只保留生成视频,音频入口只在音频栏目工具栏出现 |
### D 阶段 · 版本与运行