@ninkch/dsh-infinite-canvas 0.20.2 → 0.20.3

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.
Files changed (3) hide show
  1. package/client.js +79 -208
  2. package/package.json +2 -1
  3. package/shot-segments.js +233 -0
package/client.js CHANGED
@@ -893,7 +893,6 @@ function revealCanvasInRight() {
893
893
  'videoApi': '视频 API(提交 + 轮询)',
894
894
  'baseUrl': '接口地址',
895
895
  'apiKey': 'API Key',
896
- 'model': '模型',
897
896
  'size': '尺寸',
898
897
  'apiHintImage': '留空则使用内置演示模式(本地合成占位图)。配置后请求 POST {baseUrl}/images/generations。',
899
898
  'apiHintVideo': 'POST 接口地址提交任务,轮询 GET {url}/{taskId} 直到返回视频地址;留空则使用演示模式(本地合成动画视频)。',
@@ -1060,11 +1059,7 @@ function revealCanvasInRight() {
1060
1059
  'defaultVideoCfg': '默认视频模型',
1061
1060
  'imageApisLabel': '图片模型(可配多个)',
1062
1061
  'videoApisLabel': '视频模型(可配多个)',
1063
- 'addConfig': '新增配置',
1064
- 'setDefault': '设为默认',
1065
- 'isDefault': '默认',
1066
1062
  'cfgName': '名称',
1067
- 'delConfig': '删除此配置',
1068
1063
  'noCfgHint': '尚未配置;生成节点将使用演示模式',
1069
1064
  'bibleTab': '设定集',
1070
1065
  'bibleStyle': '风格基调(画风、年代、色调…跨集保持一致)',
@@ -1280,7 +1275,6 @@ function revealCanvasInRight() {
1280
1275
  'renamed': '已重命名',
1281
1276
  'llmMaxTokens': '输出上限 maxTokens',
1282
1277
  'llmTemperature': '温度 temperature',
1283
- 'llmParamAuto': '留空 = 用 Harness/模型默认',
1284
1278
  'llmParamHint': '留空则不下发该参数,直接使用你在 Harness 里为该模型配置的默认值(插件不会写死任何生成参数)',
1285
1279
  'imgSizeOverride': '尺寸覆盖 size',
1286
1280
  'imgSizePlaceholder': '如 1024x1024(留空=按清晰度×比例)',
@@ -1904,7 +1898,6 @@ function revealCanvasInRight() {
1904
1898
  'videoApi': 'Video API (submit + poll)',
1905
1899
  'baseUrl': 'Base URL',
1906
1900
  'apiKey': 'API Key',
1907
- 'model': 'Model',
1908
1901
  'size': 'Size',
1909
1902
  'apiHintImage': 'Leave empty to use the built-in demo mode (local placeholder images). When set, requests go to POST {baseUrl}/images/generations.',
1910
1903
  'apiHintVideo': 'POSTs the task to the URL and polls GET {url}/{taskId} until a video URL appears; leave empty for demo mode.',
@@ -2071,11 +2064,7 @@ function revealCanvasInRight() {
2071
2064
  'defaultVideoCfg': 'Default video model',
2072
2065
  'imageApisLabel': 'Image models (multiple)',
2073
2066
  'videoApisLabel': 'Video models (multiple)',
2074
- 'addConfig': 'Add config',
2075
- 'setDefault': 'Make default',
2076
- 'isDefault': 'default',
2077
2067
  'cfgName': 'Name',
2078
- 'delConfig': 'Delete this config',
2079
2068
  'noCfgHint': 'Nothing configured yet; generation nodes will use demo mode',
2080
2069
  'bibleTab': 'Bible',
2081
2070
  'bibleStyle': 'Style baseline (art, era, palette… kept across episodes)',
@@ -2292,7 +2281,6 @@ function revealCanvasInRight() {
2292
2281
  'renamed': 'Renamed',
2293
2282
  'llmMaxTokens': 'Output cap (maxTokens)',
2294
2283
  'llmTemperature': 'Temperature',
2295
- 'llmParamAuto': 'empty = Harness/model default',
2296
2284
  'llmParamHint': 'Left empty, the parameter is not sent at all — the model uses the default you configured in Harness. The plugin never hardcodes generation parameters.',
2297
2285
  'imgSizeOverride': 'Size override',
2298
2286
  'imgSizePlaceholder': 'e.g. 1024x1024 (empty = clarity × ratio)',
@@ -3645,8 +3633,8 @@ body[data-ds-dark-theme] .dshic-pick-item.is-on{background:color-mix(in srgb,var
3645
3633
  videoProviders: [], // [{id, name, url, apiKey, extra, outputFormat?, generateAudio?, protocol?, watermark?, models: [{id, model}]}]
3646
3634
  imageStar: '', // 'providerId|modelId'
3647
3635
  videoStar: '',
3648
- ttsApis: [], // [{id, name, baseUrl, apiKey, model, voice}]
3649
- ttsApiId: '',
3636
+ ttsProviders: [], // [{id, name, baseUrl, apiKey, timeoutMs?, models: [{id, model, voice}]}] —— voice 每模型一个,timeoutMs 供应商级
3637
+ ttsStar: '', // 'providerId|modelId'
3650
3638
  lang: '', // '' = 跟随 Harness
3651
3639
  };
3652
3640
  function loadSettings() {
@@ -3659,8 +3647,8 @@ body[data-ds-dark-theme] .dshic-pick-item.is-on{background:color-mix(in srgb,var
3659
3647
  videoStar: s.videoStar || '',
3660
3648
  // dsh-image-gen 桥接:启用后画布不自配图片 API,直接走它的 /studio(密钥留在它宿主侧)
3661
3649
  imageGen: { enabled: !!(s.imageGen && s.imageGen.enabled), provider: (s.imageGen && s.imageGen.provider) || '', model: (s.imageGen && s.imageGen.model) || '' },
3662
- ttsApis: Array.isArray(s.ttsApis) ? s.ttsApis : [],
3663
- ttsApiId: s.ttsApiId || '',
3650
+ ttsProviders: Array.isArray(s.ttsProviders) ? s.ttsProviders : [],
3651
+ ttsStar: s.ttsStar || '',
3664
3652
  lang: s.lang || '',
3665
3653
  // 专家:缺字段/非法值/旧字段(skillScript/skillStoryboard)→ 一律回退 general,不报错
3666
3654
  };
@@ -3707,12 +3695,34 @@ body[data-ds-dark-theme] .dshic-pick-item.is-on{background:color-mix(in srgb,var
3707
3695
  legacyVideoApiRefMap = {};
3708
3696
  for (const cfg of s.videoApis) legacyVideoApiRefMap[cfg.id] = 'p_' + cfg.id + '|m_' + cfg.id;
3709
3697
  }
3698
+ // v0.20.2 及以前 TTS 扁平 API(一配置一模型一 voice)→ 供应商 + 模型列表(issue #6 第二阶段):
3699
+ // 与 image/video 同规:派生 id 确定性沿用旧 cfg id(loadSettings 高频调用,绝不用 uid());
3700
+ // 节点数据只存 data.tts[edgeId] = {status, assetId}(无 ttsApiId),零节点迁移负担
3701
+ if (!out.ttsProviders.length && Array.isArray(s.ttsApis) && s.ttsApis.length) {
3702
+ out.ttsProviders = s.ttsApis.map((cfg) => ({
3703
+ id: 'p_' + cfg.id, name: cfg.name || T('defaultTtsCfg'),
3704
+ baseUrl: cfg.baseUrl || '', apiKey: cfg.apiKey || '',
3705
+ timeoutMs: cfg.timeoutMs || '',
3706
+ models: [{ id: 'm_' + cfg.id, model: cfg.model || '', voice: cfg.voice || 'alloy' }],
3707
+ }));
3708
+ out.ttsStar = (s.ttsApiId && 'p_' + s.ttsApiId + '|m_' + s.ttsApiId) || (out.ttsProviders[0] ? out.ttsProviders[0].id + '|' + out.ttsProviders[0].models[0].id : '');
3709
+ }
3710
3710
  return out;
3711
3711
  }
3712
3712
  function saveSettings(s) {
3713
3713
  lsSet(LS_SETTINGS, s);
3714
3714
  notify(); // 设置即改即存(无保存按钮),但必须通知画布重渲染——否则节点上的模型下拉/星标一直是旧快照
3715
3715
  }
3716
+ /** 设置卡写回:以磁盘最新值为基底叠加本卡变更,杜绝跨卡丢失更新(issue #6)。
3717
+ * 旧模式(每张卡持有挂载时快照、把整对象写回)会让卡 B 的任何保存把卡 A 刚写的字段静默回滚。
3718
+ * base = loadSettings() 现取;apply(base) 返回改了本卡字段的副本;写回 + notify。
3719
+ * 返回写回后的新设置——调用方必须 setS(返回值) 同步本地快照,否则同卡二次编辑的渲染基底仍陈旧。 */
3720
+ function updateSettings(apply) {
3721
+ const base = loadSettings();
3722
+ const next = apply(base);
3723
+ saveSettings(next);
3724
+ return next;
3725
+ }
3716
3726
 
3717
3727
  // ---------- 供应商 + 模型(图片/视频):扁平视图与解析 ----------
3718
3728
  let legacyImageApiRefMap = {}; // 旧扁平配置 id → 'providerId|modelId'(节点字段懒迁移用)
@@ -3742,6 +3752,17 @@ body[data-ds-dark-theme] .dshic-pick-item.is-on{background:color-mix(in srgb,var
3742
3752
  }
3743
3753
  return out;
3744
3754
  }
3755
+ /** 供应商列表 → 扁平 TTS 模型视图(ref = 'providerId|modelId');未填模型名的条目不进下拉(与 image/video 同规)。 */
3756
+ function flattenTtsModels(settings) {
3757
+ const out = [];
3758
+ for (const p of settings.ttsProviders || []) {
3759
+ for (const m of (p.models || [])) {
3760
+ if (!m || !m.id || !String(m.model || '').trim()) continue;
3761
+ out.push({ ref: p.id + '|' + m.id, providerId: p.id, providerName: p.name || p.id, modelId: m.id, model: String(m.model).trim(), voice: m.voice || 'alloy', baseUrl: p.baseUrl || '', apiKey: p.apiKey || '', timeoutMs: p.timeoutMs || '' });
3762
+ }
3763
+ }
3764
+ return out;
3765
+ }
3745
3766
  /** 解析节点上的模型引用:空 = 星标默认模型;都没有 = null(运行时报错)。 */
3746
3767
  function resolveImageModelCfg(settings, ref) {
3747
3768
  const list = flattenImageModels(settings);
@@ -7618,11 +7639,6 @@ function queueThumb(assetId) {
7618
7639
  return ['succeeded', 'success', 'completed', 'complete', 'done', 'finished'].includes(taskStatusOf(st));
7619
7640
  }
7620
7641
 
7621
- function resolveApiCfg(list, defId, wantId) {
7622
- if (!Array.isArray(list) || !list.length) return null;
7623
- return list.find((x) => x.id === wantId) || list.find((x) => x.id === defId) || list[0];
7624
- }
7625
-
7626
7642
  /** PCM 采样数组 → WAV Blob(单声道 16-bit,声音参考不需要立体声)。 */
7627
7643
  function pcmToWavBlob(samples, sampleRate) {
7628
7644
  const n = samples.length;
@@ -14393,7 +14409,8 @@ function queueThumb(assetId) {
14393
14409
  };
14394
14410
  const genTts = async (x) => {
14395
14411
  const settings = loadSettings();
14396
- const cfg = resolveApiCfg(settings.ttsApis, settings.ttsApiId, null);
14412
+ const list = flattenTtsModels(settings);
14413
+ const cfg = list.find((y) => y.ref === settings.ttsStar) || list[0];
14397
14414
  if (!cfg) { toast(T('errNoTts')); return; }
14398
14415
  const text = String(getSub(x) || '').trim();
14399
14416
  if (!text) { toast(T('subPlaceholder')); return; }
@@ -19426,12 +19443,9 @@ const DIRECTOR_KEY_HELP = [
19426
19443
  for (const m of (p.models || [])) options.push({ value: p.id + '|' + m.id, label: `${p.name} · ${m.name}` });
19427
19444
  }
19428
19445
  const applyTextLlm = (provider, model) => {
19429
- setS((prev) => {
19430
- const next = JSON.parse(JSON.stringify(prev));
19431
- next.textLlm = { provider: provider || '', model: model || '' };
19432
- saveSettings(next);
19433
- return next;
19434
- });
19446
+ // issue #6:基底现取磁盘最新(不再用挂载时快照整对象写回),写回后 setS 同步刷新本地快照
19447
+ const next = updateSettings((b) => ({ ...b, textLlm: { provider: provider || '', model: model || '' } }));
19448
+ setS(next);
19435
19449
  };
19436
19450
  return h('div', { className: 'dshic-field' },
19437
19451
  h('span', { className: 'dshic-field-label' }, T('llmLabel')),
@@ -19500,25 +19514,29 @@ const DIRECTOR_KEY_HELP = [
19500
19514
  style: { flex: 'none', width: 14, height: 14, lineHeight: '13px', textAlign: 'center', fontSize: 10, borderRadius: '50%', border: '1px solid var(--dsw-alias-border-secondary, #777)', color: 'var(--dsw-alias-label-secondary, #999)', cursor: 'help', userSelect: 'none', opacity: 0.85 },
19501
19515
  }, 'i');
19502
19516
  }
19503
- /** 图片/视频模型配置(供应商 + 模型两级):一个供应商配一次 URL/Key,下面挂多个模型;
19504
- * ★星标模型 = 节点未指定时的默认路由。 */
19517
+ /** 图片/视频/TTS 模型配置(供应商 + 模型两级):一个供应商配一次 URL/Key,下面挂多个模型;
19518
+ * ★星标模型 = 节点未指定时的默认路由。TTS(issue #6 第二阶段):
19519
+ * voice 是每模型字段(不同模型支持的音色清单不同),timeoutMs 是供应商级(一供应商=一连接)。 */
19505
19520
  function ModelProviderEditor({ kind }) {
19506
19521
  const [s, setS] = useState(loadSettings);
19507
19522
  const [openId, setOpenId] = useState(null);
19508
- const listKey = kind === 'image' ? 'imageProviders' : 'videoProviders';
19509
- const starKey = kind === 'image' ? 'imageStar' : 'videoStar';
19510
- const icon = kind === 'image' ? 'image' : 'video';
19511
- const labelKey = kind === 'image' ? 'imageApisLabel' : 'videoApisLabel';
19512
- const nameKey = kind === 'image' ? 'defaultImageCfg' : 'defaultVideoCfg';
19513
- const urlKey = kind === 'image' ? 'baseUrl' : 'url';
19523
+ const listKey = kind === 'image' ? 'imageProviders' : kind === 'video' ? 'videoProviders' : 'ttsProviders';
19524
+ const starKey = kind === 'image' ? 'imageStar' : kind === 'video' ? 'videoStar' : 'ttsStar';
19525
+ const icon = kind === 'image' ? 'image' : kind === 'video' ? 'video' : 'audio';
19526
+ const labelKey = kind === 'image' ? 'imageApisLabel' : kind === 'video' ? 'videoApisLabel' : 'ttsApisLabel';
19527
+ const nameKey = kind === 'image' ? 'defaultImageCfg' : kind === 'video' ? 'defaultVideoCfg' : 'defaultTtsCfg';
19528
+ const urlKey = kind === 'video' ? 'url' : 'baseUrl';
19514
19529
  const urlPh = kind === 'image'
19515
19530
  ? 'https://api.example.com/v1(或完整 /images/generations 端点)'
19516
- : 'https://api.example.com/v1/video/generations(或裸域 / /v1)';
19517
- const persist = (next) => { setS(next); saveSettings(next); };
19518
- const mutate = (fn) => { const next = JSON.parse(JSON.stringify(s)); fn(next); persist(next); };
19531
+ : kind === 'video'
19532
+ ? 'https://api.example.com/v1/video/generations(或裸域 / /v1)'
19533
+ : 'https://api.example.com/v1';
19534
+ // issue #6:写回基底 = updateSettings 现取磁盘最新(不再是挂载时快照);persist 只负责把返回的新值同步进本地快照
19535
+ const persist = (next) => setS(next);
19536
+ const mutate = (fn) => { persist(updateSettings((b) => { const d = JSON.parse(JSON.stringify(b)); fn(d); return d; })); };
19519
19537
  const addProvider = () => {
19520
19538
  const id = uid('prov');
19521
- mutate((d) => { d[listKey] = (d[listKey] || []).concat([{ id, name: T(nameKey) + ' ' + ((d[listKey] || []).length + 1), [urlKey]: '', apiKey: '', extra: '', models: [], ...(kind === 'image' ? { mode: 'generations' } : {}) }]); });
19539
+ mutate((d) => { d[listKey] = (d[listKey] || []).concat([{ id, name: T(nameKey) + ' ' + ((d[listKey] || []).length + 1), [urlKey]: '', apiKey: '', ...(kind === 'tts' ? { timeoutMs: '' } : { extra: '' }), models: [], ...(kind === 'image' ? { mode: 'generations' } : {}) }]); });
19522
19540
  setOpenId(id);
19523
19541
  };
19524
19542
  const removeProvider = (id) => {
@@ -19526,7 +19544,7 @@ const DIRECTOR_KEY_HELP = [
19526
19544
  if (openId === id) setOpenId(null);
19527
19545
  };
19528
19546
  const patchProvider = (id, k, v) => mutate((d) => { d[listKey] = (d[listKey] || []).map((x) => (x.id === id ? { ...x, [k]: v } : x)); });
19529
- const addModel = (pid) => mutate((d) => { const p = (d[listKey] || []).find((x) => x.id === pid); if (p) p.models = (p.models || []).concat([{ id: uid('m'), model: '' }]); });
19547
+ const addModel = (pid) => mutate((d) => { const p = (d[listKey] || []).find((x) => x.id === pid); if (p) p.models = (p.models || []).concat([Object.assign({ id: uid('m'), model: '' }, kind === 'tts' ? { voice: 'alloy' } : {})]); });
19530
19548
  const patchModel = (pid, mid, k, v) => mutate((d) => { const p = (d[listKey] || []).find((x) => x.id === pid); if (!p) return; p.models = (p.models || []).map((x) => (x.id === mid ? { ...x, [k]: v } : x)); });
19531
19549
  const removeModel = (pid, mid) => mutate((d) => {
19532
19550
  const p = (d[listKey] || []).find((x) => x.id === pid); if (!p) return;
@@ -19571,6 +19589,11 @@ const DIRECTOR_KEY_HELP = [
19571
19589
  ) : null,
19572
19590
  h(Field, { key: 'u', label: T('baseUrl'), value: p[urlKey] || '', onChange: (v) => patchProvider(p.id, urlKey, v), placeholder: kind === 'video' ? ((VIDEO_VENDORS[detectVideoVendor(p)] || {}).base || urlPh) : urlPh }),
19573
19591
  h(Field, { key: 'k', label: T('apiKey'), value: p.apiKey || '', onChange: (v) => patchProvider(p.id, 'apiKey', v), placeholder: kind === 'video' ? ((VIDEO_VENDORS[detectVideoVendor(p)] || {}).keyPh || 'sk-…') : 'sk-…', password: true }),
19592
+ kind === 'tts' ? h(Field, {
19593
+ key: 'to', label: T('apiTimeout'), value: p.timeoutMs || '',
19594
+ placeholder: '留空 = 120000',
19595
+ onChange: (v) => patchProvider(p.id, 'timeoutMs', v),
19596
+ }) : null,
19574
19597
  kind === 'image' ? [
19575
19598
  h(Field, { key: 'size', label: T('imgSizeOverride'), value: p.size || '', onChange: (v) => patchProvider(p.id, 'size', v), placeholder: T('imgSizePlaceholder') }),
19576
19599
  h(Field, { key: 'rf', label: T('imgResponseFormat'), value: p.responseFormat || '', onChange: (v) => patchProvider(p.id, 'responseFormat', v), placeholder: 'b64_json / url(留空=API 默认)' }),
@@ -19581,12 +19604,12 @@ const DIRECTOR_KEY_HELP = [
19581
19604
  h('option', { value: 'edits' }, T('modeEdits')),
19582
19605
  h('option', { value: 'compshare' }, T('modeCompshare')),
19583
19606
  h('option', { value: 'sanbao' }, T('modeSanbao')))),
19584
- ] : [
19607
+ ] : kind === 'video' ? [
19585
19608
  (detectVideoVendor(p) === 'openai' || detectVideoVendor(p) === 'seedance') ? h(Field, { key: 'of', label: T('vidOutFormat'), value: p.outputFormat || '', onChange: (v) => patchProvider(p.id, 'outputFormat', v), placeholder: 'mp4(留空不发送)' }) : null,
19586
19609
  (detectVideoVendor(p) === 'openai' || detectVideoVendor(p) === 'seedance') ? h('label', { key: 'ga', className: 'dshic-row', style: { gap: 6, fontSize: 11 } },
19587
19610
  h('input', { type: 'checkbox', checked: p.generateAudio === true, onChange: (e) => patchProvider(p.id, 'generateAudio', e.target.checked), onPointerDown: (e) => e.stopPropagation() }),
19588
19611
  h('span', {}, T('vidAudioOpt'))) : null,
19589
- ],
19612
+ ] : null,
19590
19613
  (kind === 'image' || kind === 'video') ? [
19591
19614
  h(Field, { key: 'extra', label: T('cfgExtra'), value: p.extra || '', onChange: (v) => patchProvider(p.id, 'extra', v), placeholder: '{"watermark":false,"prompt_extend":false}', tip: T('cfgExtraHint') }),
19592
19615
  ] : null,
@@ -19601,6 +19624,8 @@ const DIRECTOR_KEY_HELP = [
19601
19624
  onPointerDown: (e) => e.stopPropagation(), onClick: () => toggleStar(p.id, m.id),
19602
19625
  }, s[starKey] === p.id + '|' + m.id ? '★' : '☆'),
19603
19626
  h('input', { className: 'dshic-input', style: { flex: 1, minWidth: 0 }, value: m.model || '', placeholder: T('modelNamePh'), onChange: (e) => patchModel(p.id, m.id, 'model', e.target.value), onPointerDown: (e) => e.stopPropagation() }),
19627
+ // TTS:voice 每模型一个(修复旧 ApiListEditor「voice 无编辑入口」的原始缺口)
19628
+ kind === 'tts' ? h('input', { className: 'dshic-input', style: { flex: 1, minWidth: 0 }, value: m.voice || '', placeholder: 'alloy', 'aria-label': T('voice'), onChange: (e) => patchModel(p.id, m.id, 'voice', e.target.value), onPointerDown: (e) => e.stopPropagation() }) : null,
19604
19629
  h('button', { type: 'button', className: 'dshic-iconbtn', title: T('doDelete'), onPointerDown: (e) => e.stopPropagation(), onClick: () => removeModel(p.id, m.id) }, '×'),
19605
19630
  )),
19606
19631
  !(p.models || []).length ? h('div', { className: 'dshic-hint' }, T('noModelsCfg')) : null,
@@ -19609,158 +19634,6 @@ const DIRECTOR_KEY_HELP = [
19609
19634
  }),
19610
19635
  );
19611
19636
  }
19612
- function ApiListEditor({ kind }) {
19613
- const [s, setS] = useState(loadSettings);
19614
- const [openId, setOpenId] = useState(null);
19615
- const listKey = kind === 'image' ? 'imageApis' : kind === 'video' ? 'videoApis' : 'ttsApis';
19616
- const defKey = kind === 'image' ? 'imageApiId' : kind === 'video' ? 'videoApiId' : 'ttsApiId';
19617
- const labelKey = kind === 'image' ? 'imageApisLabel' : kind === 'video' ? 'videoApisLabel' : 'ttsApisLabel';
19618
- const icon = kind === 'image' ? 'image' : kind === 'video' ? 'video' : 'audio';
19619
- const nameKey = kind === 'image' ? 'defaultImageCfg' : kind === 'video' ? 'defaultVideoCfg' : 'defaultTtsCfg';
19620
- const persist = (next) => { setS(next); saveSettings(next); };
19621
- const mutate = (fn) => {
19622
- const next = JSON.parse(JSON.stringify(s));
19623
- next[listKey] = fn(next[listKey] || []);
19624
- persist(next);
19625
- };
19626
- const add = () => {
19627
- const id = uid('cfg');
19628
- mutate((list) => list.concat([{
19629
- id,
19630
- name: T(nameKey) + ' ' + ((s[listKey] || []).length + 1),
19631
- [kcUrlKey(kind)]: '',
19632
- apiKey: '',
19633
- model: '',
19634
- ...(kind === 'image' ? { mode: 'generations' } : {}),
19635
- ...(kind === 'tts' ? { voice: 'alloy' } : {}),
19636
- }]));
19637
- setOpenId(id);
19638
- };
19639
- const patch = (id, k, v) => mutate((list) => list.map((x) => (x.id === id ? { ...x, [k]: v } : x)));
19640
- const remove = (id) => {
19641
- mutate((list) => list.filter((x) => x.id !== id));
19642
- if (openId === id) setOpenId(null);
19643
- };
19644
- const list = s[listKey] || [];
19645
- const urlPh = kind === 'image' ? 'https://api.example.com/v1' : kind === 'video' ? 'https://api.example.com/v1/video/generations' : 'https://api.example.com/v1';
19646
- const urlKey = kind === 'image' ? 'baseUrl' : 'url';
19647
- return h('div', { className: 'dshic-card' },
19648
- h('div', { className: 'dshic-row' },
19649
- Ic(icon, 12),
19650
- h('strong', { style: { fontSize: 12, flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }, T(labelKey)),
19651
- h('span', { className: 'dshic-tag st' }, String(list.length)),
19652
- h('button', { type: 'button', className: 'dshic-mini', onClick: add, onPointerDown: (e) => e.stopPropagation() }, Ic('plus', 11), T('addConfig')),
19653
- ),
19654
- list.length === 0 ? h('div', { className: 'dshic-hint' }, T('noCfgHint')) : null,
19655
- list.map((cfg) => {
19656
- const open = openId === cfg.id;
19657
- const isDef = s[defKey] === cfg.id;
19658
- return h('div', { key: cfg.id, className: 'dshic-card', style: { padding: open ? 8 : 5, gap: 6, background: 'var(--dsw-alias-bg-layer-1)' } },
19659
- // 折叠头:箭头 + 名称 + 默认标记 + 删除
19660
- h('div', { className: 'dshic-row' },
19661
- h('button', {
19662
- type: 'button', className: 'dshic-iconbtn', title: open ? T('collapse') : T('unfold'),
19663
- onPointerDown: (e) => e.stopPropagation(),
19664
- onClick: () => setOpenId(open ? null : cfg.id),
19665
- }, open ? '▾' : '▸'),
19666
- open
19667
- ? h('input', {
19668
- className: 'dshic-input', style: { flex: 1, minWidth: 0, fontWeight: 600 }, value: cfg.name || '',
19669
- placeholder: T('cfgName'), autoFocus: true,
19670
- onChange: (e) => patch(cfg.id, 'name', e.target.value),
19671
- onPointerDown: (e) => e.stopPropagation(),
19672
- })
19673
- : h('span', {
19674
- style: { flex: 1, minWidth: 0, fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', cursor: 'pointer', color: 'var(--dsw-alias-label-primary)' },
19675
- onClick: () => setOpenId(cfg.id),
19676
- onPointerDown: (e) => e.stopPropagation(),
19677
- title: T('baseUrl') + ': ' + (cfg[kcUrlKey(kind)] || '—'),
19678
- }, cfg.name || T('cfgName')),
19679
- isDef
19680
- ? h('span', { className: 'dshic-tag api' }, T('isDefault'))
19681
- : h('button', {
19682
- type: 'button', className: 'dshic-mini is-ghost', title: T('setDefault'),
19683
- onPointerDown: (e) => e.stopPropagation(),
19684
- onClick: () => { const next = { ...s, [defKey]: cfg.id }; persist(next); },
19685
- }, '★'),
19686
- cfg.model ? h('span', { className: 'dshic-tag st' }, String(cfg.model).slice(0, 18)) : null,
19687
- h('button', {
19688
- type: 'button', className: 'dshic-iconbtn is-danger', title: T('delConfig'),
19689
- onPointerDown: (e) => e.stopPropagation(),
19690
- onClick: () => remove(cfg.id),
19691
- }, Ic('trash', 11)),
19692
- ),
19693
- open ? [
19694
- h(Field, { key: 'u', label: T('baseUrl'), value: cfg[kcUrlKey(kind)] || '', onChange: (v) => patch(cfg.id, urlKey, v), placeholder: urlPh }),
19695
- h(Field, { key: 'k', label: T('apiKey'), value: cfg.apiKey || '', onChange: (v) => patch(cfg.id, 'apiKey', v), placeholder: 'sk-…', password: true }),
19696
- h(Field, { key: 'm', label: T('model'), value: cfg.model || '', onChange: (v) => patch(cfg.id, 'model', v) }),
19697
- h(Field, {
19698
- key: 'to', label: T('apiTimeout'), value: cfg.timeoutMs || '',
19699
- placeholder: T('llmParamAuto'),
19700
- onChange: (v) => patch(cfg.id, 'timeoutMs', v),
19701
- }),
19702
- kind === 'image'
19703
- ? h(Field, { key: 'size', label: T('imgSizeOverride'), value: cfg.size || '', onChange: (v) => patch(cfg.id, 'size', v), placeholder: T('imgSizePlaceholder') })
19704
- : null,
19705
- kind === 'image'
19706
- ? h(Field, { key: 'rf', label: T('imgResponseFormat'), value: cfg.responseFormat || '', onChange: (v) => patch(cfg.id, 'responseFormat', v), placeholder: 'b64_json / url(留空=API 默认)' })
19707
- : null,
19708
- kind === 'image'
19709
- ? h('div', { key: 'mode', className: 'dshic-field' },
19710
- h('span', { className: 'dshic-field-label' }, T('imgMode')),
19711
- h('select', {
19712
- className: 'dshic-select', value: cfg.mode || 'generations',
19713
- onChange: (e) => patch(cfg.id, 'mode', e.target.value),
19714
- onPointerDown: (e) => e.stopPropagation(),
19715
- },
19716
- h('option', { value: 'generations' }, T('modeGenerations')),
19717
- h('option', { value: 'edits' }, T('modeEdits')),
19718
- h('option', { value: 'sanbao' }, T('modeSanbao'))))
19719
- : null,
19720
- kind === 'video'
19721
- ? h('div', { key: 'proto', className: 'dshic-field' },
19722
- h('span', { className: 'dshic-field-label' }, T('vidProtocol'), InfoTip(T('vidProtocolHint'))),
19723
- h('select', {
19724
- className: 'dshic-select', value: cfg.protocol || 'generic',
19725
- onChange: (e) => patch(cfg.id, 'protocol', e.target.value),
19726
- onPointerDown: (e) => e.stopPropagation(),
19727
- },
19728
- h('option', { value: 'generic' }, T('protoGeneric')),
19729
- h('option', { value: 'seedance' }, T('protoSeedance'))))
19730
- : null,
19731
- kind === 'video'
19732
- ? h('label', { key: 'ga', className: 'dshic-row', style: { gap: 6, fontSize: 11 } },
19733
- h('input', {
19734
- type: 'checkbox', checked: cfg.generateAudio === true,
19735
- onChange: (e) => patch(cfg.id, 'generateAudio', e.target.checked),
19736
- onPointerDown: (e) => e.stopPropagation(),
19737
- }),
19738
- h('span', {}, T('vidAudioOpt')))
19739
- : null,
19740
- kind === 'video'
19741
- ? h(Field, { key: 'of', label: T('vidOutFormat'), value: cfg.outputFormat || '', onChange: (v) => patch(cfg.id, 'outputFormat', v), placeholder: 'mp4(留空不发送)' })
19742
- : null,
19743
- kind === 'video' && cfg.protocol === 'seedance'
19744
- ? h('label', { key: 'wm', className: 'dshic-row', style: { gap: 6, fontSize: 11 } },
19745
- h('input', {
19746
- type: 'checkbox', checked: cfg.watermark === true,
19747
- onChange: (e) => patch(cfg.id, 'watermark', e.target.checked),
19748
- onPointerDown: (e) => e.stopPropagation(),
19749
- }),
19750
- h('span', {}, T('seedanceWatermark')))
19751
- : null,
19752
- (kind === 'image' || kind === 'video')
19753
- ? h(Field, { key: 'extra', label: T('cfgExtra'), value: cfg.extra || '', onChange: (v) => patch(cfg.id, 'extra', v), placeholder: '{"watermark":false,"prompt_extend":false}', tip: T('cfgExtraHint') })
19754
- : null,
19755
- kind === 'tts'
19756
- ? h(Field, { key: 'voice', label: T('voice'), value: cfg.voice || '', onChange: (v) => patch(cfg.id, 'voice', v), placeholder: 'alloy' })
19757
- : null,
19758
- ] : null,
19759
- );
19760
- }),
19761
- );
19762
- }
19763
- function kcUrlKey(kind) { return kind === 'image' ? 'baseUrl' : 'url'; }
19764
19637
 
19765
19638
  /** T2:设置面板 Craft 后期卡片(连接状态 / 工具灯 / 数据目录)。 */
19766
19639
  function CraftCard() {
@@ -20316,7 +20189,8 @@ const DIRECTOR_KEY_HELP = [
20316
20189
  list.unshift({ id: 'image-gen-bridge', name: '桥接dsh-image-gen', baseUrl: '', apiKey: '', viaImageGen: true, models });
20317
20190
  }
20318
20191
  const noChange = JSON.stringify(s0.imageProviders || []) === JSON.stringify(list);
20319
- if (!noChange) { s0.imageProviders = list; saveSettings(s0); }
20192
+ // issue #6:写回统一走 updateSettings(现取磁盘最新做基底,杜绝把别的卡刚写的字段回滚)
20193
+ if (!noChange) updateSettings((b) => ({ ...b, imageProviders: list }));
20320
20194
  return { models: models.length, changed: !noChange };
20321
20195
  };
20322
20196
  useEffect(() => {
@@ -20341,9 +20215,8 @@ const DIRECTOR_KEY_HELP = [
20341
20215
  const toggle = () => {
20342
20216
  const v = !enabled;
20343
20217
  setEnabled(v);
20344
- const s0 = loadSettings();
20345
- s0.imageGen = { ...(s0.imageGen || {}), enabled: v };
20346
- saveSettings(s0);
20218
+ // issue #6:写回统一走 updateSettings(现取磁盘最新做基底)
20219
+ updateSettings((b) => ({ ...b, imageGen: { ...(b.imageGen || {}), enabled: v } }));
20347
20220
  // 开/关即时生效:重跑一次探测同步(加回或移除桥接模型条目)
20348
20221
  (async () => {
20349
20222
  try {
@@ -20374,12 +20247,8 @@ const DIRECTOR_KEY_HELP = [
20374
20247
  function SettingsTab() {
20375
20248
  const [s, setS] = useState(loadSettings);
20376
20249
  const apply = (fn) => {
20377
- setS((prev) => {
20378
- const next = JSON.parse(JSON.stringify(prev));
20379
- fn(next);
20380
- saveSettings(next);
20381
- return next;
20382
- });
20250
+ // issue #6:与四张卡同根——基底现取磁盘最新,不再用挂载快照整对象写回
20251
+ setS(updateSettings((b) => { const d = JSON.parse(JSON.stringify(b)); fn(d); return d; }));
20383
20252
  };
20384
20253
  const field = (label, value, onChange, placeholder, password) => h(Field, { label, value, onChange, placeholder, password });
20385
20254
  return [
@@ -20414,7 +20283,7 @@ const DIRECTOR_KEY_HELP = [
20414
20283
  ),
20415
20284
  h(ModelProviderEditor, { key: 'imglist', kind: 'image' }),
20416
20285
  h(ModelProviderEditor, { key: 'vidlist', kind: 'video' }),
20417
- h(ApiListEditor, { key: 'ttslist', kind: 'tts' }),
20286
+ h(ModelProviderEditor, { key: 'ttslist', kind: 'tts' }),
20418
20287
  // 帮助与反馈:一行入口(点开弹窗看二维码与提 Issue)
20419
20288
  h('div', {
20420
20289
  key: 'support', className: 'dshic-card', style: { cursor: 'pointer' },
@@ -22372,9 +22241,11 @@ const DIRECTOR_KEY_HELP = [
22372
22241
  window.__DSH_IC_CRAFT__ = { craftBaseDir, craftBaseDirRequired, joinLocal, craftFolderOf, craft };
22373
22242
  // 设置迁移的测试缝隙
22374
22243
  window.__DSH_IC_SETTINGS__ = {
22375
- DEFAULT_SETTINGS, loadSettings, saveSettings,
22376
- flattenImageModels, resolveImageModelCfg,
22244
+ DEFAULT_SETTINGS, loadSettings, saveSettings, updateSettings,
22245
+ flattenImageModels, flattenTtsModels, resolveImageModelCfg,
22377
22246
  buildExpertContext,
22247
+ // 设置卡组件缝合口(跨卡丢失更新回归用,scripts/test-panel-layout.mjs;不进 __DSH_IC_TABS__,smoke 会遍历渲染)
22248
+ LlmModelSelect, ModelProviderEditor,
22378
22249
  };
22379
22250
  // 创作上下文注入的测试缝隙(供 scripts/test-skill-inject.mjs 断言)
22380
22251
  window.__DSH_IC_SKILL__ = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ninkch/dsh-infinite-canvas",
3
- "version": "0.20.2",
3
+ "version": "0.20.3",
4
4
  "description": "无限画布(Infinite Canvas)for DeepSeek Harness:节点式创作工作室(剧本/分镜/生成/成片),内置「媒体创作」预设模式(导演第一视角 + 引导工作坊)。Version-agnostic: reads the live catalog from the installed package at load time.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -40,6 +40,7 @@
40
40
  "index.js",
41
41
  "client.js",
42
42
  "production.js",
43
+ "shot-segments.js",
43
44
  "icon.svg",
44
45
  "cordis.patch.yml",
45
46
  "locale/*.json",
@@ -0,0 +1,233 @@
1
+ /**
2
+ * @ninkch/dsh-infinite-canvas — 按镜头切段(宿主侧权威估算器,0.20.2)
3
+ *
4
+ * 本模块是 client.js 里 planShotSegments 的**逐字移植**(零 npm 依赖的纯函数 ES module):
5
+ * - shotVisualText ← client.js L4189-4192
6
+ * - shotContinuityPlan ← client.js L4201-4249
7
+ * - isCutPoint ← client.js L4368-4370
8
+ * - planShotSegments ← client.js L4389-4514
9
+ *
10
+ * 为什么必须逐字:真实视频调用次数由客户端切段决定(client.js expandStoryboard /
11
+ * StoryboardNodeBody 都以 `planShotSegments(shots, { maxSeconds: Number(n.data.segMaxSeconds) || 15 })`
12
+ * 的结果为准——一个分镜表 ≠ 一次生成)。宿主预算单(production.js quote)按这里的输出
13
+ * 估算 videoCalls;任何语义简化都会让预算再次失真(#8:显示 4 次、实际 14 次)。
14
+ *
15
+ * 同步契约:改动 client.js 的切段算法时必须同步本文件,反之亦然。
16
+ * 漂移守卫:scripts/test-quote-segments.mjs 用 vm 加载真实 client.js,把
17
+ * window.__DSH_IC_SEGMENT__.planShotSegments 与本模块在同一组 fixtures 上断言输出一致——
18
+ * 宿主估算与客户端执行漂移 = 预算单再次失真,测试红了就必须人工对齐两端。
19
+ */
20
+
21
+ /** 镜头画面文本(visual + motion),用于衔接描述与相似度兜底。 */
22
+ function shotVisualText(sh) {
23
+ if (!sh) return '';
24
+ return [String(sh.visual || '').trim(), String(sh.motion || '').trim()].filter(Boolean).join(';');
25
+ }
26
+ /**
27
+ * 镜头衔接规划:把「尾部状态 / 起始状态 / 运镜延续 / 段落类型 / 接缝档位」统一解出来。
28
+ * 分镜字段可手写(tail/start/cam),缺失时用 visual 兜底——**绝不编造剧情**,只做"能确认的推断"。
29
+ * seg: 'opening'(首段,交代)| 'continuation'(续帧,默认)| 'new_character'(新角色入场,参考图模式)
30
+ * | 'scene_change'(换场,不接尾帧)| 'closeup'(特写/细节插入,接缝不被画面盯着看 → 标准放宽)
31
+ * join: 'strict'(同步长硬接)| 'loose'(跨场/换景,允许软接)| 'cut'(特写插入,跳切合理,不接力)
32
+ * @returns {{seg,name,join,fromTail,fromShot,tail,start,cam,chain,note}}
33
+ */
34
+ function shotContinuityPlan(sh, prev, idx) {
35
+ const s = sh || {};
36
+ const i = Number.isFinite(Number(idx)) ? Number(idx) : 0;
37
+ const prevShot = i > 0 ? (prev || null) : null;
38
+ const segRaw = String(s.seg || '').trim().toLowerCase();
39
+ const SEG_ALIAS = {
40
+ opening: 'opening', open: 'opening', '首段': 'opening', '开场': 'opening',
41
+ continuation: 'continuation', cont: 'continuation', '续': 'continuation', '续帧': 'continuation', '承接': 'continuation',
42
+ new_character: 'new_character', newchar: 'new_character', '新角色': 'new_character', '入场': 'new_character',
43
+ scene_change: 'scene_change', scene: 'scene_change', '换场': 'scene_change', '转场': 'scene_change',
44
+ closeup: 'closeup', insert: 'closeup', '特写': 'closeup', '插入': 'closeup',
45
+ // 同机位状态跳变:切前不在/切后在(灯闪现身、影子凭空在场、影化实)——奇幻特效叙事的合法段落
46
+ state_jump: 'state_jump', jump: 'state_jump', '跳变': 'state_jump', '状态跳变': 'state_jump',
47
+ };
48
+ let seg = SEG_ALIAS[segRaw] || '';
49
+ const boxed = (k) => String(s[k] || '').trim();
50
+ if (!seg) {
51
+ if (!prevShot) seg = 'opening';
52
+ else if (/换场|场景切换|转场|另一处|另一场景|切至|切到|次日|翌日|与此同时|数日后|[Cc]ut to/.test(shotVisualText(s))) seg = 'scene_change';
53
+ else if (/新角色|首次出场|走进来|入镜|入场|冒出|推门进|[Ee]nters?/.test(shotVisualText(s))) seg = 'new_character';
54
+ else if (Number(s.duration) > 0 && Number(s.duration) < 1.5 && !(s.dialogue || []).length) seg = 'closeup';
55
+ else seg = 'continuation';
56
+ }
57
+ if (seg === 'opening' && prevShot) seg = 'continuation'; // 首段只能在第 1 镜;后面标"开场"视为续帧
58
+ // 接缝档位:换场/新角色入场都放宽(新角色段本就不承接上段画面),特写插入与状态跳变允许跳切
59
+ const join = (seg === 'scene_change' || seg === 'new_character') ? 'loose' : (seg === 'closeup' || seg === 'state_jump') ? 'cut' : 'strict';
60
+ // 只有真正需要画面承接的段落才接力尾帧;新角色入场首帧若来自上一段,新角色反而无从进入
61
+ const chain = seg === 'continuation' && !!prevShot;
62
+ // ownTail = 本镜的接点尾态(留给**下一镜**);cam = 本镜运镜(同样留给下一镜延续)
63
+ const tail = boxed('tail');
64
+ const cam = boxed('cam');
65
+ // prevTail = **上一镜**的接点尾态 = 本镜的起始态(衔接块要引用的是它,不是本镜自己的 tail)。
66
+ // 旧分镜没写 tail 时退到上一镜的「最后动作」——诚实标注来源,而不是拿本镜画面冒充。
67
+ let prevTail = '';
68
+ let prevTailSource = '';
69
+ if (prevShot) {
70
+ const pt = String(prevShot.tail || '').trim();
71
+ const pm = String(prevShot.motion || '').trim();
72
+ if (pt) { prevTail = pt; prevTailSource = 'tail'; }
73
+ else if (pm) { prevTail = pm; prevTailSource = 'motion'; }
74
+ }
75
+ const start = boxed('start');
76
+ return {
77
+ idx: i, seg, join, fromTail: i > 0, fromShot: i > 0, chain,
78
+ name: String(s.title || '').trim(),
79
+ tail, cam, start, prevTail, prevTailSource,
80
+ note: boxed('note'),
81
+ };
82
+ }
83
+ /** 该 seg 是否构成一个"可以安全开始新生成段"的切点。opening 只在全表第 1 镜成立。
84
+ * state_jump(同机位状态跳变)也是合法切点:跳变本身就是"切"——前后镜只差状态、不接动作。 */
85
+ function isCutPoint(seg) {
86
+ return seg === 'scene_change' || seg === 'closeup' || seg === 'new_character' || seg === 'opening' || seg === 'state_jump';
87
+ }
88
+ /**
89
+ * 把一张分镜表的镜头按「真实镜头边界」切成若干生成段。
90
+ *
91
+ * @param shots 分镜镜头数组(data.shots)
92
+ * @param opts { maxSeconds(单次生成上限,默认 15), minSeconds(单段下限,默认 2),
93
+ * hardMax(厂商物理上限,超了必须拆,默认同 maxSeconds) }
94
+ * @returns {{ segments: Array, total: number, max: number, cutMode: string, warnings: string[] }}
95
+ * segments[i] = {
96
+ * index, shotIds, shots, startIndex, endIndex,
97
+ * duration, // 本段总时长(秒,一位小数)
98
+ * firstSeg, lastSeg, // 本段首/末镜的段落类型
99
+ * opensOnCut, // 本段是否从一个合法切点开始(第 1 段恒真)
100
+ * closesOnCut, // 本段末镜是否本身就是"换镜头"(=下一段天然切点,无需接力)
101
+ * seamRisk, // 'none' | 'chain'(靠尾帧接力)| 'forced'(找不到切点被硬切)
102
+ * needsTailChain, // 是否需要把上一段尾帧接到本段首帧
103
+ * reason, // 人类可读的切段依据(面板上显示)
104
+ * }
105
+ */
106
+ function planShotSegments(shots, opts) {
107
+ const o = opts || {};
108
+ const list = (Array.isArray(shots) ? shots : []).filter((s) => s && (String(s.visual || '').trim() || String(s.motion || '').trim() || (Array.isArray(s.dialogue) && s.dialogue.length)));
109
+ const maxSeconds = Math.max(1, Number(o.maxSeconds) || 15);
110
+ const minSeconds = Math.max(0, Math.min(Number(o.minSeconds) || 2, maxSeconds));
111
+ const warnings = [];
112
+ const durOf = (s) => Math.max(0.3, Math.round((Number(s && s.duration) || 3) * 10) / 10);
113
+ // 预解每镜的段落类型(与 shotContinuityPlan 同一套推断,保证分段与提示词口径一致)
114
+ const plans = list.map((s, i) => shotContinuityPlan(s, list[i - 1] || null, i));
115
+ const total = Math.round(list.reduce((a, s) => a + durOf(s), 0) * 10) / 10;
116
+ if (!list.length) return { segments: [], total: 0, max: maxSeconds, cutMode: 'empty', warnings: ['分镜表里没有可用镜头'] };
117
+
118
+ /** 从 from 开始贪心找到一个"可以在 to 前断开"的位置:
119
+ * 返回该段的结束下标(含);-1 表示从 from 开始连第一镜都放不下。 */
120
+ const findBreak = (from) => {
121
+ let acc = 0;
122
+ let bestCut = -1; // 最近一次合法切点之后的位置(即"下一镜是新镜头"的下标)
123
+ for (let i = from; i < list.length; i++) {
124
+ const d = durOf(list[i]);
125
+ if (acc + d > maxSeconds + 1e-6) {
126
+ // 放不下了。若当前累计还没超过下限,也要至少吃一镜(单镜超长的情况由下面兜底)
127
+ break;
128
+ }
129
+ acc += d;
130
+ // 判断"i 之后可以断开":下一镜是切点,或本镜本身就是换镜头(切在它之后)
131
+ const nextIsCut = i + 1 < list.length && isCutPoint(plans[i + 1] && plans[i + 1].seg);
132
+ const thisIsCut = isCutPoint(plans[i] && plans[i].seg);
133
+ // 切点镜的正确归属:**下一段的首镜**。
134
+ // 旧写法 thisIsCut → bestCut = i,把换场/特写镜留在本段末尾,下一段只能从它后面那一镜(多半是
135
+ // continuation)开始 → 必然报"从镜中开始"的硬切。修好后:i>from 时断在 i-1,让切点镜去开新段。
136
+ if (nextIsCut) bestCut = i;
137
+ else if (thisIsCut) bestCut = i > from ? i - 1 : i;
138
+ if (i === list.length - 1) bestCut = i;
139
+ }
140
+ if (bestCut < from) {
141
+ // 连一镜都塞不进上限:退化为"只取这一镜",交给下面标记 forced
142
+ return { end: from, forced: true, acc: durOf(list[from]) };
143
+ }
144
+ return { end: bestCut, forced: false, acc };
145
+ };
146
+
147
+ const segments = [];
148
+ let i = 0;
149
+ let warnMark = warnings.length;
150
+ while (i < list.length && segments.length < 128) {
151
+ // 段首必须是切点;若不是(说明上一段是被 forced 断开的),本镜保持原 seg
152
+ warnMark = warnings.length;
153
+ const brk = findBreak(i);
154
+ let end = brk.end;
155
+ let seamRisk = 'none';
156
+ let reason = '';
157
+ const firstSeg = (plans[i] && plans[i].seg) || 'continuation';
158
+ const opensOnCut = segments.length === 0 || isCutPoint(firstSeg);
159
+ if (!opensOnCut) {
160
+ seamRisk = 'forced';
161
+ reason = '上一段超长被迫硬切,本段从镜中断点继续,动作相位可能不连续';
162
+ warnings.push(`第 ${i + 1} 镜起的一段是硬切(上一段超长且找不到换镜头切点):这一段与上一段的接缝只能靠尾帧+提示词硬接`);
163
+ }
164
+ // 段内若含"必须承接"的 continuation,且不是首段、且首镜也不是切点 → 需要尾帧接力
165
+ const needsTailChain = segments.length > 0 && !isCutPoint(firstSeg);
166
+ if (needsTailChain) {
167
+ seamRisk = seamRisk === 'forced' ? 'forced' : 'chain';
168
+ reason = reason || '本段首镜是续帧镜头,需用上一段尾帧接力';
169
+ }
170
+ const segShots = list.slice(i, end + 1);
171
+ const duration = Math.round(segShots.reduce((a, s) => a + durOf(s), 0) * 10) / 10;
172
+ const lastSeg = (plans[end] && plans[end].seg) || 'continuation';
173
+ const closesOnCut = isCutPoint(lastSeg) || end === list.length - 1;
174
+ if (!reason) {
175
+ reason = closesOnCut
176
+ ? '本段以换镜头收尾,下一段天然切换、无需接力'
177
+ : '本段在换镜头切点处开始';
178
+ }
179
+ segments.push({
180
+ index: segments.length,
181
+ shotIds: segShots.map((s, k) => i + k),
182
+ shots: segShots,
183
+ startIndex: i,
184
+ endIndex: end,
185
+ duration,
186
+ firstSeg,
187
+ lastSeg,
188
+ opensOnCut,
189
+ closesOnCut,
190
+ seamRisk,
191
+ needsTailChain,
192
+ reason,
193
+ warnMark,
194
+ });
195
+ if (end === i && brk.forced) {
196
+ warnings.push(`第 ${i + 1} 镜单镜时长 ${durOf(list[i])}s 已超单次生成上限 ${maxSeconds}s:这一段只能单独生成,并期望厂商钳制或报错`);
197
+ }
198
+ i = end + 1;
199
+ }
200
+ // 尾部碎段并回上一段:把 20.8s 切成「19.8 + 1.0」既没意义又必然误报硬切(1 秒那段一定从镜中开始)。
201
+ // 只有"末段很短且并回去只超上限一点点"才合并;中段碎块不动,避免掩盖真正的切点问题。
202
+ if (segments.length > 1) {
203
+ const last = segments[segments.length - 1];
204
+ const prev = segments[segments.length - 2];
205
+ const tol = Math.max(0.6, maxSeconds * 0.1);
206
+ const tinyTail = last.duration <= Math.max(2.5, maxSeconds * 0.2);
207
+ const fits = (prev.duration + last.duration) <= maxSeconds + tol;
208
+ if (tinyTail && fits) {
209
+ warnings.length = last.warnMark; // 丢弃为这一段产生的告警(它已不存在)
210
+ prev.shots = prev.shots.concat(last.shots);
211
+ prev.endIndex = last.endIndex;
212
+ prev.shotIds = prev.shots.map((x, k) => prev.startIndex + k);
213
+ prev.duration = Math.round((prev.duration + last.duration) * 10) / 10;
214
+ prev.lastSeg = last.lastSeg;
215
+ prev.closesOnCut = last.closesOnCut;
216
+ segments.pop();
217
+ warnings.push(`末段只有 ${last.duration}s,已并回上一段(合并后 ${prev.duration}s,超出单次上限 ${Math.round((prev.duration - maxSeconds) * 10) / 10}s 以内):比切出一个 1 秒的碎片更好生成`);
218
+ }
219
+ }
220
+
221
+ // cutMode:整表能不能被整齐切成"每次都是换镜头"的段——决定要不要提示用户重拆分镜
222
+ const cleanCuts = segments.every((s) => s.opensOnCut);
223
+ const cutMode = cleanCuts ? 'clean' : 'forced';
224
+ if (cutMode === 'forced') {
225
+ warnings.push('本次切段存在硬切点:建议把超长的续帧段在分镜里拆成两镜(第二镜标换场/特写插入),让切点落在真实镜头上');
226
+ }
227
+ if (segments.length > 1 && !cleanCuts) {
228
+ warnings.push(`共 ${segments.length} 段,其中 ${segments.filter((s) => !s.opensOnCut).length} 段从镜中断点开始——弱衔接模型(如 MiniMax)对这些段会明显吃力`);
229
+ }
230
+ return { segments, total, max: maxSeconds, cutMode, warnings };
231
+ }
232
+
233
+ export { planShotSegments, isCutPoint, shotContinuityPlan, shotVisualText };