dsh-game-material-master 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -106,7 +106,6 @@ window.__ModuleLoader__.load({
106
106
  "任务没有启动": "The task did not start",
107
107
  "正在挂载游戏素材大师…": "Mounting Game Material Master…",
108
108
  "游戏素材大师": "Game Material Master",
109
- "火山方舟 Seedream 生图 · MiniMax 图生视频 · 谱乐 AI 音乐 · 本地处理": "Volcengine Ark Seedream image gen · MiniMax image-to-video · Puyue AI music · local processing",
110
109
  "刷新列表": "Refresh list",
111
110
  "重命名": "Rename",
112
111
  "删除项目": "Delete project",
@@ -1762,6 +1761,72 @@ window.__ModuleLoader__.load({
1762
1761
  "交 Suno 会先把这一版的试听音频上传作为参考(标准上传免费),再生成 cover 正式版;比只发文字标签更贴近 MIDI。若 Suno 判定版权,需要你确认后走付费版权通道。": "Suno first uploads this version's preview audio as a reference (standard upload is free), then generates a cover; this stays much closer to the MIDI than text tags alone. If Suno flags copyright, you'll be asked to confirm the paid copyright channel.",
1763
1762
  "用这首音频生成 Suno 正式版(计费)": "Generate a Suno version from this audio (billed)",
1764
1763
  "Suno 正在生成…({n0})": "Suno is generating… ({n0})",
1764
+ // 音效生成(模块八)
1765
+ "音效生成": "Sound effects",
1766
+ "一句话描述 → 音效 / 环境音 / 角色配音(火山引擎 Seed-Audio)": "One prompt → sound effects / ambience / character voices (Volcengine Seed-Audio)",
1767
+ "火山方舟 Seedream 生图 · MiniMax 图生视频 · 谱乐 AI 音乐 · 火山引擎音效 · 本地处理": "Volcengine Ark Seedream image gen · MiniMax image-to-video · Puyue AI music · Volcengine sound effects · local processing",
1768
+ "提示词与参数已保存": "Prompt and settings saved",
1769
+ "先写点内容:要什么声音。": "Write something first: what should it sound like?",
1770
+ "已提交生成:每次生成都会真实计费,请等它跑完。": "Generation submitted: every run is billed; wait for it to finish.",
1771
+ "删除音效任务「{n0}」?所有生成与导出都会一起删掉。": "Delete sound effect job \"{n0}\"? All takes and exports will be removed.",
1772
+ "任务已删除": "Job deleted",
1773
+ "参考素材已上传": "Reference uploaded",
1774
+ "参考素材已删除": "Reference removed",
1775
+ "正在读取音效任务…": "Loading sound effect jobs…",
1776
+ "WAV(无损,游戏引擎常用)": "WAV (lossless, common in game engines)",
1777
+ "MP3(体积小)": "MP3 (smaller)",
1778
+ "Ogg Opus(体积更小)": "Ogg Opus (even smaller)",
1779
+ "新建音效": "New sound effect",
1780
+ "把它当配音导演脚本写:声源 + 环境 + 强度/节奏 + 大致时长。单次最长 120 秒。": "Write it like a dubbing director's script: source + environment + intensity/rhythm + approximate duration. Up to 120 seconds per run.",
1781
+ "名字(可留空,按提示词自动取)": "Name (optional; derived from the prompt)",
1782
+ "例如:暴雨中的金属撞击,短促有力,约 1 秒,带一点尾音": "e.g. metal impact in heavy rain, short and forceful, about 1 second, with a slight tail",
1783
+ "输出格式": "Output format",
1784
+ "采样率": "Sample rate",
1785
+ "自动审核(生成后自己核对继续)": "Auto review (verify and continue)",
1786
+ "每一步人工审核(生成后停下等你确认)": "Manual review at every step (stop after generation)",
1787
+ "正在创建…": "Creating…",
1788
+ "创建音效任务": "Create sound effect job",
1789
+ "创建不会调用模型;点「生成」才会真实计费。": "Creating does not call the model; only Generate is billed.",
1790
+ "左侧选一个音效任务,或点「新建音效」开始。": "Pick a sound effect job on the left, or click New sound effect to start.",
1791
+ "还没生成": "Not generated yet",
1792
+ "{n0} 条生成 · 上限 120 秒": "{n0} takes · max 120 seconds",
1793
+ "提示词({n0}/2048)": "Prompt ({n0}/2048)",
1794
+ "语速(-50~100)": "Speech rate (-50 to 100)",
1795
+ "音量(-50~100)": "Loudness (-50 to 100)",
1796
+ "音调(-12~12)": "Pitch (-12 to 12)",
1797
+ "加 AIGC 节奏水印(默认关)": "Add AIGC rhythm watermark (off by default)",
1798
+ "生成(计费)": "Generate (billed)",
1799
+ "再生成一条(计费)": "Generate another take (billed)",
1800
+ "正在保存…": "Saving…",
1801
+ "保存提示词与参数": "Save prompt and settings",
1802
+ "每次生成都会真实计费;失败不会自动重试。参考图最多 1 张,参考音频最多 3 条,两者不能同时用。": "Every generation is billed; failures are not retried automatically. At most 1 reference image or 3 reference audio clips, never both.",
1803
+ "参考素材(可选)": "References (optional)",
1804
+ "上传中…": "Uploading…",
1805
+ "上传参考图": "Upload reference image",
1806
+ "上传参考音频": "Upload reference audio",
1807
+ "删除参考图": "Remove reference image",
1808
+ "参考音频 {n0}:{n1}": "Reference audio {n0}: {n1}",
1809
+ "参考图与参考音频不能同时使用;单文件上限 10MB,参考音频每条最长 30 秒。": "Reference image and audio cannot be mixed; each file is at most 10MB and each audio clip at most 30 seconds.",
1810
+ "生成结果({n0} 条)": "Results ({n0} takes)",
1811
+ "正在生成音效…": "Generating sound effect…",
1812
+ "还没有生成。点上面的「生成(计费)」。": "Nothing generated yet. Click Generate (billed) above.",
1813
+ "计费 {n0} 秒": "billed {n0}s",
1814
+ "生成时用的提示词": "Prompt used for this take",
1815
+ "打包中…": "Packing…",
1816
+ "全部打包导出(zip)": "Export all as ZIP",
1817
+ "通过本条音效": "Approve this sound effect",
1818
+ "音效任务({n0})": "Sound effect jobs ({n0})",
1819
+ "还没有任务。写一句「要什么声音」开始。": "No jobs yet. Start by describing the sound you want.",
1820
+ "音效生成(火山引擎 Seed-Audio)": "Sound effects (Volcengine Seed-Audio)",
1821
+ "用豆包语音的生成式音频模型做游戏音效:撞击 / 环境音 / UI 声 / 生物吼叫 / 角色配音。单次最长 120 秒。Key 是语音控制台的 API Key(请求头 X-Api-Key),不是火山方舟的 ARK_API_KEY;模型需要在语音控制台开通。": "Generate game sound effects with Doubao Speech's generative audio model: impacts / ambience / UI sounds / creature roars / character voices. Up to 120 seconds per run. The key is the speech console API key (header X-Api-Key), not the Ark ARK_API_KEY; the model must be enabled in the speech console.",
1822
+ "粘贴语音控制台 API Key": "Paste the speech console API key",
1823
+ "音效 API Key 已保存": "Sound effect API key saved",
1824
+ "已清除音效 API Key": "Sound effect API key cleared",
1825
+ "正在生成测试音效…": "Generating a test sound effect…",
1826
+ "测试连接(会真实生成一条极短音效,产生少量费用)": "Test connection (generates one very short sound effect; small charge)",
1827
+ "默认模型": "Default model",
1828
+ "默认输出格式": "Default output format",
1829
+ "默认采样率": "Default sample rate",
1765
1830
  };
1766
1831
  /* i18n-ignore-end */
1767
1832
  /**
@@ -2496,7 +2561,21 @@ window.__ModuleLoader__.load({
2496
2561
  ["renderMusicEdit", true],
2497
2562
  ["saveMusicVersion", true],
2498
2563
  ["deleteMusicVersion", true],
2499
- ["exportMusic", true]
2564
+ ["exportMusic", true],
2565
+ // 音效生成(模块八)。
2566
+ ["testSfx", false],
2567
+ ["listSfxJobs", false],
2568
+ ["createSfxJob", true],
2569
+ ["getSfxJob", true],
2570
+ ["saveSfxJob", true],
2571
+ ["deleteSfxJob", true],
2572
+ ["uploadSfxRef", true],
2573
+ ["removeSfxRef", true],
2574
+ ["runSfxGeneration", true],
2575
+ ["cancelSfxGeneration", true],
2576
+ ["setSfxApproved", true],
2577
+ ["revealSfxJob", true],
2578
+ ["exportSfx", true]
2500
2579
  ];
2501
2580
  const CONTRIBUTION = {
2502
2581
  package: PACKAGE,
@@ -2624,7 +2703,8 @@ window.__ModuleLoader__.load({
2624
2703
  { key: "rig", title: T("骨骼动画生成"), hint: T("拆件 → 装配定位 → 推骨骼与动画 → 打包 Spine 图集"), experimental: true },
2625
2704
  { key: "tile", title: T("45°地图地块生成"), hint: T("45° 等距地块 → 拼成地图:几何交给代码,内容交给 AI"), experimental: true },
2626
2705
  { key: "map", title: T("地图编辑器"), hint: T("导入自己的素材图 → 自动连接 → 直接画 → 导出 PNG") },
2627
- { key: "music", title: T("音乐生成编辑"), hint: T("灵感/歌词 → 对话里生成 → 回界面裁剪、调音量、淡入淡出与导出") }
2706
+ { key: "music", title: T("音乐生成编辑"), hint: T("灵感/歌词 → 对话里生成 → 回界面裁剪、调音量、淡入淡出与导出") },
2707
+ { key: "sfx", title: T("音效生成"), hint: T("一句话描述 → 音效 / 环境音 / 角色配音(火山引擎 Seed-Audio)") }
2628
2708
  ];
2629
2709
  }
2630
2710
  let MODULES = make_MODULES();
@@ -2784,7 +2864,7 @@ window.__ModuleLoader__.load({
2784
2864
  // http(s) 链接加 target="_blank",不拦就会真的新开一个标签页。
2785
2865
  // 只按 `dsh-gmm` 参数识别自己的链接,其它链接(含站外的)一律放行。
2786
2866
  const OPEN_QUERY_KEY = "dsh-gmm";
2787
- const OPEN_MODULES = new Set(["sprite", "image", "sequence", "rig", "tile", "map", "music"]);
2867
+ const OPEN_MODULES = new Set(["sprite", "image", "sequence", "rig", "tile", "map", "music", "sfx"]);
2788
2868
  /** `dialog` 允许的取值(宿主 `links.ts` 的 `OPEN_DIALOGS`,改一处要同步)。 */
2789
2869
  const OPEN_DIALOGS = new Set(["add"]);
2790
2870
  /** `shape` 允许的取值(宿主 `links.ts` 的 `OPEN_SHAPES`,改一处要同步)。 */
@@ -3690,6 +3770,45 @@ window.__ModuleLoader__.load({
3690
3770
  return error.message;
3691
3771
  return String(error);
3692
3772
  }
3773
+ /** 两个草稿值是否相同:草稿都是宿主回包里的纯 JSON,对象按序列化结果比。 */
3774
+ function sameDraft(a, b) {
3775
+ if (a === b)
3776
+ return true;
3777
+ if (a === undefined || b === undefined || a === null || b === null)
3778
+ return false;
3779
+ if (typeof a !== "object" || typeof b !== "object")
3780
+ return false;
3781
+ return JSON.stringify(a) === JSON.stringify(b);
3782
+ }
3783
+ /**
3784
+ * 把「界面草稿」和「宿主刚拉回来的值」合起来,**只更新用户没动过的字段**。
3785
+ *
3786
+ * 为什么需要:有任务在跑时界面会轮询(模块①每 2.5 秒、视频阶段固定每 5 秒;
3787
+ * 模块②③④ 每 2.5~5 秒),每次都调一次 `load()` / `loadProject()`。之前它们
3788
+ * 无条件拿宿主的值整份覆盖草稿 —— 用户正在长文本框里替换提示词时,刚打进去的
3789
+ * 内容会在一两秒内被打回原形(真机反馈:「这个提示词是无法替换的呀,我替换的
3790
+ * 时候它一秒钟又换回来」)。
3791
+ *
3792
+ * 判定标准:草稿 === 上一次从宿主读到的值 ⇒ 没改过,跟着宿主走(切语言、
3793
+ * 重置为默认、别处改了这一条都能同步);不相等 ⇒ 用户改过,留着,直到他自己
3794
+ * 保存或点「重置为默认」。
3795
+ *
3796
+ * @param force - 换项目 / 换任务 / 明确要重置时传 true:整份换成宿主的值。
3797
+ */
3798
+ function mergeDrafts(current, previous, next, force) {
3799
+ if (force === true)
3800
+ return next;
3801
+ if (next === null || typeof next !== "object") {
3802
+ // 标量(提示词这种一整段文本):没改过才跟着宿主走。
3803
+ return current === undefined || current === previous ? next : current;
3804
+ }
3805
+ const merged = {};
3806
+ for (const key of Object.keys(next)) {
3807
+ const drafted = current !== null && typeof current === "object" ? current[key] : undefined;
3808
+ merged[key] = drafted === undefined || sameDraft(drafted, previous?.[key]) ? next[key] : drafted;
3809
+ }
3810
+ return merged;
3811
+ }
3693
3812
  /**
3694
3813
  * 新建项目 / 任务时问一个名字(与「重命名」同一套 `window.prompt` 交互)。
3695
3814
  *
@@ -4396,6 +4515,14 @@ window.__ModuleLoader__.load({
4396
4515
  const intent = useStudioIntent();
4397
4516
  // 功能管理:被隐藏的模块既不在页签里,也不该在别处被切进来(深链接也会被挡)。
4398
4517
  const hidden = useHiddenModules(api);
4518
+ /**
4519
+ * 上一次从宿主读到的提示词(连同项目 id)。
4520
+ *
4521
+ * 后台轮询(有任务在跑时 2.5 秒一次、视频阶段固定 5 秒一次)会反复拉项目,
4522
+ * 用它判断界面上的草稿有没有被用户改过,别再拿宿主的值把正在输入的内容覆盖掉
4523
+ * (真机反馈:「我替换的时候它一秒钟又换回来」)。判定规则见 `mergeDrafts`。
4524
+ */
4525
+ const loadedPrompts = React.useRef({ projectId: null, images: {}, video: "" });
4399
4526
  const visibleModules = visibleModulesOf(hidden);
4400
4527
  /**
4401
4528
  * 真正渲染的模块:当前选中项被隐藏(或压根不存在)时落到第一个可见模块。
@@ -4439,14 +4566,20 @@ window.__ModuleLoader__.load({
4439
4566
  return [];
4440
4567
  }
4441
4568
  }, [api]);
4442
- const loadProject = React.useCallback(async (id) => {
4569
+ const loadProject = React.useCallback(async (id, options = {}) => {
4443
4570
  if (api === undefined || id === null)
4444
4571
  return;
4445
4572
  try {
4446
4573
  const next = await api.getProject(id);
4574
+ const previous = loadedPrompts.current;
4575
+ // 换项目、或用户明确点了「重置为默认」:草稿整份换成宿主的。
4576
+ const force = options.resetDrafts === true || previous.projectId !== id;
4577
+ const images = { ...(next.prompts?.images ?? {}) };
4578
+ const video = next.prompts?.video ?? "";
4579
+ loadedPrompts.current = { projectId: id, images, video };
4447
4580
  setProject(next);
4448
- setPromptDraft({ ...(next.prompts?.images ?? {}) });
4449
- setVideoPromptDraft(next.prompts?.video ?? "");
4581
+ setPromptDraft((current) => mergeDrafts(current, previous.images, images, force));
4582
+ setVideoPromptDraft((current) => mergeDrafts(current, previous.video, video, force));
4450
4583
  setSettingsDraft({ ...(next.settings ?? {}) });
4451
4584
  setPromptOpen((current) => {
4452
4585
  const keys = Object.keys(current);
@@ -4511,7 +4644,7 @@ window.__ModuleLoader__.load({
4511
4644
  if (options.notice !== undefined)
4512
4645
  setNotice({ kind: options.noticeKind ?? "info", text: options.notice });
4513
4646
  if (options.reload === true && projectId !== null)
4514
- await loadProject(projectId);
4647
+ await loadProject(projectId, { resetDrafts: options.resetDrafts === true });
4515
4648
  return value;
4516
4649
  }
4517
4650
  catch (error) {
@@ -4638,7 +4771,7 @@ window.__ModuleLoader__.load({
4638
4771
  }
4639
4772
  const activeStageIndex = STAGES.findIndex((s) => s.key === stage);
4640
4773
  const activeStage = STAGES[activeStageIndex < 0 ? 0 : activeStageIndex];
4641
- return h("div", { className: "SPR_root" }, h("div", { className: "SPR_head" }, h("h2", null, T("游戏素材大师")), h("span", { className: "SPR_headSub" }, T("火山方舟 Seedream 生图 · MiniMax 图生视频 · 谱乐 AI 音乐 · 本地处理")), h("span", { className: "SPR_spacer" }), activeModule === "sprite"
4774
+ return h("div", { className: "SPR_root" }, h("div", { className: "SPR_head" }, h("h2", null, T("游戏素材大师")), h("span", { className: "SPR_headSub" }, T("火山方舟 Seedream 生图 · MiniMax 图生视频 · 谱乐 AI 音乐 · 火山引擎音效 · 本地处理")), h("span", { className: "SPR_spacer" }), activeModule === "sprite"
4642
4775
  ? h(React.Fragment, null, h(Btn, { onClick: () => void refreshProjects(), disabled: loading }, T("刷新列表")), project !== null ? h(Btn, { onClick: renameCurrent }, T("重命名")) : null, project !== null ? h(Btn, { onClick: deleteCurrent, danger: true }, T("删除项目")) : null, h(Btn, { onClick: createProject, primary: true }, T("新建项目")))
4643
4776
  : null), h("div", { className: "SPR_modules", "data-hidden-count": String(hidden.length) }, visibleModules.map((entry) => h("button", {
4644
4777
  key: entry.key,
@@ -4773,9 +4906,11 @@ window.__ModuleLoader__.load({
4773
4906
  ? h(MapModule, { api, studioCtx: props.studioCtx })
4774
4907
  : activeModule === "music"
4775
4908
  ? h(MusicModule, { api, studioCtx: props.studioCtx })
4776
- : activeModule === "rig"
4777
- ? h(RigModule, { api })
4778
- : null);
4909
+ : activeModule === "sfx"
4910
+ ? h(SfxModule, { api })
4911
+ : activeModule === "rig"
4912
+ ? h(RigModule, { api })
4913
+ : null);
4779
4914
  }
4780
4915
  /** 阶段卡片下方的说明文字(阶段①有两种生成方式,各说各的)。 */
4781
4916
  function stageHint(project, stage, activeStage) {
@@ -5192,7 +5327,7 @@ window.__ModuleLoader__.load({
5192
5327
  onClick: () => {
5193
5328
  if (typeof window !== "undefined" && !window.confirm(T("把八个方向的生图提示词和视频提示词都重置为当前默认模板?你手改过的内容会丢失。")))
5194
5329
  return;
5195
- void start(() => api.savePrompts({ projectId: project.id, resetImagesToDefault: true, resetVideoToDefault: true }), { reload: true, notice: T("提示词已重置为默认模板"), noticeKind: "ok" }, { key: KEY_PROMPT_RESET, label: T("正在重置提示词…") });
5330
+ void start(() => api.savePrompts({ projectId: project.id, resetImagesToDefault: true, resetVideoToDefault: true }), { reload: true, resetDrafts: true, notice: T("提示词已重置为默认模板"), noticeKind: "ok" }, { key: KEY_PROMPT_RESET, label: T("正在重置提示词…") });
5196
5331
  }
5197
5332
  }, T("重置提示词为默认")), h(BusyBadge, { show: batchBusy, text: batchLabel }), project.source === null ? h("span", { className: "SPR_refRow" }, T("请先上传源图")) : null), h("div", { className: "SPR_grid" }, DIRECTIONS.map((direction) => {
5198
5333
  const node = project.images?.[direction.key];
@@ -10394,6 +10529,361 @@ window.__ModuleLoader__.load({
10394
10529
  ? T("谱曲 {n0} 版 · {n1}/{n2} 首", { n0: entry.compositions ?? 0, n1: entry.songsReady, n2: entry.songsTotal })
10395
10530
  : T("{n0}/{n1} 首 · {n2} 个版本", { n0: entry.songsReady, n1: entry.songsTotal, n2: entry.versions }))))), main);
10396
10531
  }
10532
+ // ── 模块八:音效生成(火山引擎 Seed-Audio)────────────────────────────
10533
+ //
10534
+ // 与音乐模块不同:这里不派给对话,界面上直接「生成」→ 后台任务 → 轮询。
10535
+ // 每次生成新增一条 take(永不覆盖),旧 take 保留;失败不自动重试。
10536
+ function sfxFmtBytes(bytes) {
10537
+ const value = Number(bytes) || 0;
10538
+ if (value >= 1024 * 1024)
10539
+ return `${(value / 1024 / 1024).toFixed(1)} MB`;
10540
+ if (value >= 1024)
10541
+ return `${(value / 1024).toFixed(0)} KB`;
10542
+ return `${value} B`;
10543
+ }
10544
+ function sfxSettingsOf(job) {
10545
+ const settings = job?.settings ?? {};
10546
+ return {
10547
+ format: settings.format ?? "wav",
10548
+ sampleRate: Number(settings.sampleRate) || 24000,
10549
+ speechRate: Number(settings.speechRate) || 0,
10550
+ loudnessRate: Number(settings.loudnessRate) || 0,
10551
+ pitchRate: Number(settings.pitchRate) || 0,
10552
+ watermark: settings.watermark === true
10553
+ };
10554
+ }
10555
+ /** 格式名由客户端翻,不用宿主回传的中文 label(切英文会露中文)。 */
10556
+ function sfxFormatLabel(id) {
10557
+ if (id === "mp3")
10558
+ return T("MP3(体积小)");
10559
+ if (id === "ogg_opus")
10560
+ return T("Ogg Opus(体积更小)");
10561
+ return T("WAV(无损,游戏引擎常用)");
10562
+ }
10563
+ function SfxModule(props) {
10564
+ useLocaleTick();
10565
+ const api = props.api;
10566
+ const intent = useStudioIntent();
10567
+ const [config, setConfig] = React.useState(null);
10568
+ const [jobs, setJobs] = React.useState([]);
10569
+ const [jobId, setJobId] = React.useState(null);
10570
+ const [job, setJob] = React.useState(null);
10571
+ const [notice, setNotice] = React.useState(null);
10572
+ const [loading, setLoading] = React.useState(true);
10573
+ const [createOpen, setCreateOpen] = React.useState(false);
10574
+ const [draft, setDraft] = React.useState({ name: "", prompt: "", format: "wav", sampleRate: 24000 });
10575
+ const [reviewMode, setReviewMode] = React.useState("auto");
10576
+ const [creating, setCreating] = React.useState(false);
10577
+ const [promptDraft, setPromptDraft] = React.useState("");
10578
+ const [settingsDraft, setSettingsDraft] = React.useState(sfxSettingsOf(null));
10579
+ const [saving, setSaving] = React.useState(false);
10580
+ const [generating, setGenerating] = React.useState(false);
10581
+ const [exporting, setExporting] = React.useState(null);
10582
+ const [exportResult, setExportResult] = React.useState(null);
10583
+ const [refBusy, setRefBusy] = React.useState(false);
10584
+ const imageInputRef = React.useRef(null);
10585
+ const audioInputRef = React.useRef(null);
10586
+ const seq = React.useRef(0);
10587
+ const loadedDraft = React.useRef({ jobId: null, prompt: "", settings: null });
10588
+ const loadConfig = React.useCallback(async () => {
10589
+ if (api === undefined)
10590
+ return;
10591
+ try {
10592
+ setConfig(await api.getConfig());
10593
+ }
10594
+ catch {
10595
+ // 配置读不到不影响任务浏览;提交时会再检查。
10596
+ }
10597
+ }, [api]);
10598
+ const loadJobs = React.useCallback(async () => {
10599
+ if (api === undefined)
10600
+ return [];
10601
+ try {
10602
+ const result = await api.listSfxJobs();
10603
+ const list = result?.jobs ?? [];
10604
+ setJobs(list);
10605
+ return list;
10606
+ }
10607
+ catch (error) {
10608
+ setNotice({ kind: "error", text: msg(error) });
10609
+ return [];
10610
+ }
10611
+ }, [api]);
10612
+ const loadJob = React.useCallback(async (id) => {
10613
+ if (api === undefined || typeof id !== "string" || id === "")
10614
+ return undefined;
10615
+ const ticket = ++seq.current;
10616
+ try {
10617
+ const next = await api.getSfxJob({ jobId: id });
10618
+ if (ticket !== seq.current)
10619
+ return undefined;
10620
+ setJob(next);
10621
+ setJobId(id);
10622
+ const force = loadedDraft.current.jobId !== next.id;
10623
+ const nextPrompt = typeof next.prompt === "string" ? next.prompt : "";
10624
+ const nextSettings = sfxSettingsOf(next);
10625
+ setPromptDraft((current) => mergeDrafts(current, loadedDraft.current.prompt, nextPrompt, force));
10626
+ setSettingsDraft((current) => mergeDrafts(current, loadedDraft.current.settings, nextSettings, force));
10627
+ loadedDraft.current = { jobId: next.id, prompt: nextPrompt, settings: nextSettings };
10628
+ return next;
10629
+ }
10630
+ catch (error) {
10631
+ if (ticket === seq.current)
10632
+ setNotice({ kind: "error", text: msg(error) });
10633
+ return undefined;
10634
+ }
10635
+ }, [api]);
10636
+ React.useEffect(() => {
10637
+ void (async () => {
10638
+ await Promise.all([loadConfig(), loadJobs()]);
10639
+ setLoading(false);
10640
+ })();
10641
+ }, [loadConfig, loadJobs]);
10642
+ // 深链接:module=sfx&job=f…;没有 job 就落到第一个任务或打开新建。
10643
+ React.useEffect(() => {
10644
+ if (intent === null || intent.module !== "sfx")
10645
+ return;
10646
+ const target = typeof intent.jobId === "string" && intent.jobId !== "" ? intent.jobId : intent.projectId;
10647
+ void (async () => {
10648
+ if (typeof target === "string" && target !== "") {
10649
+ await loadJob(target);
10650
+ setCreateOpen(false);
10651
+ }
10652
+ else {
10653
+ const list = await loadJobs();
10654
+ if (list.length > 0)
10655
+ await loadJob(list[0].id);
10656
+ else
10657
+ setCreateOpen(true);
10658
+ }
10659
+ })();
10660
+ // eslint-disable-next-line react-hooks/exhaustive-deps
10661
+ }, [intent]);
10662
+ // 有任务在跑时轮询;用 setInterval(不要依赖 updatedAt,见音乐模块的踩坑)。
10663
+ React.useEffect(() => {
10664
+ if (job?.busy !== true || jobId === null)
10665
+ return undefined;
10666
+ const timer = window.setInterval(() => {
10667
+ void loadJob(jobId);
10668
+ }, 2500);
10669
+ return () => window.clearInterval(timer);
10670
+ }, [job?.busy, jobId, loadJob]);
10671
+ const saveJob = async () => {
10672
+ if (api === undefined || jobId === null)
10673
+ return undefined;
10674
+ setSaving(true);
10675
+ try {
10676
+ const saved = await api.saveSfxJob({ jobId, prompt: promptDraft, settings: settingsDraft });
10677
+ setJob(saved);
10678
+ const nextPrompt = typeof saved.prompt === "string" ? saved.prompt : promptDraft;
10679
+ const nextSettings = sfxSettingsOf(saved);
10680
+ loadedDraft.current = { jobId, prompt: nextPrompt, settings: nextSettings };
10681
+ setPromptDraft(nextPrompt);
10682
+ setSettingsDraft(nextSettings);
10683
+ setNotice({ kind: "ok", text: T("提示词与参数已保存") });
10684
+ return saved;
10685
+ }
10686
+ catch (error) {
10687
+ setNotice({ kind: "error", text: msg(error) });
10688
+ return undefined;
10689
+ }
10690
+ finally {
10691
+ setSaving(false);
10692
+ }
10693
+ };
10694
+ const generate = async () => {
10695
+ if (api === undefined || jobId === null)
10696
+ return;
10697
+ if (promptDraft.trim() === "") {
10698
+ setNotice({ kind: "error", text: T("先写点内容:要什么声音。") });
10699
+ return;
10700
+ }
10701
+ setGenerating(true);
10702
+ try {
10703
+ await api.saveSfxJob({ jobId, prompt: promptDraft, settings: settingsDraft });
10704
+ const result = await api.runSfxGeneration({ jobId });
10705
+ if (result?.started !== true) {
10706
+ setNotice({ kind: "error", text: result?.reason ?? T("提交没有启动") });
10707
+ }
10708
+ else {
10709
+ setNotice({ kind: "ok", text: T("已提交生成:每次生成都会真实计费,请等它跑完。") });
10710
+ }
10711
+ await loadJob(jobId);
10712
+ await loadJobs();
10713
+ }
10714
+ catch (error) {
10715
+ setNotice({ kind: "error", text: msg(error) });
10716
+ }
10717
+ finally {
10718
+ setGenerating(false);
10719
+ }
10720
+ };
10721
+ const createJob = async () => {
10722
+ if (api === undefined)
10723
+ return;
10724
+ if (draft.prompt.trim() === "") {
10725
+ setNotice({ kind: "error", text: T("先写点内容:要什么声音。") });
10726
+ return;
10727
+ }
10728
+ setCreating(true);
10729
+ try {
10730
+ const created = await api.createSfxJob({
10731
+ name: draft.name.trim() === "" ? undefined : draft.name,
10732
+ prompt: draft.prompt,
10733
+ settings: { format: draft.format, sampleRate: draft.sampleRate },
10734
+ reviewMode
10735
+ });
10736
+ setJob(created);
10737
+ setJobId(created.id);
10738
+ setCreateOpen(false);
10739
+ setPromptDraft(created.prompt ?? draft.prompt);
10740
+ setSettingsDraft(sfxSettingsOf(created));
10741
+ loadedDraft.current = { jobId: created.id, prompt: created.prompt ?? draft.prompt, settings: sfxSettingsOf(created) };
10742
+ setDraft({ name: "", prompt: "", format: config?.sfxFormat ?? "wav", sampleRate: config?.sfxSampleRate ?? 24000 });
10743
+ await loadJobs();
10744
+ }
10745
+ catch (error) {
10746
+ setNotice({ kind: "error", text: msg(error) });
10747
+ }
10748
+ finally {
10749
+ setCreating(false);
10750
+ }
10751
+ };
10752
+ const removeJob = async () => {
10753
+ if (api === undefined || jobId === null)
10754
+ return;
10755
+ if (!window.confirm(T("删除音效任务「{n0}」?所有生成与导出都会一起删掉。", { n0: job?.name ?? jobId })))
10756
+ return;
10757
+ try {
10758
+ await api.deleteSfxJob({ jobId });
10759
+ setJob(null);
10760
+ setJobId(null);
10761
+ setNotice({ kind: "ok", text: T("任务已删除") });
10762
+ await loadJobs();
10763
+ }
10764
+ catch (error) {
10765
+ setNotice({ kind: "error", text: msg(error) });
10766
+ }
10767
+ };
10768
+ const exportTake = async (takeId, zip) => {
10769
+ if (api === undefined || jobId === null)
10770
+ return;
10771
+ setExporting(zip === true ? "zip" : takeId);
10772
+ try {
10773
+ const result = await api.exportSfx(zip === true ? { jobId, zip: true } : { jobId, takeId });
10774
+ setExportResult(result);
10775
+ setNotice({ kind: "ok", text: T("已导出:{n0}", { n0: result.path ?? result.file ?? "" }) });
10776
+ await loadJob(jobId);
10777
+ }
10778
+ catch (error) {
10779
+ setNotice({ kind: "error", text: msg(error) });
10780
+ }
10781
+ finally {
10782
+ setExporting(null);
10783
+ }
10784
+ };
10785
+ const uploadRef = (kind) => async (event) => {
10786
+ if (api === undefined || jobId === null)
10787
+ return;
10788
+ const file = event?.target?.files?.[0];
10789
+ event.target.value = "";
10790
+ if (file === undefined)
10791
+ return;
10792
+ setRefBusy(true);
10793
+ try {
10794
+ const base64 = await new Promise((resolve, reject) => {
10795
+ const reader = new FileReader();
10796
+ reader.onload = () => resolve(String(reader.result ?? "").split(",")[1] ?? "");
10797
+ reader.onerror = () => reject(new Error(T("读取文件失败")));
10798
+ reader.readAsDataURL(file);
10799
+ });
10800
+ const next = await api.uploadSfxRef({ jobId, kind, name: file.name, data: base64 });
10801
+ setJob(next);
10802
+ setNotice({ kind: "ok", text: T("参考素材已上传") });
10803
+ }
10804
+ catch (error) {
10805
+ setNotice({ kind: "error", text: msg(error) });
10806
+ }
10807
+ finally {
10808
+ setRefBusy(false);
10809
+ }
10810
+ };
10811
+ const removeRef = async (kind, file = undefined) => {
10812
+ if (api === undefined || jobId === null)
10813
+ return;
10814
+ setRefBusy(true);
10815
+ try {
10816
+ const next = await api.removeSfxRef({ jobId, kind, ...(file === undefined ? {} : { file }) });
10817
+ setJob(next);
10818
+ setNotice({ kind: "ok", text: T("参考素材已删除") });
10819
+ }
10820
+ catch (error) {
10821
+ setNotice({ kind: "error", text: msg(error) });
10822
+ }
10823
+ finally {
10824
+ setRefBusy(false);
10825
+ }
10826
+ };
10827
+ const approve = async (approved) => {
10828
+ if (api === undefined || jobId === null)
10829
+ return;
10830
+ try {
10831
+ const next = await api.setSfxApproved({ jobId, stage: "generate", approved });
10832
+ setJob(next);
10833
+ setNotice({ kind: "ok", text: approved ? T("已标记通过") : T("已取消通过") });
10834
+ }
10835
+ catch (error) {
10836
+ setNotice({ kind: "error", text: msg(error) });
10837
+ }
10838
+ };
10839
+ if (loading)
10840
+ return h("div", { className: "SPR_body" }, h("p", { className: "SPR_empty" }, T("正在读取音效任务…")));
10841
+ if (api === undefined)
10842
+ return h("div", { className: "SPR_body" }, h("p", { className: "SPR_empty" }, T("正在挂载游戏素材大师…")));
10843
+ const formats = (config?.sfxFormats ?? [{ id: "wav" }, { id: "mp3" }, { id: "ogg_opus" }]).map((format) => ({ id: format.id, label: sfxFormatLabel(format.id) }));
10844
+ const sampleRates = config?.sfxSampleRates ?? [16000, 24000, 44100, 48000];
10845
+ const takes = job?.takes ?? [];
10846
+ const refs = job?.refs ?? { image: null, audios: [] };
10847
+ const blocker = job?.blocker ?? config?.sfxBlocker ?? null;
10848
+ const createCard = createOpen
10849
+ ? h("section", { className: "SPR_musicCard", "data-testid": "sfx-create" }, h("h3", null, T("新建音效")), h("p", { className: "SPR_hint" }, T("把它当配音导演脚本写:声源 + 环境 + 强度/节奏 + 大致时长。单次最长 120 秒。")), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("名字(可留空,按提示词自动取)")), h("input", { className: "SPR_input", value: draft.name, onChange: (event) => setDraft({ ...draft, name: event.target.value }) })), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("提示词")), h("textarea", {
10850
+ className: "SPR_musicText",
10851
+ "data-testid": "sfx-create-prompt",
10852
+ rows: 3,
10853
+ maxLength: 2048,
10854
+ value: draft.prompt,
10855
+ placeholder: T("例如:暴雨中的金属撞击,短促有力,约 1 秒,带一点尾音"),
10856
+ onChange: (event) => setDraft({ ...draft, prompt: event.target.value })
10857
+ })), h("div", { className: "SPR_musicGrid2" }, h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("输出格式")), h("select", { className: "SPR_input", value: draft.format, onChange: (event) => setDraft({ ...draft, format: event.target.value }) }, formats.map((format) => h("option", { key: format.id, value: format.id }, format.label)))), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("采样率")), h("select", { className: "SPR_input", value: String(draft.sampleRate), onChange: (event) => setDraft({ ...draft, sampleRate: Number(event.target.value) }) }, sampleRates.map((rate) => h("option", { key: String(rate), value: String(rate) }, `${rate} Hz`))))), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("审核模式")), h("select", { className: "SPR_input", value: reviewMode, onChange: (event) => setReviewMode(event.target.value) }, h("option", { value: "auto" }, T("自动审核(生成后自己核对继续)")), h("option", { value: "manual" }, T("每一步人工审核(生成后停下等你确认)")))), h("div", { className: "SPR_toolbar" }, h(BusyBtn, { busy: creating, busyText: T("正在创建…"), primary: true, "data-testid": "sfx-create-submit", onClick: () => void createJob() }, T("创建音效任务")), h(Btn, { onClick: () => setCreateOpen(false) }, T("取消"))), h("p", { className: "SPR_hint" }, T("创建不会调用模型;点「生成」才会真实计费。")))
10858
+ : null;
10859
+ const main = h("div", { className: "SPR_main" }, notice !== null ? h("div", { className: "SPR_note", "data-kind": notice.kind }, notice.text) : null, createCard, job === null
10860
+ ? h("p", { className: "SPR_empty" }, T("左侧选一个音效任务,或点「新建音效」开始。"))
10861
+ : h(React.Fragment, null, h("section", { className: "SPR_musicCard", "data-testid": "sfx-job" }, h("div", { className: "SPR_musicJobHead" }, h("h3", null, job.name), h(Chip, { kind: job.busy ? "running" : job.status === "error" ? "error" : takes.length > 0 ? "ready" : "stale", text: job.busy ? T("生成中…") : job.status === "error" ? T("失败") : takes.length > 0 ? T("已完成") : T("还没生成") }), job.reviewMode ? h("span", { className: "SPR_musicMeta" }, job.reviewMode === "manual" ? T("每一步人工审核") : T("自动审核")) : null, h("span", { className: "SPR_musicMeta" }, T("{n0} 条生成 · 上限 120 秒", { n0: takes.length }))), blocker !== null ? h("div", { className: "SPR_note", "data-kind": "error" }, blocker) : null, job.error ? h("div", { className: "SPR_note", "data-kind": "error" }, job.error) : null, h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("提示词({n0}/2048)", { n0: promptDraft.length })), h("textarea", {
10862
+ className: "SPR_musicText",
10863
+ "data-testid": "sfx-prompt",
10864
+ rows: 4,
10865
+ maxLength: 2048,
10866
+ value: promptDraft,
10867
+ onChange: (event) => setPromptDraft(event.target.value)
10868
+ })), h("div", { className: "SPR_musicGrid2" }, h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("输出格式")), h("select", { className: "SPR_input", value: settingsDraft.format, onChange: (event) => setSettingsDraft({ ...settingsDraft, format: event.target.value }) }, formats.map((format) => h("option", { key: format.id, value: format.id }, format.label)))), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("采样率")), h("select", { className: "SPR_input", value: String(settingsDraft.sampleRate), onChange: (event) => setSettingsDraft({ ...settingsDraft, sampleRate: Number(event.target.value) }) }, sampleRates.map((rate) => h("option", { key: String(rate), value: String(rate) }, `${rate} Hz`)))), h(NumField, { label: T("语速(-50~100)"), value: settingsDraft.speechRate, min: -50, max: 100, onChange: (value) => setSettingsDraft({ ...settingsDraft, speechRate: value }) }), h(NumField, { label: T("音量(-50~100)"), value: settingsDraft.loudnessRate, min: -50, max: 100, onChange: (value) => setSettingsDraft({ ...settingsDraft, loudnessRate: value }) }), h(NumField, { label: T("音调(-12~12)"), value: settingsDraft.pitchRate, min: -12, max: 12, onChange: (value) => setSettingsDraft({ ...settingsDraft, pitchRate: value }) })), h("label", { className: "SPR_musicCheck" }, h("input", { type: "checkbox", checked: settingsDraft.watermark, onChange: (event) => setSettingsDraft({ ...settingsDraft, watermark: event.target.checked }) }), T("加 AIGC 节奏水印(默认关)")), h("div", { className: "SPR_toolbar" }, h(BusyBtn, { busy: generating || job.busy === true, busyText: T("正在生成…"), primary: true, "data-testid": "sfx-generate", disabled: blocker !== null || promptDraft.trim() === "", onClick: () => void generate() }, takes.length === 0 ? T("生成(计费)") : T("再生成一条(计费)")), h(BusyBtn, { busy: saving, busyText: T("正在保存…"), onClick: () => void saveJob() }, T("保存提示词与参数")), h(Btn, { onClick: () => void api.revealSfxJob({ jobId }) }, T("打开任务目录")), h(Btn, { danger: true, onClick: () => void removeJob() }, T("删除任务"))), h("p", { className: "SPR_hint" }, T("每次生成都会真实计费;失败不会自动重试。参考图最多 1 张,参考音频最多 3 条,两者不能同时用。"))), h("section", { className: "SPR_musicCard", "data-testid": "sfx-refs" }, h("h3", null, T("参考素材(可选)")), h("div", { className: "SPR_toolbar" }, h(BusyBtn, { busy: refBusy, busyText: T("上传中…"), onClick: () => imageInputRef.current?.click?.() }, T("上传参考图")), h(BusyBtn, { busy: refBusy, busyText: T("上传中…"), onClick: () => audioInputRef.current?.click?.() }, T("上传参考音频")), h("input", { ref: imageInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", style: { display: "none" }, onChange: uploadRef("image") }), h("input", { ref: audioInputRef, type: "file", accept: "audio/wav,audio/mpeg,audio/ogg,audio/opus", style: { display: "none" }, onChange: uploadRef("audio") })), refs.image !== null && refs.image !== undefined
10869
+ ? h("div", { className: "SPR_musicSource" }, h("img", { className: "SPR_thumbMd", src: musicAssetUrl(job, refs.image.file, refs.image.url), alt: refs.image.name }), h("span", { className: "SPR_musicMeta" }, `${refs.image.name} · ${sfxFmtBytes(refs.image.bytes)}`), h(Btn, { onClick: () => void removeRef("image") }, T("删除参考图")))
10870
+ : null, (refs.audios ?? []).length > 0
10871
+ ? h("div", { className: "SPR_musicSongs" }, (refs.audios ?? []).map((entry, index) => h("div", { key: entry.file, className: "SPR_musicSong" }, h("div", { className: "SPR_musicSongBody" }, h("strong", null, T("参考音频 {n0}:{n1}", { n0: index + 1, n1: entry.name })), h("span", { className: "SPR_musicMeta" }, `${sfxFmtBytes(entry.bytes)}${entry.duration ? ` · ${Number(entry.duration).toFixed(1)} 秒` : ""} · 提示词里用 @音频${index + 1}`), h("audio", { className: "SPR_musicAudio", controls: true, preload: "metadata", src: musicAssetUrl(job, entry.file, entry.url) })), h(Btn, { onClick: () => void removeRef("audio", entry.file) }, T("删除")))))
10872
+ : h("p", { className: "SPR_hint" }, T("参考图与参考音频不能同时使用;单文件上限 10MB,参考音频每条最长 30 秒。"))), h("section", { className: "SPR_musicCard", "data-testid": "sfx-takes" }, h("h3", null, T("生成结果({n0} 条)", { n0: takes.length })), job.busy === true ? h(LoadingOverlay, { show: true, text: T("正在生成音效…") }) : null, takes.length === 0
10873
+ ? h("p", { className: "SPR_hint" }, T("还没有生成。点上面的「生成(计费)」。"))
10874
+ : h("div", { className: "SPR_musicSongs" }, takes.slice().reverse().map((take) => h("div", { key: take.id, className: "SPR_musicSong", "data-testid": "sfx-take" }, h("div", { className: "SPR_musicSongBody" }, h("div", { className: "SPR_musicSongHead" }, h("strong", null, take.id), h("span", { className: "SPR_musicMeta" }, `${String(take.format).toUpperCase()} · ${take.duration ? `${Number(take.duration).toFixed(2)} 秒` : "—"} · ${sfxFmtBytes(take.bytes)}`), take.originalDuration && take.duration && Math.abs(take.originalDuration - take.duration) > 0.05
10875
+ ? h("span", { className: "SPR_musicMeta" }, T("计费 {n0} 秒", { n0: Number(take.originalDuration).toFixed(2) }))
10876
+ : null), h("audio", { className: "SPR_musicAudio", controls: true, preload: "metadata", src: musicAssetUrl(job, take.file, take.url) }), h("details", { className: "SPR_musicLyrics" }, h("summary", null, T("生成时用的提示词")), h("pre", null, take.prompt))), h("div", { className: "SPR_toolbar" }, h(BusyBtn, { busy: exporting === take.id, busyText: T("导出中…"), onClick: () => void exportTake(take.id, false) }, T("导出")), h("a", { className: "SPR_link", href: musicDownloadUrl(job, take.file, take.url), download: `${job.name}-${take.id}.${take.format}` }, T("下载")))))), takes.length > 1
10877
+ ? h("div", { className: "SPR_toolbar" }, h(BusyBtn, { busy: exporting === "zip", busyText: T("打包中…"), onClick: () => void exportTake(undefined, true) }, T("全部打包导出(zip)")))
10878
+ : null, exportResult !== null
10879
+ ? h("p", { className: "SPR_hint" }, T("已导出:{n0}", { n0: exportResult.path ?? exportResult.file ?? "" }), exportResult.downloadUrl ? h("a", { className: "SPR_link", href: exportResult.downloadUrl }, T("下载")) : null)
10880
+ : null), h("section", { className: "SPR_musicCard" }, h("div", { className: "SPR_toolbar" }, h(Btn, { primary: job.stages?.generate?.approved !== true, onClick: () => void approve(job.stages?.generate?.approved !== true) }, job.stages?.generate?.approved === true ? T("取消通过") : T("通过本条音效")), h(Btn, { onClick: () => void loadJob(jobId) }, T("刷新"))), (job.log ?? []).length > 0
10881
+ ? h("details", { className: "SPR_musicLog" }, h("summary", null, T("任务日志({n0} 条)", { n0: (job.log ?? []).length })), h("ul", null, (job.log ?? []).slice(-10).map((entry, index) => h("li", { key: index }, `${new Date(entry.at).toLocaleTimeString()} · ${entry.message}`))))
10882
+ : null)));
10883
+ return h("div", { className: "SPR_body SPR_musicBody" }, h("div", { className: "SPR_side" }, h("div", { className: "SPR_sideTitle" }, T("音效任务({n0})", { n0: jobs.length })), h(Btn, { primary: true, "data-testid": "sfx-create-open", onClick: () => { setDraft({ name: "", prompt: "", format: config?.sfxFormat ?? "wav", sampleRate: config?.sfxSampleRate ?? 24000 }); setCreateOpen(true); setJob(null); setJobId(null); } }, T("新建音效")), jobs.length === 0
10884
+ ? h("p", { className: "SPR_hint" }, T("还没有任务。写一句「要什么声音」开始。"))
10885
+ : jobs.map((entry) => h("button", { key: entry.id, type: "button", className: "SPR_projItem", "data-active": entry.id === jobId ? "true" : "false", onClick: () => void loadJob(entry.id) }, h("span", { className: "SPR_projName" }, entry.name), h("span", { className: "SPR_projMeta" }, `${entry.takes ?? 0} 条${entry.latestDuration ? ` · ${Number(entry.latestDuration).toFixed(2)}s` : ""}${entry.busy ? " · ⏳" : ""}`)))), main);
10886
+ }
10397
10887
  // ── 模块②:图片生成 ─────────────────────────────────────────────────
10398
10888
  /** 模块②的 pending key:整批生成、单张重生成、抠像、上传、新建任务。 */
10399
10889
  const K_IMG_JOB = "img:job";
@@ -12129,6 +12619,13 @@ window.__ModuleLoader__.load({
12129
12619
  const tasks = usePendingTasks();
12130
12620
  // 深链接:切到某一个图片任务。
12131
12621
  const intent = useStudioIntent();
12622
+ /**
12623
+ * 上一次从宿主读到的草稿(连同任务 id)。
12624
+ *
12625
+ * 有任务在跑时这里每 2.5 秒 `load()` 一次;无条件覆盖草稿的话,用户正在
12626
+ * 改提示词 / 尺寸时会被打回原形(同模块①的视频提示词)。判定见 `mergeDrafts`。
12627
+ */
12628
+ const loadedDrafts = React.useRef({ id: null, prompt: "", suffix: "", settings: {}, keying: {} });
12132
12629
  React.useEffect(() => {
12133
12630
  if (intent === null)
12134
12631
  return;
@@ -12152,11 +12649,16 @@ window.__ModuleLoader__.load({
12152
12649
  return;
12153
12650
  try {
12154
12651
  const next = await api.getImageJob(id);
12652
+ const previous = loadedDrafts.current;
12653
+ const force = previous.id !== id;
12654
+ const settings = { ...(next.settings ?? {}) };
12655
+ const keying = { ...(next.keying ?? {}) };
12656
+ loadedDrafts.current = { id, prompt: next.prompt ?? "", suffix: next.suffix ?? "", settings, keying };
12155
12657
  setJob(next);
12156
- setPromptDraft(next.prompt ?? "");
12157
- setSuffixDraft(next.suffix ?? "");
12158
- setSettingsDraft({ ...(next.settings ?? {}) });
12159
- setKeyingDraft({ ...(next.keying ?? {}) });
12658
+ setPromptDraft((current) => mergeDrafts(current, previous.prompt, next.prompt ?? "", force));
12659
+ setSuffixDraft((current) => mergeDrafts(current, previous.suffix, next.suffix ?? "", force));
12660
+ setSettingsDraft((current) => mergeDrafts(current, previous.settings, settings, force));
12661
+ setKeyingDraft((current) => mergeDrafts(current, previous.keying, keying, force));
12160
12662
  }
12161
12663
  catch (error) {
12162
12664
  setNotice({ kind: "error", text: msg(error) });
@@ -12372,6 +12874,13 @@ window.__ModuleLoader__.load({
12372
12874
  const tasks = usePendingTasks();
12373
12875
  // 深链接:切到某一个序列帧任务。
12374
12876
  const intent = useStudioIntent();
12877
+ /**
12878
+ * 上一次从宿主读到的草稿(连同任务 id)。
12879
+ *
12880
+ * 视频 / 抽帧 / 合成在跑时这里每 5 秒 `load()` 一次;无条件覆盖草稿的话,
12881
+ * 用户正在改提示词 / 时长时会被打回原形。判定见 `mergeDrafts`。
12882
+ */
12883
+ const loadedDrafts = React.useRef({ id: null, prompt: "", suffix: "", settings: {}, keying: {} });
12375
12884
  React.useEffect(() => {
12376
12885
  if (intent === null)
12377
12886
  return;
@@ -12410,11 +12919,16 @@ window.__ModuleLoader__.load({
12410
12919
  return;
12411
12920
  try {
12412
12921
  const next = await api.getSequenceJob(id);
12922
+ const previous = loadedDrafts.current;
12923
+ const force = previous.id !== id;
12924
+ const settings = { ...(next.settings ?? {}) };
12925
+ const keying = { ...(next.keying ?? {}) };
12926
+ loadedDrafts.current = { id, prompt: next.prompt ?? "", suffix: next.suffix ?? "", settings, keying };
12413
12927
  setJob(next);
12414
- setPromptDraft(next.prompt ?? "");
12415
- setSuffixDraft(next.suffix ?? "");
12416
- setSettingsDraft({ ...(next.settings ?? {}) });
12417
- setKeyingDraft({ ...(next.keying ?? {}) });
12928
+ setPromptDraft((current) => mergeDrafts(current, previous.prompt, next.prompt ?? "", force));
12929
+ setSuffixDraft((current) => mergeDrafts(current, previous.suffix, next.suffix ?? "", force));
12930
+ setSettingsDraft((current) => mergeDrafts(current, previous.settings, settings, force));
12931
+ setKeyingDraft((current) => mergeDrafts(current, previous.keying, keying, force));
12418
12932
  }
12419
12933
  catch (error) {
12420
12934
  setNotice({ kind: "error", text: msg(error) });
@@ -14673,6 +15187,13 @@ window.__ModuleLoader__.load({
14673
15187
  const globalConfig = useGlobalConfig(api);
14674
15188
  const tasks = usePendingTasks();
14675
15189
  const intent = useStudioIntent();
15190
+ /**
15191
+ * 上一次从宿主读到的草稿(连同任务 id)。
15192
+ *
15193
+ * 有阶段在跑时这里每 2.5 秒 `load()` 一次;无条件覆盖草稿的话,用户正在改
15194
+ * 摊平提示词 / 网格参数时会被打回原形。判定见 `mergeDrafts`。
15195
+ */
15196
+ const loadedDrafts = React.useRef({ id: null, prompt: "", suffix: "", settings: {} });
14676
15197
  React.useEffect(() => {
14677
15198
  if (intent === null)
14678
15199
  return;
@@ -14724,10 +15245,16 @@ window.__ModuleLoader__.load({
14724
15245
  setJob(null);
14725
15246
  return;
14726
15247
  }
15248
+ const previous = loadedDrafts.current;
15249
+ const force = previous.id !== id;
15250
+ const prompt = next.prompts?.sheet ?? "";
15251
+ const suffix = next.prompts?.suffix ?? "";
15252
+ const settings = { ...(next.settings ?? {}) };
15253
+ loadedDrafts.current = { id, prompt, suffix, settings };
14727
15254
  setJob(next);
14728
- setPromptDraft(next.prompts?.sheet ?? "");
14729
- setSuffixDraft(next.prompts?.suffix ?? "");
14730
- setSettingsDraft({ ...(next.settings ?? {}) });
15255
+ setPromptDraft((current) => mergeDrafts(current, previous.prompt, prompt, force));
15256
+ setSuffixDraft((current) => mergeDrafts(current, previous.suffix, suffix, force));
15257
+ setSettingsDraft((current) => mergeDrafts(current, previous.settings, settings, force));
14731
15258
  setSelected((current) => (current !== null && (next.parts ?? []).some((part) => part.name === current) ? current : null));
14732
15259
  }
14733
15260
  catch (error) {
@@ -15058,6 +15585,8 @@ window.__ModuleLoader__.load({
15058
15585
  * 探测,所以留成草稿,失焦才保存。
15059
15586
  */
15060
15587
  const [scorePaths, setScorePaths] = React.useState(null);
15588
+ /** 音效模块的语音 API Key(单独一份,不是方舟 Key)。 */
15589
+ const [sfxKey, setSfxKey] = React.useState("");
15061
15590
  const load = React.useCallback(async () => {
15062
15591
  if (api === undefined)
15063
15592
  return;
@@ -15599,7 +16128,42 @@ window.__ModuleLoader__.load({
15599
16128
  await run(() => api.testMusicScore(), (value) => (value?.ok === true ? T("谱曲依赖已就绪") : value?.blocker ?? T("仍有依赖缺失")));
15600
16129
  setTesting(null);
15601
16130
  }
15602
- }, T("重新检测"))), h("p", { className: "SPR_hint" }, T("安装提示:python3 -m pip install scoremill;macOS 可 brew install fluid-synth;SoundFont 放到 ~/Library/Audio/SoundFonts/FluidR3_GM.sf2。")), h("p", { className: "SPR_hint" }, T("谱曲模式参考:scoremill(MIT,https://github.com/CharlesCNorton/scoremill)与 Midra 的 prompt-to-code MIDI 思路;只吸收方法论,未打包其代码或音源。"))), h("div", { className: "SPR_settingsGroup" }, h("h3", null, T("功能管理")), h("p", null, T("隐藏不用的功能。隐藏后界面里不再出现它的页签与侧栏菜单项,对话里的 AI 也无法调用它(工具会直接报错)。随时可以再打开,已有的项目数据不会被删除。")), h("div", { className: "SPR_featureList" }, MODULES.map((entry) => {
16131
+ }, T("重新检测"))), h("p", { className: "SPR_hint" }, T("安装提示:python3 -m pip install scoremill;macOS 可 brew install fluid-synth;SoundFont 放到 ~/Library/Audio/SoundFonts/FluidR3_GM.sf2。")), h("p", { className: "SPR_hint" }, T("谱曲模式参考:scoremill(MIT,https://github.com/CharlesCNorton/scoremill)与 Midra 的 prompt-to-code MIDI 思路;只吸收方法论,未打包其代码或音源。"))), h("div", { className: "SPR_settingsGroup" }, h("h3", null, T("音效生成(火山引擎 Seed-Audio)")), h("p", null, T("用豆包语音的生成式音频模型做游戏音效:撞击 / 环境音 / UI 声 / 生物吼叫 / 角色配音。单次最长 120 秒。Key 是语音控制台的 API Key(请求头 X-Api-Key),不是火山方舟的 ARK_API_KEY;模型需要在语音控制台开通。")), config.sfxBlocker !== null && config.sfxBlocker !== undefined
16132
+ ? h("div", { className: "SPR_note", "data-kind": "error" }, config.sfxBlocker)
16133
+ : null, h("div", { className: "SPR_fields" }, h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("API Key")), h("input", {
16134
+ className: "SPR_input",
16135
+ type: "password",
16136
+ autoComplete: "off",
16137
+ "data-testid": "cfg-sfx-key",
16138
+ placeholder: config.sfxApiKeySet ? T("已配置 {n0}(留空表示不修改)", { n0: config.sfxApiKeyHint }) : T("粘贴语音控制台 API Key"),
16139
+ value: sfxKey,
16140
+ onChange: (event) => setSfxKey(event.target.value)
16141
+ })), h("div", { className: "SPR_toolbar" }, h(Btn, { primary: true, disabled: sfxKey.trim() === "", onClick: () => void run(async () => { await api.saveConfig({ sfxApiKey: sfxKey }); setSfxKey(""); }, T("音效 API Key 已保存")) }, T("保存 Key")), h(Btn, { disabled: config.sfxApiKeySet !== true, onClick: () => void run(() => api.saveConfig({ clearSfxApiKey: true }), T("已清除音效 API Key")) }, T("清除 Key")), h(BusyBtn, {
16142
+ busy: testing === "sfx",
16143
+ busyText: T("正在生成测试音效…"),
16144
+ disabled: testing !== null || config.sfxApiKeySet !== true,
16145
+ onClick: async () => {
16146
+ setTesting("sfx");
16147
+ await run(() => api.testSfx(), (value) => T("连接正常:{n0}", { n0: value.message ?? "" }));
16148
+ setTesting(null);
16149
+ }
16150
+ }, T("测试连接(会真实生成一条极短音效,产生少量费用)"))), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("API 地址")), h("input", {
16151
+ className: "SPR_input",
16152
+ value: config.sfxBaseUrl ?? "",
16153
+ onChange: (event) => void patch({ sfxBaseUrl: event.target.value }),
16154
+ placeholder: "https://openspeech.bytedance.com"
16155
+ })), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("默认模型")), h("input", {
16156
+ className: "SPR_input",
16157
+ value: config.sfxModel ?? "seed-audio-1.0",
16158
+ onChange: (event) => void patch({ sfxModel: event.target.value }),
16159
+ placeholder: "seed-audio-1.0"
16160
+ })), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("默认输出格式")), h("select", { className: "SPR_input", value: config.sfxFormat ?? "wav", onChange: (event) => void patch({ sfxFormat: event.target.value }) }, (config.sfxFormats ?? [{ id: "wav" }, { id: "mp3" }, { id: "ogg_opus" }]).map((format) => h("option", { key: format.id, value: format.id }, sfxFormatLabel(format.id))))), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("默认采样率")), h("select", { className: "SPR_input", value: String(config.sfxSampleRate ?? 24000), onChange: (event) => void patch({ sfxSampleRate: Number(event.target.value) }) }, (config.sfxSampleRates ?? [16000, 24000, 44100, 48000]).map((rate) => h("option", { key: String(rate), value: String(rate) }, `${rate} Hz`)))), h(NumField, {
16161
+ label: T("请求超时(毫秒)"),
16162
+ value: config.sfxTimeoutMs ?? 300000,
16163
+ min: 30000,
16164
+ max: 900000,
16165
+ onChange: (value) => void patch({ sfxTimeoutMs: value })
16166
+ })), h("p", { className: "SPR_hint" }, T("文档:"), config.sfxDocsUrl ? h("a", { className: "SPR_link", href: config.sfxDocsUrl, target: "_blank", rel: "noreferrer" }, config.sfxDocsUrl) : null, T(" · 控制台:"), config.sfxConsoleUrl ? h("a", { className: "SPR_link", href: config.sfxConsoleUrl, target: "_blank", rel: "noreferrer" }, config.sfxConsoleUrl) : null)), h("div", { className: "SPR_settingsGroup" }, h("h3", null, T("功能管理")), h("p", null, T("隐藏不用的功能。隐藏后界面里不再出现它的页签与侧栏菜单项,对话里的 AI 也无法调用它(工具会直接报错)。随时可以再打开,已有的项目数据不会被删除。")), h("div", { className: "SPR_featureList" }, MODULES.map((entry) => {
15603
16167
  const isHidden = hiddenNow.includes(entry.key);
15604
16168
  return h("label", {
15605
16169
  key: entry.key,
@@ -15829,7 +16393,21 @@ window.__ModuleLoader__.load({
15829
16393
  renderMusicEdit: (payload) => call("renderMusicEdit", payload),
15830
16394
  saveMusicVersion: (payload) => call("saveMusicVersion", payload),
15831
16395
  deleteMusicVersion: (payload) => call("deleteMusicVersion", payload),
15832
- exportMusic: (payload) => call("exportMusic", payload)
16396
+ exportMusic: (payload) => call("exportMusic", payload),
16397
+ // 音效生成(模块八)
16398
+ testSfx: () => call("testSfx"),
16399
+ listSfxJobs: () => call("listSfxJobs"),
16400
+ createSfxJob: (payload) => call("createSfxJob", payload),
16401
+ getSfxJob: (payload) => call("getSfxJob", payload),
16402
+ saveSfxJob: (payload) => call("saveSfxJob", payload),
16403
+ deleteSfxJob: (payload) => call("deleteSfxJob", payload),
16404
+ uploadSfxRef: (payload) => call("uploadSfxRef", payload),
16405
+ removeSfxRef: (payload) => call("removeSfxRef", payload),
16406
+ runSfxGeneration: (payload) => call("runSfxGeneration", payload),
16407
+ cancelSfxGeneration: (payload) => call("cancelSfxGeneration", payload),
16408
+ setSfxApproved: (payload) => call("setSfxApproved", payload),
16409
+ revealSfxJob: (payload) => call("revealSfxJob", payload),
16410
+ exportSfx: (payload) => call("exportSfx", payload)
15833
16411
  };
15834
16412
  // ── 深链接:会话里的链接点一下切到本插件页面 ─────────────────────
15835
16413
  // 拦截器与生命周期绑定:插件停止 / 更新时监听器一定被摘掉。
@@ -15884,7 +16462,7 @@ window.__ModuleLoader__.load({
15884
16462
  * `mapgeom` / `mapdoc` 的真实现做黄金对照逐点比对 —— 界面复刻的那部分几何
15885
16463
  * 必须有守门的,否则「预览与导出错位」会以静默的方式回来。
15886
16464
  */
15887
- bundleModule.exports.__test = { StudioPanel, TileModule, ImageModule, SequenceModule, RigSemanticsPanel, MapModule, MusicModule, MAP_pointToCell, MAP_cellAnchor, MAP_cellTopLeft, MAP_lineCells, usePendingTasks, LoadingOverlay, MediaBox, BusyBtn, BusyBadge, NumField, ZoomableImage, CSS, subscribeIntent, parseIntents, openStudioIntent, OPEN_QUERY_KEY, StudioGlyph, StudioGlyphIcon, publishHiddenModules, useHiddenModules, visibleModulesOf, normalizeHiddenKeys, ConfigSection, attachSessionBridge, openAssetChat, openMusicChat, buildAssetRequestPrompt, buildMusicRequestPrompt, buildComposeRequestPrompt, deriveAssetName, deriveMusicName, ASSET_FRAMES_MIN, ASSET_FRAMES_MAX };
16465
+ bundleModule.exports.__test = { StudioPanel, TileModule, ImageModule, SequenceModule, mergeDrafts, RigSemanticsPanel, MapModule, MusicModule, SfxModule, MAP_pointToCell, MAP_cellAnchor, MAP_cellTopLeft, MAP_lineCells, usePendingTasks, LoadingOverlay, MediaBox, BusyBtn, BusyBadge, NumField, ZoomableImage, CSS, subscribeIntent, parseIntents, openStudioIntent, OPEN_QUERY_KEY, StudioGlyph, StudioGlyphIcon, publishHiddenModules, useHiddenModules, visibleModulesOf, normalizeHiddenKeys, ConfigSection, attachSessionBridge, openAssetChat, openMusicChat, buildAssetRequestPrompt, buildMusicRequestPrompt, buildComposeRequestPrompt, deriveAssetName, deriveMusicName, ASSET_FRAMES_MIN, ASSET_FRAMES_MAX };
15888
16466
  return bundleModule.exports;
15889
16467
  }
15890
16468
  });