5902 lines
258 KiB
JavaScript
5902 lines
258 KiB
JavaScript
import { app } from "../../../scripts/app.js";
|
||
import { api } from "../../../scripts/api.js";
|
||
import { openReferenceImageEditor } from "./o1keyReferenceImageEditor.js";
|
||
|
||
const NODE_TYPE = "O1keyImageGenerator";
|
||
const SAVE_NODE_TYPE = "O1keyImageSave";
|
||
const MAX_REFERENCES = 50;
|
||
const MAX_REQUEST_REFERENCES = 10;
|
||
const GENERATOR_MIN_SIZE = [500, 1025];
|
||
const GENERATOR_DENSE_MIN_HEIGHT = 1110;
|
||
const GENERATOR_BATCH_MIN_HEIGHT = 1215;
|
||
const GENERATOR_DENSE_BATCH_MIN_HEIGHT = 1300;
|
||
const GENERATOR_DEFAULT_SIZE = [560, 1035];
|
||
const PROMPT_DEFAULT_HEIGHT = 106;
|
||
const USE_NATIVE_LITEGRAPH_PARAMETERS = true;
|
||
const NATIVE_PARAMETER_WIDGETS = new Set([
|
||
"模型", "模型线路", "思考等级", "分辨率", "宽高比", "生图数量", "seed",
|
||
"质量", "输出格式", "缩放图片", "背景", "批量出图", "批量模式", "命名规则",
|
||
"filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms",
|
||
]);
|
||
const PROMPT_PLACEHOLDER = "描述你想生成的图片;多个提示词用独占一行的 --- 分隔;Seedream 图层拆分时可留空…";
|
||
const GENERATOR_OUTPUT_COUNT = 4;
|
||
const GENERATOR_LAYER_OUTPUT_COUNT = 3;
|
||
const SAVE_NODE_LAYOUT_SIZE = [300, 260];
|
||
const SAVE_NODE_LAYOUT_GAP_X = 50;
|
||
const SAVE_NODE_LAYOUT_ORIGIN_GAP_X = 70;
|
||
const SAVE_NODE_CHROME_FALLBACK = 140;
|
||
const SAVE_NODE_CHROME_VUE_FALLBACK = 96;
|
||
const SAVE_SLOT_GRID_NODE_INSET = 24;
|
||
const SAVE_SLOT_GRID_PADDING_BORDER = 14;
|
||
const SAVE_SLOT_GRID_GAP = 7;
|
||
const SAVE_PREVIEW_MIN_HEIGHT = 220;
|
||
const SAVE_PREVIEW_MAX_HEIGHT = 720;
|
||
const SAVE_PREVIEW_SIZE_LABEL_HEIGHT = 15;
|
||
const GENERATOR_CHROME_HEIGHT = 48;
|
||
const GENERATOR_PANEL_MIN_HEIGHT = GENERATOR_MIN_SIZE[1] - GENERATOR_CHROME_HEIGHT;
|
||
const GENERATOR_COMPACT_MIN_HEIGHT = 320;
|
||
const DOM_WIDGET_CHROME = 20;
|
||
const PANEL_CONTENT_GAP = 8;
|
||
const PANEL_CONTENT_PADDING = 18;
|
||
const ACTIONS_BASE_HEIGHT = 42;
|
||
const ACTIONS_STATUS_HEIGHT = 21;
|
||
const SETTLE_FIT_DELAYS = [60, 200, 600];
|
||
// computeSize() is re-derived from the laid-out DOM, so it reports the node height plus a
|
||
// small rounding offset. Fitting every offset re-laid the node out forever (1510 <-> 1528);
|
||
// a dead zone keeps repeated fits idempotent while still absorbing real row changes.
|
||
const GENERATOR_FIT_TOLERANCE = 24;
|
||
// A single resize event can never move the corner this far; anything larger is a stale
|
||
// gesture (menu click without a matching pointerup) rather than the user dragging.
|
||
const GENERATOR_DRAG_OVERSHOOT = 400;
|
||
// The pointer must have gone down on the node itself before a resize counts as a drag.
|
||
const GENERATOR_DRAG_MARGIN = 12;
|
||
const REFERENCE_LIGHTBOX_ID = "o1key-image-reference-lightbox";
|
||
const CANVAS_IMAGE_PICKER_ID = "o1key-canvas-image-picker";
|
||
const MODEL_OPTIONS = [
|
||
{ value: "Nano Banana 2.1", label: "Nano Banana 2.1", description: "快速,批量" },
|
||
{ value: "Nano Banana 2", label: "Nano Banana 2", description: "快速,批量" },
|
||
{ value: "Nano Banana Pro", label: "Nano Banana Pro", description: "高质量资产" },
|
||
{ value: "gpt-image-2.6-sunburst", label: "GPT Image 2.6 Sunburst", description: "精修,细节还原" },
|
||
{ value: "gpt-image-2.6-flare", label: "GPT Image 2.6 Flare", description: "快速出图" },
|
||
{ value: "gpt-image-2.5-sunburst", label: "GPT Image 2.5 Sunburst", description: "高质量,细节" },
|
||
{ value: "gpt-image-2.5-flare", label: "GPT Image 2.5 Flare", description: "快速,日常" },
|
||
{ value: "gpt-image-2", label: "GPT Image 2", description: "高质量,编辑" },
|
||
{ value: "Seedream 5.0 Pro", label: "Seedream 5.0 Pro", description: "高质量,参考图,分层" },
|
||
];
|
||
const RETIRED_MODEL_ALIASES = Object.freeze({
|
||
"Nano Banana 2 Lite": "Nano Banana 2",
|
||
"Nano Banana": "Nano Banana 2",
|
||
});
|
||
function normalizeUnifiedModel(value) {
|
||
const candidate = String(value ?? "").trim();
|
||
if (MODEL_OPTIONS.some((option) => option.value === candidate)) return candidate;
|
||
return RETIRED_MODEL_ALIASES[candidate] || "Nano Banana 2.1";
|
||
}
|
||
const ROUTES = [
|
||
{ value: "畅速", label: "特价", description: "便宜" },
|
||
{ value: "直连", label: "优质", description: "小贵" },
|
||
{ value: "专线", label: "企业", description: "贵" },
|
||
];
|
||
const THINKING_LEVEL_OPTIONS = [
|
||
{ value: "低", label: "低", description: "耗时低,智力低" },
|
||
{ value: "高", label: "高", description: "耗时高,智力高" },
|
||
];
|
||
const RESIZE_OPTIONS = [
|
||
{ value: "不缩放", label: "不缩放", description: "无大图" },
|
||
{ value: "智能缩放", label: "智能缩放", description: "有大图" },
|
||
];
|
||
const ALL_RESOLUTIONS = ["智能", "512", "1K", "2K", "4K"];
|
||
const GPT_RESOLUTIONS = ["智能", "1K", "2K", "4K"];
|
||
const GPT_RATIOS = ["智能", "1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16"];
|
||
const GPT_QUALITIES = ["高", "中", "低", "自动"];
|
||
const GPT_25_QUALITIES = [...GPT_QUALITIES, "超高", "最高"];
|
||
|
||
const GPT_COMPLEXITY_OPTIONS = [
|
||
{ value: "高", label: "高", description: "充分规划,耗时更长" },
|
||
{ value: "中", label: "中", description: "平衡规划与速度" },
|
||
{ value: "低", label: "低", description: "较少规划,速度优先" },
|
||
];
|
||
const GPT_COMPLEXITY_TO_LABEL = Object.freeze({
|
||
high: "高",
|
||
medium: "中",
|
||
low: "低",
|
||
高: "高",
|
||
中: "中",
|
||
低: "低",
|
||
});
|
||
function normalizeGptComplexityLabel(value) {
|
||
if (value == null || value === "") return "高";
|
||
return GPT_COMPLEXITY_TO_LABEL[value]
|
||
?? GPT_COMPLEXITY_TO_LABEL[String(value).toLowerCase()]
|
||
?? "高";
|
||
}
|
||
|
||
const GPT_IMAGE_COUNTS = Array.from({ length: 8 }, (_, index) => String(index + 1));
|
||
const GPT_OUTPUT_FORMATS = [
|
||
{ value: "jpeg", label: "JPEG", description: "不支持透明背景" },
|
||
{ value: "png", label: "PNG", description: "支持透明背景" },
|
||
{ value: "webp", label: "WebP", description: "支持透明背景" },
|
||
];
|
||
const GPT_26_EXTRA_OUTPUT_FORMATS = [
|
||
{ value: "svg", label: "SVG", description: "矢量,仅纯文生图" },
|
||
{ value: "gif", label: "GIF", description: "动图,仅纯文生图" },
|
||
];
|
||
const SEEDREAM_RESOLUTIONS = ["智能", "1K", "2K"];
|
||
const SEEDREAM_LAYER_RESOLUTIONS = ["智能", "1K", "1.5K", "2K"];
|
||
const SEEDREAM_RATIOS = ["智能", "1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "21:9"];
|
||
const SEEDREAM_OUTPUT_FORMATS = [
|
||
{ value: "png", label: "PNG", description: "无损输出" },
|
||
{ value: "jpeg", label: "JPEG", description: "较小文件" },
|
||
];
|
||
const SEEDREAM_REFERENCE_LIMITS = Object.freeze({
|
||
maxBytes: 30 * 1024 * 1024,
|
||
minSideExclusive: 14,
|
||
minLayerPixels: 512 * 512,
|
||
maxPixels: 6000 * 6000,
|
||
minAspectRatio: 1 / 16,
|
||
maxAspectRatio: 16,
|
||
});
|
||
const SAVE_NAMING_RULES = [
|
||
{ value: "自定义前缀", label: "自定义", description: "使用文件名前缀" },
|
||
{ value: "和主图一致", label: "和主图一致", description: "沿用第1张参考图名称" },
|
||
{ value: "自然数字", label: "自然数字", description: "按 1、2、3… 命名" },
|
||
];
|
||
const SAVE_FORMATS = [
|
||
{ value: "原始", label: "原始", description: "保留模型返回格式" },
|
||
{ value: "png", label: "PNG", description: "无损转换" },
|
||
{ value: "jpg", label: "JPEG", description: "高质量有损转换" },
|
||
{ value: "webp", label: "WebP", description: "无损转换" },
|
||
];
|
||
const GPT_BACKGROUNDS = [
|
||
{ value: "auto", label: "自动", description: "由模型选择" },
|
||
{ value: "transparent", label: "透明", description: "仅 PNG / WebP" },
|
||
{ value: "opaque", label: "不透明", description: "生成实色背景" },
|
||
];
|
||
const IMAGE_COUNTS = ["1", "2", "4", "9"];
|
||
// Industry-neutral wording: 素材 = source assets, 目标 = targets to receive them.
|
||
const BATCH_MODE_GROUP_TO_TARGETS = "整组素材→多个目标";
|
||
const BATCH_MODE_ALL_PAIRS = "每张素材×每张目标";
|
||
const BATCH_MODE_SINGLE_REFERENCES = "每张素材单独出图";
|
||
const BATCH_MODE_VALUES = [
|
||
BATCH_MODE_GROUP_TO_TARGETS,
|
||
BATCH_MODE_ALL_PAIRS,
|
||
BATCH_MODE_SINGLE_REFERENCES,
|
||
];
|
||
// Workflows saved before the rename keep working: old labels map to the new ones.
|
||
const BATCH_MODE_ALIASES = new Map([
|
||
["一组搭配+多模特", BATCH_MODE_GROUP_TO_TARGETS],
|
||
["全部搭配×全部模特", BATCH_MODE_ALL_PAIRS],
|
||
["单图素材批量", BATCH_MODE_SINGLE_REFERENCES],
|
||
]);
|
||
const BATCH_MODE_OPTIONS = [
|
||
{ value: BATCH_MODE_GROUP_TO_TARGETS, label: "整组素材→多个目标", description: "整组共用" },
|
||
{ value: BATCH_MODE_ALL_PAIRS, label: "每张素材×每张目标", description: "两两组合" },
|
||
{ value: BATCH_MODE_SINGLE_REFERENCES, label: "每张素材单独出图", description: "无需目标" },
|
||
];
|
||
|
||
function normalizeBatchMode(value) {
|
||
const text = String(value ?? "").trim();
|
||
if (!text) return BATCH_MODE_GROUP_TO_TARGETS;
|
||
if (BATCH_MODE_VALUES.includes(text)) return text;
|
||
return BATCH_MODE_ALIASES.get(text) || BATCH_MODE_GROUP_TO_TARGETS;
|
||
}
|
||
|
||
function batchModeOf(node) {
|
||
return normalizeBatchMode(node?._o1igBatchMode?.value);
|
||
}
|
||
const ALL_RATIOS = [
|
||
"智能", "1:1", "1:4", "1:8", "2:3", "3:2", "3:4",
|
||
"4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9",
|
||
];
|
||
const NANO2_ONLY_RATIOS = new Set(["1:4", "1:8", "4:1", "8:1"]);
|
||
const GPT_IMAGE_MODELS = new Set([
|
||
"gpt-image-2.6-sunburst",
|
||
"gpt-image-2.6-flare",
|
||
"gpt-image-2.5-sunburst",
|
||
"gpt-image-2.5-flare",
|
||
"gpt-image-2",
|
||
]);
|
||
const isGptImageModel = (model) => GPT_IMAGE_MODELS.has(model);
|
||
const MODEL_CAPABILITIES = Object.freeze({
|
||
"Nano Banana 2.1": Object.freeze({ thinking: true, quality: false, output: false, mask: false, resize: true, saveFormat: true }),
|
||
"Nano Banana 2": Object.freeze({ thinking: true, quality: false, output: false, mask: false, resize: true, saveFormat: true }),
|
||
"Nano Banana Pro": Object.freeze({ thinking: false, quality: false, output: false, mask: false, resize: true, saveFormat: true }),
|
||
"gpt-image-2": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }),
|
||
"gpt-image-2.5-sunburst": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }),
|
||
"gpt-image-2.5-flare": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }),
|
||
"gpt-image-2.6-sunburst": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false, complexity: true, frames: true }),
|
||
"gpt-image-2.6-flare": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false, complexity: true, frames: true }),
|
||
"Seedream 5.0 Pro": Object.freeze({ thinking: false, quality: false, output: true, mask: false, resize: false, saveFormat: false, layers: true }),
|
||
});
|
||
// Retired names only hide a stale server widget until ComfyUI restarts; they are never
|
||
// serialized, so they must stay out of GENERATOR_SERIALIZED_WIDGETS.
|
||
const RETIRED_BACKEND_WIDGETS = new Set(["内容审查强度", "在线搜索"]);
|
||
const BACKEND_WIDGETS = [
|
||
"prompt", "模型", "模型线路", "思考等级", "分辨率", "宽高比",
|
||
"生图数量", "seed", "参考图清单", "质量", "输出格式", "蒙版清单", "缩放图片", "背景", "内容审查强度",
|
||
"批量出图", "批量模式", "模特图清单", "命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分", "复杂度", "帧数", "帧时长ms",
|
||
];
|
||
|
||
const CSS = `
|
||
/* Keep the image-generation panel and its interactions; only layout and theme are shared. */
|
||
.o1ig-panel,.o1ig-actions,.o1ig-lightbox,.o1ig-canvas-picker{
|
||
--o1ig-text:var(--input-text);
|
||
--o1ig-muted:var(--descrip-text);
|
||
--o1ig-surface:var(--comfy-input-bg);
|
||
--o1ig-border:var(--border-color);
|
||
--o1ig-invalid:var(--error-text);
|
||
--o1ig-radius:var(--radius-lg,8px);
|
||
color:var(--o1ig-text);font-family:var(--font-sans,Inter,system-ui,sans-serif);
|
||
}
|
||
.lg-node-widget:has(.o1ig-panel){
|
||
height:100%;min-height:0;display:flex;flex-direction:column;align-self:stretch;
|
||
}
|
||
/* The slot between the widget and the panel must grow too, otherwise the slack the node body
|
||
carries is left as an empty strip instead of stretching the prompt area. */
|
||
.lg-node-widget:has(.o1ig-panel)>div:has(.o1ig-panel){flex:1 1 auto;height:100%;}
|
||
.lg-node-widget .o1ig-panel,.lg-node-widget .o1ig-actions{
|
||
--o1ig-text:var(--component-node-foreground,var(--input-text));
|
||
--o1ig-muted:var(--component-node-foreground-secondary,var(--descrip-text));
|
||
--o1ig-surface:var(--component-node-widget-background,var(--comfy-input-bg));
|
||
--o1ig-border:var(--component-node-border,var(--border-color));
|
||
}
|
||
.lg-node-widget .o1ig-panel{flex:1 1 auto;min-height:0;}
|
||
/* The Vue body already pads the widget column, so the panel must not add a second inset on the
|
||
right: its content has to end where the native parameter rows end. */
|
||
.lg-node-widget .o1ig-panel{padding-right:0;}
|
||
.lg-node-widget .o1ig-actions{padding-left:0;padding-right:0;}
|
||
.o1ig-panel{
|
||
width:100%;height:100%;min-height:0;box-sizing:border-box;padding:10px 12px 8px;
|
||
font-size:12px;line-height:1.5;display:flex;flex-direction:column;gap:8px;overflow:visible;user-select:none;
|
||
}
|
||
.o1ig-actions{
|
||
width:100%;height:100%;box-sizing:border-box;padding:2px 12px 8px;
|
||
display:flex;flex-direction:column;gap:7px;justify-content:flex-end;user-select:none;
|
||
}
|
||
.o1ig-panel button,.o1ig-actions button,.o1ig-lightbox button,.o1ig-canvas-picker button{
|
||
border:1px solid var(--o1ig-border);background:var(--o1ig-surface);color:var(--o1ig-text);
|
||
font:inherit;box-shadow:none;
|
||
}
|
||
.o1ig-panel button:hover,.o1ig-actions button:hover,.o1ig-lightbox button:hover,.o1ig-canvas-picker button:hover{
|
||
border-color:var(--o1ig-muted);background:var(--o1ig-surface);color:var(--o1ig-text);
|
||
}
|
||
.o1ig-panel button:focus-visible,.o1ig-actions button:focus-visible,.o1ig-lightbox button:focus-visible,.o1ig-canvas-picker button:focus-visible{
|
||
outline:1px solid currentColor;outline-offset:2px;
|
||
}
|
||
.o1ig-panel button:disabled,.o1ig-actions button:disabled{cursor:wait;opacity:.6;}
|
||
.o1ig-refs{
|
||
display:flex;flex:0 0 109px;box-sizing:border-box;gap:7px;min-height:109px;overflow-x:auto;overflow-y:hidden;
|
||
padding:1px 1px 4px;border-radius:var(--o1ig-radius);scrollbar-width:thin;
|
||
}
|
||
.o1ig-refs.o1ig-reordering{outline:1px dashed var(--o1ig-border);outline-offset:2px;}
|
||
.o1ig-batch-bar{display:flex;gap:8px;flex:0 0 auto;align-items:stretch;}
|
||
.o1ig-batch-toggle{
|
||
flex:1;min-width:0;height:28px;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 11px;
|
||
box-sizing:border-box;border-radius:var(--o1ig-radius);cursor:pointer;font-size:11px;
|
||
}
|
||
.o1ig-batch-switch{width:28px;height:16px;padding:2px;box-sizing:border-box;border:1px solid var(--o1ig-muted);border-radius:999px;}
|
||
.o1ig-batch-switch::after{content:"";display:block;width:10px;height:10px;border-radius:50%;background:var(--o1ig-muted);transition:transform .15s ease;}
|
||
.o1ig-batch-toggle.enabled .o1ig-batch-switch::after{transform:translateX(12px);background:var(--o1ig-text);}
|
||
.o1ig-batch-mode{display:none;flex:1;min-width:0;}.o1ig-batch-mode.visible{display:block;}
|
||
.o1ig-assets{display:flex;flex-direction:column;gap:6px;min-width:0;}
|
||
.o1ig-asset-header{display:flex;align-items:center;gap:8px;min-height:28px;padding:0 2px;color:var(--o1ig-muted);font-size:11px;}
|
||
.o1ig-asset-header strong{display:flex;align-items:center;gap:7px;color:var(--o1ig-text);font-size:12px;font-weight:500;}
|
||
.o1ig-asset-meta{display:flex;min-width:0;align-items:baseline;gap:7px;}
|
||
.o1ig-asset-actions{display:flex;flex:0 0 auto;align-items:center;gap:5px;margin-left:auto;}
|
||
.o1ig-asset-hint{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||
.o1ig-asset-hint.hidden{display:none;}
|
||
.o1ig-model-assets{display:none;}.o1ig-model-assets.visible{display:flex;}
|
||
/* Live preview of what the current batch settings will queue. */
|
||
.o1ig-batch-summary{
|
||
display:none;min-height:18px;padding:3px 2px 1px;color:var(--o1ig-muted);font-size:11px;
|
||
align-items:baseline;gap:0 8px;flex-wrap:wrap;
|
||
}
|
||
.o1ig-batch-summary.visible{display:flex;}
|
||
.o1ig-batch-summary-detail{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||
.o1ig-batch-summary-total{
|
||
flex:0 0 auto;margin-left:auto;color:var(--o1ig-text);font-weight:600;font-variant-numeric:tabular-nums;
|
||
}
|
||
.o1ig-thumb{
|
||
position:relative;flex:0 0 102px;height:102px;box-sizing:border-box;border-radius:var(--o1ig-radius);
|
||
border:1px solid var(--o1ig-border);background:var(--o1ig-surface);overflow:hidden;transition:transform .12s ease,opacity .12s ease;
|
||
}
|
||
.o1ig-add{position:relative;display:flex;flex:0 0 auto;height:28px;box-sizing:border-box;align-items:center;justify-content:center;gap:5px;padding:0 9px;border-radius:var(--o1ig-radius);cursor:pointer;}
|
||
.o1ig-add b{font-size:15px;line-height:1;font-weight:400;}.o1ig-add span{font-size:11px;}
|
||
.o1ig-canvas-pick b{font-size:13px;line-height:1;}
|
||
.o1ig-clear-refs{position:relative;display:flex;flex:0 0 auto;height:28px;box-sizing:border-box;align-items:center;justify-content:center;gap:5px;padding:0 9px;border-radius:var(--o1ig-radius);cursor:pointer;}
|
||
.o1ig-clear-refs span{font-size:11px;}
|
||
.o1ig-panel .o1ig-clear-refs:disabled,.o1ig-panel .o1ig-clear-refs:disabled:hover{cursor:default;opacity:.45;}
|
||
.o1ig-thumb img{width:100%;height:100%;display:block;object-fit:contain;background:var(--o1ig-surface);}
|
||
.o1ig-thumb .o1ig-edit{position:absolute;top:5px;left:5px;z-index:2;width:25px;height:25px;padding:0;display:grid;place-items:center;border-radius:6px;cursor:pointer;font-size:15px;opacity:.84;}
|
||
.o1ig-thumb:hover .o1ig-edit,.o1ig-thumb .o1ig-edit:focus-visible{opacity:1;}
|
||
.o1ig-thumb .o1ig-replace{position:absolute;right:5px;bottom:5px;z-index:2;height:22px;padding:0 7px;border-radius:6px;cursor:pointer;font-size:10px;}
|
||
.o1ig-thumb .o1ig-remove{position:absolute;top:5px;right:5px;width:23px;height:23px;padding:0;border-radius:6px;cursor:pointer;font-size:14px;opacity:0;}
|
||
.o1ig-thumb:hover .o1ig-remove,.o1ig-thumb .o1ig-remove:focus-visible{opacity:1;}
|
||
.o1ig-thumb.previewable{cursor:grab;}.o1ig-thumb.previewable:active{cursor:grabbing;}.o1ig-thumb.sort-locked{cursor:zoom-in;}
|
||
.o1ig-thumb.o1ig-dragging{opacity:.3;transform:scale(.91);outline:2px solid currentColor;}
|
||
.o1ig-thumb.o1ig-dragging::before{content:"移动中";position:absolute;inset:0;z-index:4;display:grid;place-items:center;background:var(--o1ig-surface);font-size:11px;pointer-events:none;}
|
||
.o1ig-thumb.o1ig-dragging .o1ig-remove,.o1ig-thumb.o1ig-dragging .o1ig-replace{display:none;}
|
||
.o1ig-thumb.replacing::after{content:"替换中…";position:absolute;inset:0;z-index:3;display:grid;place-items:center;background:var(--o1ig-surface);font-size:11px;pointer-events:none;}
|
||
.o1ig-thumb.o1ig-drop-before{transform:translateX(7px);box-shadow:inset 4px 0 currentColor;}
|
||
.o1ig-thumb.o1ig-drop-after{transform:translateX(-7px);box-shadow:inset -4px 0 currentColor;}
|
||
.o1ig-thumb img.o1ig-previewable{cursor:inherit;}
|
||
.o1ig-thumb img.o1ig-previewable:focus-visible{outline:2px solid currentColor;outline-offset:-3px;}
|
||
.o1ig-reference-index{position:absolute;left:5px;bottom:5px;z-index:1;min-width:23px;height:22px;padding:0 6px;box-sizing:border-box;display:grid;place-items:center;border:1px solid var(--o1ig-border);border-radius:6px;background:var(--o1ig-surface);font-size:11px;line-height:1;pointer-events:none;}
|
||
.o1ig-thumb.pending::after{content:'···';position:absolute;inset:0;display:grid;place-items:center;background:var(--o1ig-surface);letter-spacing:2px;}
|
||
.o1ig-empty-reference{flex:0 0 102px;height:102px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;border-style:dashed!important;border-radius:var(--o1ig-radius);cursor:pointer;}
|
||
.o1ig-empty-reference:hover,.o1ig-empty-reference.drag{outline:1px dashed currentColor;outline-offset:-4px;}
|
||
.o1ig-empty-reference b{font-size:22px;line-height:1;font-weight:300;}.o1ig-empty-reference span{font-size:11px;}
|
||
.o1ig-lightbox{position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:color-mix(in srgb,var(--bg-color) 94%,transparent);outline:none;}
|
||
.o1ig-lightbox[aria-hidden="true"]{display:none;}
|
||
.o1ig-lightbox-image{display:block;width:auto;height:auto;max-width:90vw;max-height:90vh;border-radius:4px;object-fit:contain;}
|
||
.o1ig-lightbox-button{position:fixed;z-index:1;width:44px;height:44px;padding:0;display:grid;place-items:center;border-radius:50%;cursor:pointer;font-size:30px!important;}
|
||
.o1ig-lightbox-close{top:16px;right:16px;font-size:27px!important;}.o1ig-lightbox-previous{top:50%;left:16px;transform:translateY(-50%);}.o1ig-lightbox-next{top:50%;right:16px;transform:translateY(-50%);}
|
||
.o1ig-canvas-picker{position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;padding:24px;box-sizing:border-box;background:color-mix(in srgb,var(--bg-color) 76%,transparent);}
|
||
.o1ig-canvas-picker-dialog{width:min(840px,92vw);max-height:min(720px,88vh);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--o1ig-border);border-radius:12px;background:var(--comfy-menu-bg);}
|
||
.o1ig-canvas-picker-header{display:flex;align-items:center;gap:12px;padding:14px 16px;border-bottom:1px solid var(--o1ig-border);}
|
||
.o1ig-canvas-picker-header strong{flex:1;font-size:15px;font-weight:500;}.o1ig-canvas-picker-header span{color:var(--o1ig-muted);font-size:11px;}
|
||
.o1ig-canvas-picker-close{width:30px;height:30px;padding:0;border-radius:7px;cursor:pointer;font-size:20px!important;}
|
||
.o1ig-canvas-picker-grid{min-height:140px;padding:14px;overflow:auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(145px,1fr));gap:10px;}
|
||
.o1ig-canvas-picker-card{min-width:0;padding:0;overflow:hidden;border-radius:9px;cursor:pointer;text-align:left;}
|
||
.o1ig-canvas-picker-card:disabled{cursor:wait;opacity:.65;}
|
||
.o1ig-canvas-picker-card img{display:block;width:100%;height:118px;object-fit:contain;background:var(--o1ig-surface);}
|
||
.o1ig-canvas-picker-card strong,.o1ig-canvas-picker-card span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0 8px;}
|
||
.o1ig-canvas-picker-card strong{padding-top:7px;font-size:11px;font-weight:500;}.o1ig-canvas-picker-card span{padding-top:2px;padding-bottom:8px;color:var(--o1ig-muted);font-size:10px;}
|
||
.o1ig-canvas-picker-empty{grid-column:1/-1;display:grid;place-items:center;min-height:150px;color:var(--o1ig-muted);text-align:center;font-size:12px;}
|
||
.o1ig-prompt-wrap{position:relative;width:100%;flex:1 1 auto;height:auto;min-height:${PROMPT_DEFAULT_HEIGHT}px;min-width:0;display:flex;flex-direction:column;overflow:hidden;}
|
||
.o1ig-prompt{width:100%;flex:1 1 auto;min-height:${PROMPT_DEFAULT_HEIGHT}px;height:100%;max-height:none;resize:none;box-sizing:border-box;padding:10px 12px 40px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);color:var(--o1ig-text);outline:none;font:inherit;font-size:12px;line-height:1.55;user-select:text;}
|
||
.o1ig-prompt::placeholder{color:var(--o1ig-muted);}.o1ig-prompt:focus{border-color:var(--o1ig-muted);}
|
||
.o1ig-prompt-wrap.invalid .o1ig-prompt{border-color:var(--o1ig-invalid);}
|
||
.o1ig-prompt-wrap.invalid{animation:o1ig-prompt-shake .3s ease-in-out;}
|
||
@keyframes o1ig-prompt-shake{0%,100%{transform:translateX(0)}25%{transform:translateX(-3px)}75%{transform:translateX(3px)}}
|
||
.o1ig-prompt-optimize{position:absolute;right:8px;bottom:8px;min-width:96px;height:28px;padding:0 9px;display:flex;align-items:center;justify-content:center;gap:5px;border-radius:7px;cursor:pointer;font-size:11px!important;line-height:1;white-space:nowrap;}
|
||
.o1ig-prompt-optimize-icon{display:block;font-size:15px;line-height:1;transform-origin:center;}
|
||
.o1ig-prompt-optimize.busy .o1ig-prompt-optimize-icon{animation:o1ig-magic-pulse .9s ease-in-out infinite alternate;}
|
||
@keyframes o1ig-magic-pulse{from{transform:rotate(-5deg) scale(.92);opacity:.58}to{transform:rotate(5deg) scale(1.08);opacity:1}}
|
||
.o1ig-prompt-optimize-status{position:absolute;right:112px;bottom:10px;z-index:1;display:none;align-items:center;gap:6px;max-width:calc(100% - 128px);height:24px;box-sizing:border-box;padding:0 7px;border-radius:6px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;pointer-events:none;background:var(--o1ig-surface);color:var(--o1ig-muted);font-size:10px;line-height:24px;}
|
||
.o1ig-prompt-optimize-status.visible{display:flex;}
|
||
.o1ig-prompt-optimize-status.busy::before{content:"";flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:currentColor;animation:o1ig-prompt-status-pulse .8s ease-in-out infinite alternate;}
|
||
@keyframes o1ig-prompt-status-pulse{from{opacity:.35;transform:scale(.8)}to{opacity:1;transform:scale(1.12)}}
|
||
.o1ig-toolbar{width:100%;min-width:0;display:grid;flex:0 0 auto;grid-template-columns:minmax(0,1fr);gap:6px;position:relative;overflow:visible;}
|
||
.o1ig-field-wide{grid-column:1/-1;}
|
||
.o1ig-control{width:100%;height:28px;min-width:0;box-sizing:border-box;padding:0 9px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);color:var(--o1ig-text);outline:none;font:inherit;font-size:12px;line-height:1.4;font-variant-numeric:tabular-nums;}
|
||
.o1ig-control:hover,.o1ig-control:focus{border-color:var(--o1ig-muted);}
|
||
.o1ig-select{position:relative;min-width:0;height:28px;z-index:1;}.o1ig-select.open{z-index:50;}
|
||
.o1ig-select-trigger{width:100%;height:28px;min-width:0;display:flex;align-items:center;gap:6px;box-sizing:border-box;padding:0 7px 0 9px;border-radius:var(--o1ig-radius);cursor:pointer;text-align:left;font-size:12px!important;line-height:1.4;font-variant-numeric:tabular-nums;}
|
||
.o1ig-select-value{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.4;}
|
||
.o1ig-select-caret{width:14px;height:14px;flex:0 0 14px;display:flex;align-items:center;justify-content:center;align-self:center;line-height:0;transform-origin:50% 50%;transition:transform .14s ease;}
|
||
.o1ig-select-caret svg{display:block;width:12px;height:12px;overflow:visible;}.o1ig-select.open .o1ig-select-caret{transform:rotate(180deg);}
|
||
.o1ig-select-menu{position:absolute;top:32px;left:0;min-width:100%;width:100%;display:none;box-sizing:border-box;padding:5px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--comfy-menu-bg);}
|
||
.o1ig-select.open .o1ig-select-menu{display:grid;gap:2px;}
|
||
.o1ig-panel .o1ig-select-option{min-width:100%;min-height:28px;box-sizing:border-box;padding:5px 9px;border:0;border-radius:5px;display:flex;align-items:center;cursor:pointer;font-size:12px;line-height:1.4;text-align:left;white-space:nowrap;}
|
||
.o1ig-select-option.has-description{gap:14px;justify-content:space-between;}
|
||
.o1ig-select-option-label{min-width:0;overflow:hidden;text-overflow:ellipsis;}
|
||
.o1ig-select-option-description{flex:0 0 auto;color:var(--o1ig-muted);font-size:10px;line-height:1.35;}
|
||
.o1ig-panel .o1ig-select-option.selected{outline:1px solid var(--o1ig-muted);outline-offset:-1px;font-weight:600;}
|
||
.o1ig-field-inline-label{display:grid;grid-template-columns:104px minmax(0,1fr);align-items:center;gap:0;min-width:0;min-height:28px;height:28px;overflow:visible;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);}
|
||
.o1ig-field-inline-label > .o1ig-inline-label{padding-left:9px;color:var(--o1ig-muted);font-size:11px;line-height:1.4;white-space:nowrap;pointer-events:none;}
|
||
.o1ig-field-inline-label > .o1ig-control{height:26px;padding:0 7px;border:0;border-radius:0;background:transparent;}
|
||
.o1ig-field-inline-label > .o1ig-control:hover,.o1ig-field-inline-label > .o1ig-control:focus{border-color:transparent;background:transparent;}
|
||
.o1ig-field-inline-label > .o1ig-select{height:26px;}
|
||
.o1ig-field-inline-label .o1ig-select-trigger{height:26px;padding-left:4px;border:0;border-radius:0;background:transparent;}
|
||
.o1ig-field-inline-label .o1ig-select-value{text-align:right;}
|
||
.o1ig-field-inline-label > .o1ig-mask-wrap{height:26px;align-items:center;}
|
||
.o1ig-field-inline-label > .o1ig-mask-wrap .o1ig-control{height:26px;border:0;border-radius:0;background:transparent;}
|
||
.o1ig-field-inline-label:focus-within,.o1ig-field-inline-label:hover{border-color:var(--o1ig-muted);}
|
||
.o1ig-resize-warning{display:none;grid-column:2;color:var(--o1ig-muted);font-size:10px;line-height:1.4;}.o1ig-resize-warning.visible{display:block;}
|
||
.o1ig-mask-wrap{display:grid;grid-template-columns:minmax(0,1fr) 28px;gap:5px;}
|
||
.o1ig-mask-button{padding:0 9px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left;cursor:pointer;}.o1ig-mask-clear{padding:0;font-size:15px;cursor:pointer;}
|
||
.o1ig-generate{width:100%;height:32px;flex:0 0 32px;border-radius:var(--o1ig-radius);font-size:12px;cursor:pointer;}
|
||
.o1ig-status{display:none;flex:0 0 14px;min-height:14px;text-align:center;color:var(--o1ig-muted);font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.o1ig-status.visible{display:block;}
|
||
.o1igs-progress-host{position:relative;}
|
||
.o1igs-progress-track{
|
||
position:absolute;z-index:2;top:1px;left:8px;right:8px;height:2px;border-radius:2px;
|
||
opacity:0;transition:opacity .14s ease;pointer-events:none;
|
||
background:linear-gradient(90deg,#eee 0 var(--o1igs-progress,0%),rgba(255,255,255,.13) var(--o1igs-progress,0%) 100%);
|
||
}
|
||
.o1igs-progress-track.busy{opacity:1;}
|
||
.o1igs-slots{
|
||
width:100%;box-sizing:border-box;padding:6px;display:grid;gap:7px;overflow:auto;
|
||
border:1px solid rgba(255,255,255,.08);border-radius:8px;background:#202123;
|
||
}
|
||
.o1igs-slot{position:relative;min-width:0;aspect-ratio:1/1;display:grid;place-items:center;overflow:hidden;
|
||
border:1px solid rgba(255,255,255,.1);border-radius:7px;background:#191a1c;color:#989a9f;font-size:11px;}
|
||
.o1igs-slot.pending::after,.o1igs-slot.running::after{content:"";position:absolute;inset:0;transform:translateX(-100%);
|
||
background:linear-gradient(90deg,transparent,rgba(255,255,255,.07),transparent);animation:o1igs-slot-loading 1.3s infinite;}
|
||
@keyframes o1igs-slot-loading{to{transform:translateX(100%)}}
|
||
.o1igs-slot img{width:100%;height:100%;display:block;object-fit:cover;}
|
||
.o1igs-slot-index{position:absolute;top:4px;left:4px;z-index:2;min-width:18px;height:18px;padding:0 4px;box-sizing:border-box;
|
||
display:grid;place-items:center;border-radius:5px;background:rgba(0,0,0,.68);color:#fff;font-size:10px;font-weight:700;}
|
||
.o1igs-slot-retry{width:100%;height:100%;padding:8px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:5px;
|
||
border:0;background:rgba(87,36,36,.34);color:#efcaca;cursor:pointer;font:inherit;font-size:11px;}
|
||
.o1igs-slot-retry:hover{background:rgba(116,42,42,.48);color:#fff}.o1igs-slot-retry:disabled{cursor:wait;opacity:.6}
|
||
.o1igs-slot-retry b{font-size:18px;line-height:1}.o1igs-slot.cancelled{color:#8f9196;background:#1b1c1e;}
|
||
.o1key-slots-visible .image-preview{display:none!important;}
|
||
`;
|
||
|
||
function injectStyles() {
|
||
if (document.getElementById("o1ig-styles")) return;
|
||
const style = document.createElement("style");
|
||
style.id = "o1ig-styles";
|
||
style.textContent = CSS;
|
||
document.head.appendChild(style);
|
||
document.addEventListener("pointerdown", (event) => {
|
||
if (openDropdown && !openDropdown.contains(event.target)) closeDropdown();
|
||
}, true);
|
||
}
|
||
|
||
function findWidget(node, name) {
|
||
return node?.widgets?.find((widget) => widget.name === name);
|
||
}
|
||
|
||
function setWidgetValue(node, name, value) {
|
||
const widget = findWidget(node, name);
|
||
if (!widget) return;
|
||
widget.value = value;
|
||
widget.callback?.(value);
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
|
||
function isGeneratedSeedControl(widget) {
|
||
const name = String(widget?.name || "");
|
||
return name === "control_after_generate" || name.endsWith(" control_after_generate");
|
||
}
|
||
|
||
function generatorSeed(node) {
|
||
// The seed row is the native widget, so it is the single source of truth.
|
||
const value = Math.floor(Number(findWidget(node, "seed")?.value));
|
||
return Number.isFinite(value) ? Math.max(0, value) : 0;
|
||
}
|
||
|
||
function hideBackendWidget(widget) {
|
||
if (!widget) return;
|
||
if (!widget.__o1igOriginalComputeSizeCaptured) {
|
||
widget.__o1igOriginalComputeSizeCaptured = true;
|
||
widget.__o1igHadComputeSize = "computeSize" in widget;
|
||
widget.__o1igOriginalComputeSize = widget.computeSize;
|
||
widget.computeSize = () => [0, -4];
|
||
}
|
||
widget.__o1igHidden = true;
|
||
widget.hidden = true;
|
||
widget.options ??= {};
|
||
widget.options.hidden = true;
|
||
}
|
||
|
||
function showBackendWidget(widget) {
|
||
if (!widget) return;
|
||
if (widget.__o1igHidden && widget.__o1igOriginalComputeSizeCaptured) {
|
||
if (widget.__o1igHadComputeSize) widget.computeSize = widget.__o1igOriginalComputeSize;
|
||
else delete widget.computeSize;
|
||
}
|
||
widget.__o1igHidden = false;
|
||
widget.hidden = false;
|
||
widget.options ??= {};
|
||
widget.options.hidden = false;
|
||
}
|
||
|
||
function setNativeWidgetVisible(node, name, visible) {
|
||
if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return;
|
||
const widget = findWidget(node, name);
|
||
if (visible) showBackendWidget(widget);
|
||
else hideBackendWidget(widget);
|
||
}
|
||
|
||
function hideBackendWidgets(node) {
|
||
for (const name of BACKEND_WIDGETS) {
|
||
const widget = findWidget(node, name);
|
||
if (USE_NATIVE_LITEGRAPH_PARAMETERS && NATIVE_PARAMETER_WIDGETS.has(name)) {
|
||
showBackendWidget(widget);
|
||
} else {
|
||
hideBackendWidget(widget);
|
||
}
|
||
}
|
||
for (const widget of node?.widgets || []) {
|
||
if (!isGeneratedSeedControl(widget)) continue;
|
||
// The seed row is native, so its 生成后控制 companion stays visible too.
|
||
showBackendWidget(widget);
|
||
// LiteGraph restores by widget.serialize; options.serialize only excludes API prompts.
|
||
// Keep it out of widgets_values so the schema order stays aligned.
|
||
widget.serialize = false;
|
||
}
|
||
}
|
||
|
||
const NATIVE_PARAMETER_PANEL_FIELDS = Object.freeze({
|
||
"模型": "_o1igModel",
|
||
"模型线路": "_o1igRoute",
|
||
"思考等级": "_o1igThinking",
|
||
"分辨率": "_o1igResolution",
|
||
"宽高比": "_o1igRatio",
|
||
"生图数量": "_o1igCount",
|
||
"质量": "_o1igQuality",
|
||
"输出格式": "_o1igOutputFormat",
|
||
"缩放图片": "_o1igResize",
|
||
"背景": "_o1igBackground",
|
||
"批量模式": "_o1igBatchMode",
|
||
"图层拆分": "_o1igLayerDecomposition",
|
||
"命名规则": "_o1igNamingRule",
|
||
"filename_prefix": "_o1igFilenamePrefix",
|
||
"格式": "_o1igSaveFormat",
|
||
"保存位置": "_o1igSaveLocation",
|
||
"帧数": "_o1igFrameCount",
|
||
"帧时长ms": "_o1igFrameDuration",
|
||
});
|
||
|
||
function syncNativeParameterToPanel(node, name, value) {
|
||
if (!USE_NATIVE_LITEGRAPH_PARAMETERS || node._o1igNativeParameterSyncing) return;
|
||
node._o1igNativeParameterSyncing = true;
|
||
try {
|
||
const controlName = NATIVE_PARAMETER_PANEL_FIELDS[name];
|
||
if (controlName && node[controlName]) {
|
||
node[controlName].value = name === "模型"
|
||
? normalizeUnifiedModel(value)
|
||
: name === "图层拆分"
|
||
? (value === true || String(value || "").toLowerCase() === "true" || value === "开启" ? "开启" : "关闭")
|
||
: value;
|
||
}
|
||
if (name === "批量出图") {
|
||
node._o1igBatchEnabled = value === true
|
||
|| String(value || "").toLowerCase() === "true"
|
||
|| value === "开启";
|
||
syncBatchLayout(node);
|
||
syncModelOptions(node);
|
||
} else if (name === "批量模式") {
|
||
syncBatchLayout(node);
|
||
} else if (name === "模型" || name === "图层拆分") {
|
||
syncModelOptions(node);
|
||
} else if (name === "输出格式" || name === "背景" || name === "帧数" || name === "帧时长ms") {
|
||
syncGptOutputOptions(node);
|
||
if (name === "输出格式" || name === "背景") syncModelOptions(node);
|
||
} else if (name === "命名规则" || name === "格式" || name === "保存位置" || name === "filename_prefix") {
|
||
syncGeneratorSaveControls(node);
|
||
} else if (name === "缩放图片") {
|
||
syncResizeWarning(node);
|
||
}
|
||
syncNativeWidgetOptions(node);
|
||
} finally {
|
||
node._o1igNativeParameterSyncing = false;
|
||
}
|
||
}
|
||
|
||
const NATIVE_COMBO_PANEL_FIELDS = Object.freeze({
|
||
"模型线路": "_o1igRoute",
|
||
"思考等级": "_o1igThinking",
|
||
"分辨率": "_o1igResolution",
|
||
"宽高比": "_o1igRatio",
|
||
"生图数量": "_o1igCount",
|
||
"质量": "_o1igQuality",
|
||
"输出格式": "_o1igOutputFormat",
|
||
"缩放图片": "_o1igResize",
|
||
"背景": "_o1igBackground",
|
||
"批量模式": "_o1igBatchMode",
|
||
"命名规则": "_o1igNamingRule",
|
||
"格式": "_o1igSaveFormat",
|
||
});
|
||
|
||
function syncNativeWidgetOptions(node) {
|
||
if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return;
|
||
for (const [name, controlName] of Object.entries(NATIVE_COMBO_PANEL_FIELDS)) {
|
||
const widget = findWidget(node, name);
|
||
const control = node[controlName];
|
||
if (!widget || !control?._o1igOptions) continue;
|
||
widget.options ??= {};
|
||
widget.options.values = control._o1igOptions.map((option) => option.value);
|
||
widget.value = control.value;
|
||
}
|
||
}
|
||
|
||
function installNativeParameterBridge(node) {
|
||
if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return;
|
||
for (const name of NATIVE_PARAMETER_WIDGETS) {
|
||
const widget = findWidget(node, name);
|
||
if (!widget || widget.__o1igNativeParameterBridge) continue;
|
||
const originalCallback = widget.callback;
|
||
widget.__o1igNativeParameterBridge = true;
|
||
widget.callback = function () {
|
||
const result = originalCallback?.apply(this, arguments);
|
||
syncNativeParameterToPanel(node, name, this.value);
|
||
return result;
|
||
};
|
||
}
|
||
}
|
||
|
||
function movePanelWidgetToFront(node, panelWidget) {
|
||
if (!USE_NATIVE_LITEGRAPH_PARAMETERS || !Array.isArray(node.widgets)) return;
|
||
const index = node.widgets.indexOf(panelWidget);
|
||
if (index < 0) return;
|
||
node.widgets.splice(index, 1);
|
||
node.widgets.unshift(panelWidget);
|
||
}
|
||
|
||
function moveWidgetToEnd(node, widget) {
|
||
if (!Array.isArray(node?.widgets) || !widget) return;
|
||
const index = node.widgets.indexOf(widget);
|
||
if (index < 0) return;
|
||
node.widgets.splice(index, 1);
|
||
node.widgets.push(widget);
|
||
}
|
||
|
||
function parseReferences(value) {
|
||
try {
|
||
const parsed = typeof value === "string" ? JSON.parse(value || "[]") : value;
|
||
if (!Array.isArray(parsed)) return [];
|
||
return parsed.slice(0, MAX_REFERENCES).filter((item) => item?.name).map((item) => ({
|
||
name: String(item.name),
|
||
subfolder: String(item.subfolder || ""),
|
||
type: "input",
|
||
}));
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
function parseMask(value) {
|
||
try {
|
||
const parsed = typeof value === "string" ? JSON.parse(value || "{}") : value;
|
||
if (!parsed || typeof parsed !== "object" || !parsed.name) return null;
|
||
return {
|
||
name: String(parsed.name),
|
||
subfolder: String(parsed.subfolder || ""),
|
||
type: "input",
|
||
};
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function syncMaskControl(node) {
|
||
if (!node._o1igMaskButton || !node._o1igMaskClear) return;
|
||
node._o1igMaskButton.textContent = node._o1igMask?.name || "添加蒙版";
|
||
node._o1igMaskButton.title = node._o1igMask?.name || "上传 GPT Image 编辑蒙版";
|
||
node._o1igMaskClear.disabled = !node._o1igMask;
|
||
|
||
syncGptOutputOptions(node);
|
||
}
|
||
|
||
function viewPath(item) {
|
||
const filename = item?.filename || item?.name;
|
||
if (!filename) return "";
|
||
const params = new URLSearchParams({ filename: String(filename), type: item.type || "input" });
|
||
if (item.subfolder) params.set("subfolder", item.subfolder);
|
||
return `/view?${params.toString()}`;
|
||
}
|
||
|
||
function viewUrl(item) {
|
||
const path = viewPath(item);
|
||
return path ? api.apiURL(path) : "";
|
||
}
|
||
|
||
function thumbnailUrl(item) {
|
||
const filename = item?.filename || item?.name;
|
||
if (!filename) return "";
|
||
const params = new URLSearchParams({
|
||
filename: String(filename),
|
||
type: item.type || "input",
|
||
});
|
||
if (item.subfolder) params.set("subfolder", item.subfolder);
|
||
return api.apiURL(`/o1key/image/thumbnail?${params.toString()}`);
|
||
}
|
||
|
||
function canvasImageDescriptor(item) {
|
||
const filename = String(item?.filename || item?.name || "").trim();
|
||
const type = String(item?.type || "").trim();
|
||
if (!filename || !["input", "output", "temp"].includes(type)) return null;
|
||
return {
|
||
filename,
|
||
subfolder: String(item?.subfolder || ""),
|
||
type,
|
||
};
|
||
}
|
||
|
||
function canvasImageDescriptorFromUrl(value) {
|
||
if (!value) return null;
|
||
try {
|
||
const url = new URL(String(value), document.baseURI || "http://localhost/");
|
||
return canvasImageDescriptor({
|
||
filename: url.searchParams.get("filename"),
|
||
subfolder: url.searchParams.get("subfolder"),
|
||
type: url.searchParams.get("type"),
|
||
});
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function graphNodeList(graph) {
|
||
if (Array.isArray(graph?._nodes)) return graph._nodes;
|
||
if (graph?.nodes instanceof Map) return [...graph.nodes.values()];
|
||
if (Array.isArray(graph?.nodes)) return graph.nodes;
|
||
return [];
|
||
}
|
||
|
||
function canvasImageCandidates(targetNode) {
|
||
const graph = targetNode?.graph || app.graph;
|
||
const candidates = [];
|
||
const seen = new Set();
|
||
for (const sourceNode of graphNodeList(graph)) {
|
||
if (!sourceNode || sourceNode === targetNode) continue;
|
||
const nodeId = String(sourceNode.id);
|
||
const output = app.nodeOutputs?.[nodeId] || {};
|
||
const descriptors = [
|
||
...(Array.isArray(output.images) ? output.images : []),
|
||
...(Array.isArray(output.gifs) ? output.gifs : []),
|
||
...(Array.isArray(sourceNode._o1igsLastResults) ? sourceNode._o1igsLastResults : []),
|
||
...(Array.isArray(sourceNode.images) ? sourceNode.images : []),
|
||
...(Array.isArray(sourceNode.imgs)
|
||
? sourceNode.imgs.map((image) => canvasImageDescriptorFromUrl(image?.currentSrc || image?.src))
|
||
: []),
|
||
];
|
||
const sourceLabel = String(
|
||
sourceNode.title || sourceNode.comfyClass || sourceNode.type || `节点 ${nodeId}`,
|
||
);
|
||
for (const rawDescriptor of descriptors) {
|
||
const descriptor = canvasImageDescriptor(rawDescriptor);
|
||
if (!descriptor) continue;
|
||
const identity = [descriptor.filename, descriptor.subfolder, descriptor.type].join("\n");
|
||
if (seen.has(identity)) continue;
|
||
seen.add(identity);
|
||
candidates.push({ nodeId, sourceLabel, descriptor });
|
||
}
|
||
}
|
||
return candidates;
|
||
}
|
||
|
||
function closeReferenceLightbox(lightbox = document.getElementById(REFERENCE_LIGHTBOX_ID)) {
|
||
if (!lightbox) return;
|
||
lightbox.setAttribute("aria-hidden", "true");
|
||
lightbox._o1igItems = [];
|
||
lightbox._o1igActiveIndex = -1;
|
||
lightbox._o1igPreviouslyFocusedElement?.focus?.();
|
||
lightbox._o1igPreviouslyFocusedElement = null;
|
||
}
|
||
|
||
function updateReferenceLightbox(lightbox) {
|
||
const items = lightbox?._o1igItems || [];
|
||
const activeIndex = Number(lightbox?._o1igActiveIndex);
|
||
const entry = items[activeIndex];
|
||
if (!entry) {
|
||
closeReferenceLightbox(lightbox);
|
||
return;
|
||
}
|
||
lightbox._o1igImage.src = viewUrl(entry.item);
|
||
lightbox._o1igImage.alt = entry.item?.name || `图片 ${activeIndex + 1}`;
|
||
const hasMultiple = items.length > 1;
|
||
lightbox._o1igPrevious.hidden = !hasMultiple;
|
||
lightbox._o1igNext.hidden = !hasMultiple;
|
||
}
|
||
|
||
function navigateReferenceLightbox(lightbox, direction) {
|
||
const items = lightbox?._o1igItems || [];
|
||
if (!items.length) return;
|
||
lightbox._o1igActiveIndex = (
|
||
lightbox._o1igActiveIndex + direction + items.length
|
||
) % items.length;
|
||
updateReferenceLightbox(lightbox);
|
||
}
|
||
|
||
function ensureReferenceLightbox() {
|
||
let lightbox = document.getElementById(REFERENCE_LIGHTBOX_ID);
|
||
if (lightbox || !document.body) return lightbox;
|
||
|
||
lightbox = document.createElement("div");
|
||
lightbox.id = REFERENCE_LIGHTBOX_ID;
|
||
lightbox.className = "o1ig-lightbox";
|
||
lightbox.tabIndex = -1;
|
||
lightbox.setAttribute("role", "dialog");
|
||
lightbox.setAttribute("aria-modal", "true");
|
||
lightbox.setAttribute("aria-label", "图片预览");
|
||
lightbox.setAttribute("aria-hidden", "true");
|
||
|
||
const image = document.createElement("img");
|
||
image.className = "o1ig-lightbox-image";
|
||
|
||
const makeButton = (className, label, text) => {
|
||
const button = document.createElement("button");
|
||
button.type = "button";
|
||
button.className = `o1ig-lightbox-button ${className}`;
|
||
button.setAttribute("aria-label", label);
|
||
button.textContent = text;
|
||
return button;
|
||
};
|
||
const close = makeButton("o1ig-lightbox-close", "关闭", "×");
|
||
const previous = makeButton("o1ig-lightbox-previous", "上一张", "‹");
|
||
const next = makeButton("o1ig-lightbox-next", "下一张", "›");
|
||
|
||
Object.assign(lightbox, {
|
||
_o1igImage: image,
|
||
_o1igClose: close,
|
||
_o1igPrevious: previous,
|
||
_o1igNext: next,
|
||
_o1igItems: [],
|
||
_o1igActiveIndex: -1,
|
||
_o1igMaskMouseDownTarget: null,
|
||
_o1igPreviouslyFocusedElement: null,
|
||
});
|
||
close.addEventListener("click", () => closeReferenceLightbox(lightbox));
|
||
previous.addEventListener("click", () => navigateReferenceLightbox(lightbox, -1));
|
||
next.addEventListener("click", () => navigateReferenceLightbox(lightbox, 1));
|
||
lightbox.addEventListener("mousedown", (event) => {
|
||
lightbox._o1igMaskMouseDownTarget = event.target;
|
||
});
|
||
lightbox.addEventListener("mouseup", (event) => {
|
||
if (lightbox._o1igMaskMouseDownTarget === event.target && event.target === lightbox) {
|
||
closeReferenceLightbox(lightbox);
|
||
}
|
||
});
|
||
lightbox.addEventListener("keydown", (event) => {
|
||
const actions = {
|
||
ArrowLeft: () => navigateReferenceLightbox(lightbox, -1),
|
||
ArrowRight: () => navigateReferenceLightbox(lightbox, 1),
|
||
Escape: () => closeReferenceLightbox(lightbox),
|
||
};
|
||
const action = actions[event.key];
|
||
if (!action) return;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
action();
|
||
});
|
||
lightbox.append(image, close, previous, next);
|
||
document.body.append(lightbox);
|
||
return lightbox;
|
||
}
|
||
|
||
function referenceLightboxEntries(node) {
|
||
const entries = (node?._o1igReferences || []).map((item, index) => ({
|
||
item, role: "references", index,
|
||
}));
|
||
if (
|
||
node?._o1igBatchEnabled
|
||
&& batchModeOf(node) !== BATCH_MODE_SINGLE_REFERENCES
|
||
) {
|
||
entries.push(...(node._o1igModelReferences || []).map((item, index) => ({
|
||
item, role: "models", index,
|
||
})));
|
||
}
|
||
return entries.filter((entry) => viewUrl(entry.item));
|
||
}
|
||
|
||
function showReferenceLightbox(node, role, listIndex) {
|
||
const lightbox = ensureReferenceLightbox();
|
||
if (!lightbox) return;
|
||
const items = referenceLightboxEntries(node);
|
||
const activeIndex = items.findIndex((entry) => entry.role === role && entry.index === listIndex);
|
||
if (activeIndex < 0) return;
|
||
lightbox._o1igItems = items;
|
||
lightbox._o1igActiveIndex = activeIndex;
|
||
lightbox._o1igPreviouslyFocusedElement = document.activeElement;
|
||
updateReferenceLightbox(lightbox);
|
||
lightbox.setAttribute("aria-hidden", "false");
|
||
requestAnimationFrame(() => lightbox.focus());
|
||
}
|
||
|
||
async function uploadImage(file) {
|
||
const body = new FormData();
|
||
body.append("image", file, file.name);
|
||
body.append("type", "input");
|
||
body.append("overwrite", "false");
|
||
const response = await api.fetchApi("/upload/image", { method: "POST", body });
|
||
if (!response.ok) throw new Error(`上传失败:${file.name}`);
|
||
const data = await response.json();
|
||
return {
|
||
name: String(data.name || file.name),
|
||
subfolder: String(data.subfolder || ""),
|
||
type: "input",
|
||
};
|
||
}
|
||
|
||
let imageUploadQueue = Promise.resolve();
|
||
|
||
function enqueueImageUpload(file) {
|
||
// ComfyUI appends a natural-number suffix when a name already exists.
|
||
// Keep every o1key upload sequential so two requests cannot race while the
|
||
// native endpoint checks and allocates that filename in the input root.
|
||
const request = imageUploadQueue.then(() => uploadImage(file));
|
||
imageUploadQueue = request.catch(() => {});
|
||
return request;
|
||
}
|
||
|
||
function validateSeedreamReferenceDimensions(width, height, label, { layerDecomposition = false } = {}) {
|
||
const limits = SEEDREAM_REFERENCE_LIMITS;
|
||
width = Number(width);
|
||
height = Number(height);
|
||
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
||
throw new Error(`${label}尺寸无效:${width}×${height}`);
|
||
}
|
||
const pixels = width * height;
|
||
if (!layerDecomposition && (width <= limits.minSideExclusive || height <= limits.minSideExclusive)) {
|
||
throw new Error(`${label}宽和高都必须大于 ${limits.minSideExclusive}px,当前为 ${width}×${height}`);
|
||
}
|
||
const ratio = width / height;
|
||
if (ratio < limits.minAspectRatio || ratio > limits.maxAspectRatio) {
|
||
throw new Error(`${label}宽高比必须在 1:16~16:1,当前为 ${width}:${height}`);
|
||
}
|
||
if (layerDecomposition && (pixels < limits.minLayerPixels || pixels > limits.maxPixels)) {
|
||
throw new Error(`${label}总像素必须在 512×512(262144)~6000×6000(36000000)之间,当前为 ${width}×${height}(${pixels})`);
|
||
}
|
||
if (!layerDecomposition && pixels > limits.maxPixels) {
|
||
throw new Error(`${label}总像素不能超过 6000×6000(36000000),当前为 ${width}×${height}(${pixels})`);
|
||
}
|
||
}
|
||
|
||
async function readImageFileDimensions(file) {
|
||
if (typeof createImageBitmap !== "function") return null;
|
||
const bitmap = await createImageBitmap(file);
|
||
try {
|
||
return [bitmap.width, bitmap.height];
|
||
} finally {
|
||
bitmap.close?.();
|
||
}
|
||
}
|
||
|
||
async function validateSeedreamReferenceFile(node, file) {
|
||
if (node?._o1igModel?.value !== "Seedream 5.0 Pro") return;
|
||
const label = file?.name || "Seedream 参考图";
|
||
if (Number(file?.size) > SEEDREAM_REFERENCE_LIMITS.maxBytes) {
|
||
throw new Error(`${label}文件不能超过 30MB,当前为 ${(file.size / 1024 / 1024).toFixed(2)}MB`);
|
||
}
|
||
const dimensions = await readImageFileDimensions(file);
|
||
if (!dimensions) return;
|
||
const [width, height] = dimensions;
|
||
validateSeedreamReferenceDimensions(width, height, label, {
|
||
layerDecomposition: node?._o1igLayerDecomposition?.value === "开启",
|
||
});
|
||
}
|
||
|
||
function toast(severity, summary, detail) {
|
||
app.extensionManager?.toast?.add?.({ severity, summary, detail, life: 3000 });
|
||
}
|
||
|
||
const UNSAFE_IMAGE_ERROR_MESSAGE = "内容被拒绝:该图像被内容安全系统标记为不安全。";
|
||
const SAFETY_REJECTION_ERROR_MESSAGE = "您的请求已被安全系统拒绝";
|
||
const INSUFFICIENT_BALANCE_ERROR_MESSAGE = "上游额度不足!";
|
||
const EMPTY_IMAGE_RESPONSE_ERROR_MESSAGE = "图片生成过程中被内容审查机制拒绝!";
|
||
const UNSAFE_PROMPT_ERROR_MESSAGE = "提供的提示被认为是不安全的,不能用于生成内容。";
|
||
const SEEDANCE_ERROR_NODE_TYPES = new Set(["SeedanceAutoPass", "SeedanceMultiModal"]);
|
||
const SEEDANCE_COPYRIGHT_ERROR_MESSAGE = "输出视频触发版权审查被拒绝生成!";
|
||
|
||
function formatImageGenerationError(value) {
|
||
const message = String(value || "生成失败");
|
||
if (/content rejected:\s*the image was flagged as unsafe by the content safety system/i.test(message)) {
|
||
return UNSAFE_IMAGE_ERROR_MESSAGE;
|
||
}
|
||
if (/your request was rejected by the safety system/i.test(message)) {
|
||
return SAFETY_REJECTION_ERROR_MESSAGE;
|
||
}
|
||
if (/insufficient balance/i.test(message)) {
|
||
return INSUFFICIENT_BALANCE_ERROR_MESSAGE;
|
||
}
|
||
if (/image generation returned empty response/i.test(message)) {
|
||
return EMPTY_IMAGE_RESPONSE_ERROR_MESSAGE;
|
||
}
|
||
if (/the provided prompt is considered unsafe and it cannot be used to generate content/i.test(message)) {
|
||
return UNSAFE_PROMPT_ERROR_MESSAGE;
|
||
}
|
||
return message;
|
||
}
|
||
|
||
function formatSeedanceGenerationError(value) {
|
||
const message = String(value || "视频生成失败");
|
||
if (/the request failed because the output video may be related to copyright restrictions?/i.test(message)) {
|
||
return SEEDANCE_COPYRIGHT_ERROR_MESSAGE;
|
||
}
|
||
return message;
|
||
}
|
||
|
||
function updateExecutionErrorOverlay(message, root = document) {
|
||
const overlay = root?.querySelector?.('[data-testid="error-overlay"]');
|
||
const messageContainer = overlay?.querySelector?.('[data-testid="error-overlay-messages"]');
|
||
const messageElement = messageContainer?.querySelector?.("p");
|
||
if (!messageElement) return false;
|
||
const nextMessage = String(message || "生成失败");
|
||
if (messageElement.textContent !== nextMessage) {
|
||
messageElement.textContent = nextMessage;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
let executionErrorOverlayObserver = null;
|
||
let executionErrorOverlayTimer = null;
|
||
|
||
function replaceExecutionErrorOverlay(message) {
|
||
const formattedMessage = String(message || "生成失败");
|
||
executionErrorOverlayObserver?.disconnect?.();
|
||
if (executionErrorOverlayTimer) clearTimeout(executionErrorOverlayTimer);
|
||
|
||
const applyMessage = () => updateExecutionErrorOverlay(formattedMessage);
|
||
const root = document.body || document.documentElement;
|
||
if (root && typeof MutationObserver === "function") {
|
||
executionErrorOverlayObserver = new MutationObserver(() => {
|
||
applyMessage();
|
||
});
|
||
executionErrorOverlayObserver.observe(root, {
|
||
childList: true,
|
||
subtree: true,
|
||
characterData: true,
|
||
});
|
||
}
|
||
|
||
// Vue updates the core error overlay after the execution_error listeners
|
||
// finish. Apply on the next frame and keep observing briefly in case the
|
||
// existing overlay is re-rendered with ComfyUI's generic fallback copy.
|
||
requestAnimationFrame(applyMessage);
|
||
executionErrorOverlayTimer = setTimeout(() => {
|
||
applyMessage();
|
||
executionErrorOverlayObserver?.disconnect?.();
|
||
executionErrorOverlayObserver = null;
|
||
executionErrorOverlayTimer = null;
|
||
}, 1500);
|
||
}
|
||
|
||
let openDropdown = null;
|
||
const parallelBatches = new Map();
|
||
const NATIVE_QUEUE_BRIDGE_KEY = "__o1keyImageJobQueueBridge";
|
||
const O1KEY_QUEUE_JOB_PREFIX = "o1key:";
|
||
const O1KEY_QUEUE_WORKFLOW_LABEL = "o1key 图片生成";
|
||
const MAX_NATIVE_QUEUE_HISTORY = 64;
|
||
const nativeQueueBridge = api[NATIVE_QUEUE_BRIDGE_KEY] || {
|
||
installed: false,
|
||
jobs: new Map(),
|
||
sequence: 0,
|
||
lastNativeQueueRemaining: 0,
|
||
historyLoaded: false,
|
||
historyLoadPromise: null,
|
||
originals: {},
|
||
};
|
||
nativeQueueBridge.historyLoaded ??= false;
|
||
nativeQueueBridge.historyLoadPromise ??= null;
|
||
api[NATIVE_QUEUE_BRIDGE_KEY] = nativeQueueBridge;
|
||
|
||
function activeGraphNodeById(nodeId) {
|
||
if (nodeId == null) return null;
|
||
const graph = app.graph;
|
||
return graph?.getNodeById?.(nodeId)
|
||
|| graph?.getNodeById?.(Number(nodeId))
|
||
|| graphNodes(graph).find((node) => String(node?.id) === String(nodeId))
|
||
|| null;
|
||
}
|
||
|
||
function isActiveGraphNode(node) {
|
||
return Boolean(node && activeGraphNodeById(node.id) === node);
|
||
}
|
||
|
||
function detachParallelBatchNode(node) {
|
||
if (!node) return;
|
||
for (const registered of parallelBatches.values()) {
|
||
if (registered.source === node) {
|
||
registered.generatorNodeId ??= node.id;
|
||
registered.source = null;
|
||
}
|
||
if (registered.saveNode === node) {
|
||
registered.saveNodeId ??= node.id;
|
||
registered.saveNode = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
function nativeQueueJobId(batchId) {
|
||
return `${O1KEY_QUEUE_JOB_PREFIX}${batchId}`;
|
||
}
|
||
|
||
function isTerminalNativeQueueStatus(status) {
|
||
return status === "completed" || status === "failed" || status === "cancelled";
|
||
}
|
||
|
||
function nativeQueueStatus(state) {
|
||
if (state === "queued") return "pending";
|
||
if (state === "running" || state === "saving") return "in_progress";
|
||
if (state === "completed") return "completed";
|
||
if (state === "cancelled") return "cancelled";
|
||
return "failed";
|
||
}
|
||
|
||
function nativeQueueImages(detail) {
|
||
return normalizeSaveResults(detail?.images).filter(
|
||
(item) => item.type === "output" || item.external_saved === true,
|
||
);
|
||
}
|
||
|
||
function trimNativeQueueHistory() {
|
||
const terminal = [...nativeQueueBridge.jobs.values()]
|
||
.filter((job) => isTerminalNativeQueueStatus(job.status))
|
||
.sort((left, right) => (right.execution_end_time || 0) - (left.execution_end_time || 0));
|
||
for (const job of terminal.slice(MAX_NATIVE_QUEUE_HISTORY)) {
|
||
nativeQueueBridge.jobs.delete(job.id);
|
||
}
|
||
}
|
||
|
||
function notifyNativeTaskQueue() {
|
||
if (typeof api.dispatchCustomEvent !== "function") return;
|
||
const activeCount = [...nativeQueueBridge.jobs.values()].filter(
|
||
(job) => !isTerminalNativeQueueStatus(job.status),
|
||
).length;
|
||
api.dispatchCustomEvent("status", {
|
||
exec_info: {
|
||
queue_remaining: Math.max(0, Number(nativeQueueBridge.lastNativeQueueRemaining) || 0) + activeCount,
|
||
},
|
||
o1key_virtual_queue_update: true,
|
||
});
|
||
}
|
||
|
||
function updateNativeQueueJob(detail, { forceState = "", images = null, error = "" } = {}) {
|
||
const batchId = String(detail?.batch_id || "");
|
||
if (!batchId) return null;
|
||
const id = nativeQueueJobId(batchId);
|
||
const now = Date.now();
|
||
let job = nativeQueueBridge.jobs.get(id);
|
||
const previousStatus = job?.status || "";
|
||
if (!job) {
|
||
nativeQueueBridge.sequence += 1;
|
||
job = {
|
||
id,
|
||
batch_id: batchId,
|
||
status: "pending",
|
||
create_time: now,
|
||
execution_start_time: null,
|
||
execution_end_time: null,
|
||
preview_output: null,
|
||
outputs_count: 0,
|
||
execution_error: null,
|
||
workflow_id: O1KEY_QUEUE_WORKFLOW_LABEL,
|
||
priority: 1_100_000 + nativeQueueBridge.sequence,
|
||
generator_node_id: Number(detail?.generator_node_id),
|
||
save_node_id: Number(detail?.save_node_id),
|
||
images: [],
|
||
o1key_total_count: 0,
|
||
};
|
||
nativeQueueBridge.jobs.set(id, job);
|
||
}
|
||
|
||
const state = forceState || String(detail?.state || "queued");
|
||
const status = nativeQueueStatus(state);
|
||
job.status = status;
|
||
if (Number.isFinite(Number(detail?.generator_node_id))) {
|
||
job.generator_node_id = Number(detail.generator_node_id);
|
||
}
|
||
if (Number.isFinite(Number(detail?.save_node_id))) {
|
||
job.save_node_id = Number(detail.save_node_id);
|
||
}
|
||
const totalCount = Math.max(0, Math.floor(Number(detail?.total_count) || 0));
|
||
if (totalCount) job.o1key_total_count = totalCount;
|
||
const createTime = Number(detail?.create_time);
|
||
const startTime = Number(detail?.execution_start_time);
|
||
const endTime = Number(detail?.execution_end_time);
|
||
if (Number.isFinite(createTime) && createTime > 0) job.create_time = createTime;
|
||
if (Number.isFinite(startTime) && startTime > 0) job.execution_start_time = startTime;
|
||
if (status === "in_progress" && !job.execution_start_time) job.execution_start_time = now;
|
||
if (Number.isFinite(endTime) && endTime > 0) job.execution_end_time = endTime;
|
||
if (isTerminalNativeQueueStatus(status)) job.execution_end_time ||= now;
|
||
|
||
const savedImages = images === null ? nativeQueueImages(detail) : normalizeSaveResults(images);
|
||
if (savedImages.length) {
|
||
job.images = savedImages;
|
||
job.outputs_count = savedImages.length;
|
||
const preview = savedImages[0];
|
||
const animated = animatedFlagsForSaveResults(savedImages);
|
||
job.preview_output = {
|
||
...preview,
|
||
nodeId: String(job.save_node_id),
|
||
mediaType: animated ? "images" : "images",
|
||
display_name: preview.filename,
|
||
};
|
||
if (animated) job.animated = animated;
|
||
}
|
||
if (!job.o1key_total_count && savedImages.length) {
|
||
job.o1key_total_count = savedImages.length;
|
||
}
|
||
const errorMessage = String(error || detail?.error || "");
|
||
job.execution_error = status === "failed" ? {
|
||
prompt_id: id,
|
||
timestamp: now,
|
||
node_id: String(job.save_node_id),
|
||
node_type: SAVE_NODE_TYPE,
|
||
executed: [],
|
||
exception_message: errorMessage || "o1key 图片生成失败",
|
||
exception_type: "O1keyImageGenerationError",
|
||
traceback: [],
|
||
current_inputs: {},
|
||
current_outputs: {},
|
||
} : null;
|
||
|
||
trimNativeQueueHistory();
|
||
if (!previousStatus || previousStatus !== status || isTerminalNativeQueueStatus(status)) {
|
||
notifyNativeTaskQueue();
|
||
}
|
||
scheduleNativePreviewActionSync();
|
||
return job;
|
||
}
|
||
|
||
async function loadPersistedNativeQueueHistory() {
|
||
if (nativeQueueBridge.historyLoaded) return;
|
||
if (!nativeQueueBridge.historyLoadPromise) {
|
||
nativeQueueBridge.historyLoadPromise = (async () => {
|
||
let loaded = false;
|
||
try {
|
||
const response = await api.fetchApi(
|
||
`/o1key/image/jobs/history?limit=${MAX_NATIVE_QUEUE_HISTORY}`,
|
||
{ cache: "no-store" },
|
||
);
|
||
const result = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(result?.error || `HTTP ${response.status}`);
|
||
for (const detail of result?.items || []) updateNativeQueueJob(detail);
|
||
loaded = true;
|
||
} catch {
|
||
// Native queue/history must remain usable during a brief reconnect.
|
||
} finally {
|
||
nativeQueueBridge.historyLoaded = loaded;
|
||
nativeQueueBridge.historyLoadPromise = null;
|
||
}
|
||
})();
|
||
}
|
||
return nativeQueueBridge.historyLoadPromise;
|
||
}
|
||
|
||
async function updatePersistedNativeQueueHistory(payload) {
|
||
const response = await api.fetchApi("/o1key/image/jobs/history", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(payload),
|
||
});
|
||
const result = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(result?.error || `HTTP ${response.status}`);
|
||
}
|
||
|
||
async function cancelNativeO1keyJob(job) {
|
||
if (!job || isTerminalNativeQueueStatus(job.status)) return;
|
||
const response = await api.fetchApi(`/o1key/image/jobs/${encodeURIComponent(job.batch_id)}/cancel`, {
|
||
method: "POST",
|
||
});
|
||
const result = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(result?.error || `取消任务失败(HTTP ${response.status})`);
|
||
if (!findBatchNodes(result).batchId) {
|
||
updateNativeQueueJob(result, {
|
||
forceState: String(result?.state || "cancelled"),
|
||
error: result?.error || "任务已取消",
|
||
});
|
||
}
|
||
handleParallelImageJob(result);
|
||
}
|
||
|
||
function installNativeTaskQueueBridge() {
|
||
if (nativeQueueBridge.installed || typeof api.getQueue !== "function") return;
|
||
nativeQueueBridge.installed = true;
|
||
const originals = nativeQueueBridge.originals;
|
||
originals.getQueue = api.getQueue.bind(api);
|
||
originals.getHistory = typeof api.getHistory === "function" ? api.getHistory.bind(api) : async () => [];
|
||
originals.getJobDetail = typeof api.getJobDetail === "function" ? api.getJobDetail.bind(api) : async () => undefined;
|
||
originals.cancelJob = typeof api.cancelJob === "function" ? api.cancelJob.bind(api) : async () => {};
|
||
originals.cancelJobs = typeof api.cancelJobs === "function" ? api.cancelJobs.bind(api) : async () => {};
|
||
originals.deleteItem = typeof api.deleteItem === "function" ? api.deleteItem.bind(api) : async () => {};
|
||
originals.clearItems = typeof api.clearItems === "function" ? api.clearItems.bind(api) : async () => {};
|
||
|
||
api.getQueue = async (...args) => {
|
||
const result = await originals.getQueue(...args);
|
||
const jobs = [...nativeQueueBridge.jobs.values()];
|
||
return {
|
||
Running: [...(result?.Running || []), ...jobs.filter((job) => job.status === "in_progress")],
|
||
Pending: [...(result?.Pending || []), ...jobs.filter((job) => job.status === "pending")],
|
||
};
|
||
};
|
||
api.getHistory = async (maxItems = 200, options = {}) => {
|
||
const history = await originals.getHistory(maxItems, options);
|
||
if ((Number(options?.offset) || 0) > 0) return history;
|
||
await loadPersistedNativeQueueHistory();
|
||
const jobs = [...nativeQueueBridge.jobs.values()]
|
||
.filter((job) => isTerminalNativeQueueStatus(job.status));
|
||
return [...history, ...jobs]
|
||
.sort((left, right) => (
|
||
(right.execution_end_time || right.create_time || 0)
|
||
- (left.execution_end_time || left.create_time || 0)
|
||
))
|
||
.slice(0, Math.max(0, Number(maxItems) || 200));
|
||
};
|
||
api.getJobDetail = async (jobId) => {
|
||
const job = nativeQueueBridge.jobs.get(String(jobId));
|
||
if (!job) return originals.getJobDetail(jobId);
|
||
return {
|
||
...job,
|
||
outputs: job.images?.length ? (() => {
|
||
const output = { images: job.images };
|
||
const animated = animatedFlagsForSaveResults(job.images);
|
||
if (animated) output.animated = animated;
|
||
return { [String(job.save_node_id)]: output };
|
||
})() : {},
|
||
update_time: job.execution_end_time || Date.now(),
|
||
};
|
||
};
|
||
api.cancelJob = async (jobId) => {
|
||
const job = nativeQueueBridge.jobs.get(String(jobId));
|
||
if (job) return cancelNativeO1keyJob(job);
|
||
return originals.cancelJob(jobId);
|
||
};
|
||
api.cancelJobs = async (jobIds) => {
|
||
const nativeIds = [];
|
||
const o1keyJobs = [];
|
||
for (const jobId of jobIds || []) {
|
||
const job = nativeQueueBridge.jobs.get(String(jobId));
|
||
if (job) o1keyJobs.push(job);
|
||
else nativeIds.push(jobId);
|
||
}
|
||
await Promise.all([
|
||
...o1keyJobs.map((job) => cancelNativeO1keyJob(job)),
|
||
...(nativeIds.length ? [originals.cancelJobs(nativeIds)] : []),
|
||
]);
|
||
};
|
||
api.deleteItem = async (type, jobId) => {
|
||
const id = String(jobId);
|
||
const job = nativeQueueBridge.jobs.get(id);
|
||
if (!job) return originals.deleteItem(type, jobId);
|
||
if (!isTerminalNativeQueueStatus(job.status)) await cancelNativeO1keyJob(job);
|
||
if (type === "history" || isTerminalNativeQueueStatus(job.status)) {
|
||
await updatePersistedNativeQueueHistory({ batch_id: job.batch_id });
|
||
nativeQueueBridge.jobs.delete(id);
|
||
notifyNativeTaskQueue();
|
||
}
|
||
};
|
||
api.clearItems = async (type) => {
|
||
await originals.clearItems(type);
|
||
if (type === "queue") {
|
||
const pending = [...nativeQueueBridge.jobs.values()].filter(
|
||
(job) => job.status === "pending",
|
||
);
|
||
await Promise.all(pending.map((job) => cancelNativeO1keyJob(job)));
|
||
} else if (type === "history") {
|
||
await updatePersistedNativeQueueHistory({ clear: true });
|
||
for (const [id, job] of nativeQueueBridge.jobs) {
|
||
if (isTerminalNativeQueueStatus(job.status)) nativeQueueBridge.jobs.delete(id);
|
||
}
|
||
notifyNativeTaskQueue();
|
||
}
|
||
};
|
||
api.addEventListener?.("status", ({ detail }) => {
|
||
if (detail?.o1key_virtual_queue_update) return;
|
||
nativeQueueBridge.lastNativeQueueRemaining = Math.max(
|
||
0,
|
||
Number(detail?.exec_info?.queue_remaining) || 0,
|
||
);
|
||
});
|
||
}
|
||
|
||
function createBatchId() {
|
||
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
|
||
const bytes = new Uint8Array(16);
|
||
globalThis.crypto.getRandomValues(bytes);
|
||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||
const hex = [...bytes].map((value) => value.toString(16).padStart(2, "0"));
|
||
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
||
}
|
||
|
||
function closeDropdown(dropdown = openDropdown) {
|
||
if (!dropdown) return;
|
||
dropdown.classList.remove("open");
|
||
dropdown._o1igTrigger.setAttribute("aria-expanded", "false");
|
||
if (openDropdown === dropdown) openDropdown = null;
|
||
}
|
||
|
||
function setDropdownValue(dropdown, value) {
|
||
const fallback = dropdown._o1igOptions[0]?.value ?? "";
|
||
const selected = dropdown._o1igOptions.find((option) => option.value === value);
|
||
const nextValue = selected ? selected.value : fallback;
|
||
dropdown._o1igValue = nextValue;
|
||
const selectedOption = selected || dropdown._o1igOptions[0];
|
||
dropdown._o1igValueLabel.textContent = selectedOption?.label || "";
|
||
dropdown._o1igTrigger.title = selectedOption?.description
|
||
? `${selectedOption.label} · ${selectedOption.description}`
|
||
: selectedOption?.label || "";
|
||
for (const button of dropdown._o1igMenu.children) {
|
||
const active = button.dataset.value === nextValue;
|
||
button.classList.toggle("selected", active);
|
||
button.setAttribute("aria-selected", String(active));
|
||
}
|
||
}
|
||
|
||
function setDropdownOptions(dropdown, options, preferred) {
|
||
dropdown._o1igOptions = options.map((option) => (
|
||
typeof option === "string" ? { value: option, label: option } : option
|
||
));
|
||
dropdown._o1igMenu.replaceChildren();
|
||
for (const option of dropdown._o1igOptions) {
|
||
const button = document.createElement("button");
|
||
button.type = "button";
|
||
button.className = "o1ig-select-option";
|
||
button.dataset.value = option.value;
|
||
const optionLabel = document.createElement("span");
|
||
optionLabel.className = "o1ig-select-option-label";
|
||
optionLabel.textContent = option.label;
|
||
button.append(optionLabel);
|
||
if (option.description) {
|
||
button.classList.add("has-description");
|
||
const description = document.createElement("span");
|
||
description.className = "o1ig-select-option-description";
|
||
description.textContent = option.description;
|
||
button.append(description);
|
||
button.title = `${option.label} · ${option.description}`;
|
||
}
|
||
button.setAttribute("role", "option");
|
||
button.addEventListener("click", () => {
|
||
setDropdownValue(dropdown, option.value);
|
||
closeDropdown(dropdown);
|
||
dropdown.dispatchEvent(new Event("change", { bubbles: true }));
|
||
});
|
||
dropdown._o1igMenu.append(button);
|
||
}
|
||
setDropdownValue(dropdown, preferred);
|
||
}
|
||
|
||
function makeDropdown(options, current, title = "") {
|
||
const dropdown = document.createElement("div");
|
||
dropdown.className = "o1ig-select";
|
||
dropdown.title = title;
|
||
dropdown.setAttribute("role", "combobox");
|
||
dropdown.setAttribute("aria-label", title);
|
||
|
||
const trigger = document.createElement("button");
|
||
trigger.type = "button";
|
||
trigger.className = "o1ig-select-trigger";
|
||
trigger.setAttribute("aria-haspopup", "listbox");
|
||
trigger.setAttribute("aria-expanded", "false");
|
||
const valueLabel = document.createElement("span");
|
||
valueLabel.className = "o1ig-select-value";
|
||
const caret = document.createElement("span");
|
||
caret.className = "o1ig-select-caret";
|
||
caret.setAttribute("aria-hidden", "true");
|
||
const caretIcon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||
caretIcon.setAttribute("viewBox", "0 0 12 12");
|
||
caretIcon.setAttribute("focusable", "false");
|
||
const caretPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
|
||
caretPath.setAttribute("d", "M2.25 4.25 6 8l3.75-3.75");
|
||
caretPath.setAttribute("fill", "none");
|
||
caretPath.setAttribute("stroke", "currentColor");
|
||
caretPath.setAttribute("stroke-width", "1.5");
|
||
caretPath.setAttribute("stroke-linecap", "round");
|
||
caretPath.setAttribute("stroke-linejoin", "round");
|
||
caretIcon.append(caretPath);
|
||
caret.append(caretIcon);
|
||
trigger.append(valueLabel, caret);
|
||
|
||
const menu = document.createElement("div");
|
||
menu.className = "o1ig-select-menu";
|
||
menu.setAttribute("role", "listbox");
|
||
dropdown.append(trigger, menu);
|
||
Object.assign(dropdown, {
|
||
_o1igMenu: menu,
|
||
_o1igTrigger: trigger,
|
||
_o1igValueLabel: valueLabel,
|
||
});
|
||
Object.defineProperty(dropdown, "value", {
|
||
get: () => dropdown._o1igValue,
|
||
set: (value) => setDropdownValue(dropdown, value),
|
||
});
|
||
trigger.addEventListener("click", () => {
|
||
const willOpen = !dropdown.classList.contains("open");
|
||
if (openDropdown && openDropdown !== dropdown) closeDropdown();
|
||
dropdown.classList.toggle("open", willOpen);
|
||
trigger.setAttribute("aria-expanded", String(willOpen));
|
||
openDropdown = willOpen ? dropdown : null;
|
||
});
|
||
trigger.addEventListener("keydown", (event) => {
|
||
if (event.key !== "ArrowDown" && event.key !== "Enter" && event.key !== " ") return;
|
||
event.preventDefault();
|
||
if (!dropdown.classList.contains("open")) trigger.click();
|
||
dropdown._o1igMenu.querySelector(".selected")?.focus();
|
||
});
|
||
setDropdownOptions(dropdown, options, current);
|
||
return dropdown;
|
||
}
|
||
|
||
function makeSelect(values, current, title = "") {
|
||
return makeDropdown(values, current, title);
|
||
}
|
||
|
||
function imageCountOptions(model, current) {
|
||
const values = isGptImageModel(model) ? [...GPT_IMAGE_COUNTS] : [...IMAGE_COUNTS];
|
||
if (isGptImageModel(model) && String(current) === "9") values.push("9");
|
||
return values.map((value) => ({ value, label: `${value}张` }));
|
||
}
|
||
|
||
function makeImageCountSelect(current, model) {
|
||
return makeDropdown(imageCountOptions(model, current), String(current ?? "1"), "生图数量");
|
||
}
|
||
|
||
function normalizeImageCount(value, model = "") {
|
||
const normalized = String(value ?? "1");
|
||
return imageCountOptions(model, normalized).some((option) => option.value === normalized) ? normalized : "1";
|
||
}
|
||
|
||
function replaceOptions(select, values, preferred) {
|
||
const optionValues = values.map((option) => typeof option === "string" ? option : option.value);
|
||
setDropdownOptions(
|
||
select,
|
||
values,
|
||
optionValues.includes(preferred) ? preferred : optionValues[0],
|
||
);
|
||
}
|
||
|
||
function makeAdvancedField(labelText, control) {
|
||
const field = document.createElement("div");
|
||
field.className = "o1ig-field-inline-label";
|
||
const label = document.createElement("span");
|
||
label.className = "o1ig-inline-label";
|
||
label.textContent = labelText;
|
||
field.append(label, control);
|
||
return field;
|
||
}
|
||
|
||
function makeInlineLabelField(labelText, control) {
|
||
return makeAdvancedField(labelText, control);
|
||
}
|
||
|
||
function setFieldVisible(field, visible) {
|
||
if (field) field.style.display = visible ? "" : "none";
|
||
}
|
||
|
||
function syncGptOutputOptions(node) {
|
||
if (!node._o1igOutputFormat || !node._o1igBackground) return;
|
||
const model = node._o1igModel?.value;
|
||
let formats;
|
||
if (model === "Seedream 5.0 Pro") {
|
||
formats = SEEDREAM_OUTPUT_FORMATS;
|
||
} else {
|
||
const is26 = /^gpt-image-2\.6-/.test(String(model || ""));
|
||
const hasRefs = (node._o1igReferences || []).length > 0
|
||
|| (node._o1igModelReferences || []).length > 0
|
||
|| Boolean(node._o1igMask);
|
||
formats = [...GPT_OUTPUT_FORMATS];
|
||
if (is26 && !hasRefs) formats = [...formats, ...GPT_26_EXTRA_OUTPUT_FORMATS];
|
||
if (node._o1igBackground.value === "transparent") {
|
||
formats = formats.filter((option) => option.value !== "jpeg" && option.value !== "svg" && option.value !== "gif");
|
||
}
|
||
}
|
||
replaceOptions(node._o1igOutputFormat, formats, node._o1igOutputFormat.value);
|
||
setWidgetValue(node, "输出格式", node._o1igOutputFormat.value);
|
||
setWidgetValue(node, "背景", node._o1igBackground.value);
|
||
const showFrames = /^gpt-image-2\.6-/.test(String(model || ""))
|
||
&& node._o1igOutputFormat.value === "gif";
|
||
setFieldVisible(node._o1igFrameCountField, showFrames);
|
||
setFieldVisible(node._o1igFrameDurationField, showFrames);
|
||
if (node._o1igFrameCount) setWidgetValue(node, "帧数", Number(node._o1igFrameCount.value) || 9);
|
||
if (node._o1igFrameDuration) setWidgetValue(node, "帧时长ms", Number(node._o1igFrameDuration.value) || 200);
|
||
}
|
||
|
||
function generatorSaveSettings(node) {
|
||
const model = node?._o1igModel?.value || findWidget(node, "模型")?.value || "Nano Banana 2.1";
|
||
const capabilities = MODEL_CAPABILITIES[model] || MODEL_CAPABILITIES["Nano Banana 2"];
|
||
return {
|
||
filename_prefix: String(
|
||
node?._o1igFilenamePrefix?.value
|
||
?? findWidget(node, "filename_prefix")?.value
|
||
?? "o1key"
|
||
).trim() || "o1key",
|
||
format: capabilities.saveFormat
|
||
? node?._o1igSaveFormat?.value || findWidget(node, "格式")?.value || "原始"
|
||
: "原始",
|
||
save_location: String(
|
||
node?._o1igSaveLocation?.value
|
||
?? findWidget(node, "保存位置")?.value
|
||
?? ""
|
||
).trim(),
|
||
naming_rule: node?._o1igNamingRule?.value
|
||
|| findWidget(node, "命名规则")?.value
|
||
|| "自定义前缀",
|
||
};
|
||
}
|
||
|
||
function syncGeneratorSaveControls(node) {
|
||
if (!node?._o1igNamingRule) return;
|
||
const capabilities = MODEL_CAPABILITIES[node._o1igModel?.value]
|
||
|| MODEL_CAPABILITIES["Nano Banana 2"];
|
||
setFieldVisible(node._o1igFilenamePrefixField, node._o1igNamingRule.value === "自定义前缀");
|
||
setFieldVisible(node._o1igSaveFormatField, capabilities.saveFormat);
|
||
if (USE_NATIVE_LITEGRAPH_PARAMETERS) {
|
||
setNativeWidgetVisible(node, "filename_prefix", node._o1igNamingRule.value === "自定义前缀");
|
||
setNativeWidgetVisible(node, "格式", capabilities.saveFormat);
|
||
}
|
||
const settings = generatorSaveSettings(node);
|
||
setWidgetValue(node, "命名规则", settings.naming_rule);
|
||
setWidgetValue(node, "filename_prefix", settings.filename_prefix);
|
||
setWidgetValue(node, "格式", node._o1igSaveFormat?.value || "原始");
|
||
setWidgetValue(node, "保存位置", settings.save_location);
|
||
}
|
||
|
||
function syncResizeWarning(node) {
|
||
if (!node._o1igResizeWarning) return;
|
||
const resizeAvailable = node._o1igResizeField?.style.display !== "none";
|
||
node._o1igResizeWarning.classList.toggle(
|
||
"visible",
|
||
resizeAvailable && node._o1igResize?.value === "智能缩放",
|
||
);
|
||
}
|
||
|
||
function statusLineVisible(node) {
|
||
return String(node?._o1igStatus?.className || "").includes("visible");
|
||
}
|
||
|
||
function syncActionsHeight(node) {
|
||
const visible = statusLineVisible(node);
|
||
if (visible === node._o1igStatusVisible) return;
|
||
node._o1igStatusVisible = visible;
|
||
if (!node._o1igActionsWidget) return;
|
||
// The panel is flexible, so the status row is taken from / returned to the prompt area.
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
|
||
function setStatus(node, text = "", kind = "") {
|
||
if (!node._o1igGenerate || !node._o1igStatus) return;
|
||
clearTimeout(node._o1igStatusTimer);
|
||
node._o1igStatus.className = `o1ig-status${text ? " visible" : ""}${kind === "error" ? " error" : ""}`;
|
||
node._o1igStatus.textContent = text;
|
||
node._o1igGenerate.disabled = false;
|
||
node._o1igGenerate.textContent = "开始生成";
|
||
node._o1igGenerate.classList?.remove?.("cancel");
|
||
node._o1igPanel?.classList.toggle("busy", kind === "busy");
|
||
syncActionsHeight(node);
|
||
if (kind === "ok" && text) {
|
||
node._o1igStatusTimer = setTimeout(() => {
|
||
if (!node._o1igRunning) setStatus(node, "", "");
|
||
}, 2200);
|
||
}
|
||
}
|
||
|
||
function setPromptOptimizeStatus(node, text = "", kind = "") {
|
||
const status = node._o1igPromptOptimizeStatus;
|
||
if (!status) return;
|
||
clearTimeout(node._o1igPromptOptimizeStatusTimer);
|
||
status.className = `o1ig-prompt-optimize-status${text ? " visible" : ""}${kind ? ` ${kind}` : ""}`;
|
||
status.textContent = text;
|
||
status.title = text;
|
||
if (text && kind !== "busy") {
|
||
node._o1igPromptOptimizeStatusTimer = setTimeout(() => {
|
||
if (!node._o1igOptimizing) setPromptOptimizeStatus(node);
|
||
}, kind === "error" ? 3600 : 2200);
|
||
}
|
||
}
|
||
|
||
function flagEmptyPrompt(node) {
|
||
// No wording on purpose: pointing at the field is enough, a status line under the button
|
||
// just pushed the layout around and read as noise.
|
||
const wrap = node?._o1igPrompt?.parentElement;
|
||
node?._o1igPrompt?.focus?.();
|
||
if (!wrap?.classList) return;
|
||
wrap.classList.remove("invalid");
|
||
void wrap.offsetWidth; // Restart the shake on every click.
|
||
wrap.classList.add("invalid");
|
||
clearTimeout(node._o1igPromptInvalidTimer);
|
||
node._o1igPromptInvalidTimer = setTimeout(() => {
|
||
wrap.classList?.remove("invalid");
|
||
}, 600);
|
||
}
|
||
|
||
function applyGeneratorSize(node, width, height) {
|
||
if (!(height > 0)) return;
|
||
const currentWidth = Number(node.size?.[0]) || 0;
|
||
const currentHeight = Number(node.size?.[1]) || 0;
|
||
if (Math.abs(currentWidth - width) < 0.5 && Math.abs(currentHeight - height) < 0.5) return;
|
||
node._o1igAutoSizing = true;
|
||
try {
|
||
node.setSize?.([width, height]);
|
||
// Remember the last programmatic height: it is the baseline of the next user drag.
|
||
node._o1igSizedHeight = height;
|
||
} finally {
|
||
node._o1igAutoSizing = false;
|
||
}
|
||
}
|
||
|
||
// A setSize() fired while the pointer is up comes from the engine (node creation, workflow
|
||
// restore, or the Vue layout re-measuring when rows are added/removed). Only a resize with a
|
||
// pressed pointer is a real drag by the user.
|
||
let canvasPointerDown = false;
|
||
let canvasPointerY = 0;
|
||
let canvasPointerStartY = 0;
|
||
let canvasPointerStartX = 0;
|
||
function trackCanvasPointer(event) {
|
||
canvasPointerDown = event.type !== "pointerup" && event.type !== "pointercancel";
|
||
const x = Number(event.clientX);
|
||
const y = Number(event.clientY);
|
||
if (Number.isFinite(y)) canvasPointerY = y;
|
||
if (event.type === "pointerdown") {
|
||
canvasPointerStartX = Number.isFinite(x) ? x : 0;
|
||
canvasPointerStartY = Number.isFinite(y) ? y : 0;
|
||
}
|
||
}
|
||
for (const type of ["pointerdown", "pointerup", "pointercancel", "pointermove"]) {
|
||
document?.addEventListener?.(type, trackCanvasPointer, { capture: true, passive: true });
|
||
}
|
||
window?.addEventListener?.("blur", () => {
|
||
canvasPointerDown = false;
|
||
});
|
||
|
||
function resetCanvasPointerGesture() {
|
||
// Any graph (re)load voids a gesture that never got its pointerup, which otherwise let a
|
||
// stale press turn later re-layouts into "drags" and made the node grow on its own.
|
||
canvasPointerDown = false;
|
||
canvasPointerStartX = 0;
|
||
canvasPointerStartY = 0;
|
||
}
|
||
|
||
function generatorNodeRoot(node) {
|
||
// Vue nodes are real DOM boxes, so the browser itself can say whether a press landed on the
|
||
// node. The canvas transform is not usable there: the DOM box and ds.offset disagree, which
|
||
// made the geometry test reject perfectly good drags. Classic canvas nodes have no such root.
|
||
const panel = node?._o1igPanel;
|
||
const root = panel?.closest?.("[data-node-id]");
|
||
return root && root.contains?.(panel) ? root : null;
|
||
}
|
||
|
||
function pointerStartsInsideNode(node, clientX, clientY) {
|
||
// Menus and dialogs live outside the node box, so a press there can never resize it.
|
||
const x = Number(clientX);
|
||
const y = Number(clientY);
|
||
if (!Number.isFinite(x) || !Number.isFinite(y)) return false;
|
||
if (!(x > 0) || !(y > 0)) return false;
|
||
const root = generatorNodeRoot(node);
|
||
const hit = root ? document?.elementFromPoint?.(x, y) : null;
|
||
if (root && hit) return root === hit || root.contains(hit);
|
||
const ds = node?.graph?.canvas?.ds;
|
||
if (!ds) return false;
|
||
const scale = Number(ds.scale) || 1;
|
||
const localX = (x - (Number(ds.offset?.[0]) || 0)) / scale;
|
||
const localY = (y - (Number(ds.offset?.[1]) || 0)) / scale;
|
||
const width = Number(node?.size?.[0]) || 0;
|
||
const height = Number(node?.size?.[1]) || 0;
|
||
return localX >= node.pos[0] - GENERATOR_DRAG_MARGIN
|
||
&& localX <= node.pos[0] + width + GENERATOR_DRAG_MARGIN
|
||
&& localY >= node.pos[1] - GENERATOR_DRAG_MARGIN
|
||
&& localY <= node.pos[1] + height + GENERATOR_DRAG_MARGIN;
|
||
}
|
||
|
||
function generatorExtraHeight(node) {
|
||
// Height the user dragged beyond the content. Keeping it as a delta (instead of a
|
||
// "manual resize" flag) means the node still shrinks back when rows disappear.
|
||
const raw = Number(node?.properties?.o1keyPanelExtraHeight);
|
||
return Number.isFinite(raw) ? Math.max(0, Math.round(raw)) : 0;
|
||
}
|
||
|
||
function setGeneratorExtraHeight(node, extra) {
|
||
if (!node) return;
|
||
node.properties ??= {};
|
||
const value = Math.max(0, Math.round(Number(extra) || 0));
|
||
if (generatorExtraHeight(node) === value) return;
|
||
node.properties.o1keyPanelExtraHeight = value;
|
||
}
|
||
|
||
function nextGeneratorExtra(anchor, pointerY, heightDelta, scale) {
|
||
// Decides whether a resize event may move the dragged-out height. Returns null when it must
|
||
// be left alone.
|
||
// A width drag (or any engine re-layout) changes the node height while the pointer keeps
|
||
// still: the Vue body resizes itself whenever the panel grows, so folding that height into
|
||
// the extra height fed the node straight back into a runaway loop.
|
||
if (!(anchor?.pointerY > 0)) return anchor.extra + heightDelta;
|
||
const pointerDelta = (Number(pointerY) - anchor.pointerY) / (Number(scale) || 1);
|
||
if (Math.abs(pointerDelta) <= 1) return null;
|
||
// A stale gesture (press swallowed by a menu, then the pointer moved far away) would
|
||
// otherwise fold the whole mouse travel into the extra height and inflate the node.
|
||
if (Math.abs(pointerDelta) > GENERATOR_DRAG_OVERSHOOT) return null;
|
||
return anchor.extra + pointerDelta;
|
||
}
|
||
|
||
function nodeDomScale(node) {
|
||
// CSS pixels inside a node are canvas pixels times the canvas zoom. Read the zoom from the
|
||
// canvas: deriving it from the panel box mixes in DOM rounding and drifts while dragging.
|
||
const scale = Number(node?.graph?.canvas?.ds?.scale);
|
||
if (Number.isFinite(scale) && scale > 0) return scale;
|
||
const panel = node?._o1igPanel;
|
||
const layout = Number(panel?.offsetHeight);
|
||
const painted = Number(panel?.getBoundingClientRect?.().height);
|
||
if (!(layout > 0) || !(painted > 0)) return 1;
|
||
const ratio = painted / layout;
|
||
return Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
|
||
}
|
||
|
||
function generatorPanelDomHeight(node) {
|
||
// Height the panel element itself has to cover: its content plus the dragged-out height.
|
||
// The DOM widget chrome (LiteGraph's margin around every DOM widget) lives outside the
|
||
// element, so it is not part of this number.
|
||
const content = measurePanelContentHeight(node);
|
||
if (content > 0) return content + generatorExtraHeight(node);
|
||
return Math.max(
|
||
GENERATOR_COMPACT_MIN_HEIGHT,
|
||
generatorPanelMinHeight(node) - domWidgetChrome(node?._o1igPanelWidget, node?._o1igPanel),
|
||
);
|
||
}
|
||
|
||
function syncPanelExtraDomHeight(node) {
|
||
const panel = node?._o1igPanel;
|
||
if (!panel?.style) return;
|
||
const extra = generatorExtraHeight(node);
|
||
// Only the Vue node body needs this: its grid rows follow min-content, so whatever the node
|
||
// has beyond the other rows must land on the panel or the grid splits it between its two
|
||
// auto rows (empty strips above the first parameter row and above the button).
|
||
if (!(extra > 0) || !isVueNodesEnabled()) {
|
||
if (panel.style.minHeight) panel.style.minHeight = "";
|
||
return;
|
||
}
|
||
// Never read this back from the laid-out row: the row is scaled by the canvas zoom and
|
||
// re-derived from this very value, which made the target drift while dragging.
|
||
const target = Math.ceil(generatorPanelDomHeight(node));
|
||
if (!(target > 0)) return;
|
||
const current = Number.parseFloat(panel.style.minHeight) || 0;
|
||
if (Math.abs(current - target) <= 1) return;
|
||
panel.style.minHeight = `${target}px`;
|
||
}
|
||
|
||
function fitNode(node) {
|
||
if (!node?._o1igPanelWidget) return;
|
||
// A fresh fit re-bases the drag anchor used by onResize.
|
||
node._o1igDragAnchor = null;
|
||
// Workflows saved before the delta bookkeeping carry this flag; it no longer means anything.
|
||
if (node.properties?.o1keyPanelAutoHeight !== undefined) delete node.properties.o1keyPanelAutoHeight;
|
||
// Any setSize() during creation / workflow restore is engine driven, not a user resize.
|
||
node._o1igSettled = false;
|
||
const enforce = () => {
|
||
const width = Math.max(Number(node.size?.[0]) || 0, GENERATOR_MIN_SIZE[0]);
|
||
// Keep classic computeLayoutSize (getMinHeight) and Vue layout in sync.
|
||
node._o1igPanelWidget.options ??= {};
|
||
node._o1igPanelWidget.options.getMinHeight = () => generatorPanelMinHeight(node);
|
||
// The panel must stay flexible (no computeSize) so it absorbs the node's free space
|
||
// instead of leaving an empty strip under the last parameter row.
|
||
if (node._o1igPanelWidget.computeSize) delete node._o1igPanelWidget.computeSize;
|
||
if (node._o1igActionsWidget) {
|
||
node._o1igActionsWidget.options ??= {};
|
||
node._o1igActionsWidget.options.getMinHeight = () => actionsWidgetHeight(node);
|
||
node._o1igActionsWidget.options.getMaxHeight = () => actionsWidgetHeight(node);
|
||
}
|
||
syncPanelExtraDomHeight(node);
|
||
const contentHeight = generatorContentHeight(node, width);
|
||
// generatorPanelMinHeight() already carries the dragged-out height, so computeSize is
|
||
// the whole story: no leftover slack can appear above the action bar.
|
||
// Keep the engine's height when it already matches within the measurement noise,
|
||
// otherwise the node oscillates by that noise on every fit.
|
||
const currentHeight = Number(node.size?.[1]) || 0;
|
||
const height = Math.abs(currentHeight - contentHeight) <= GENERATOR_FIT_TOLERANCE
|
||
? currentHeight
|
||
: contentHeight;
|
||
applyGeneratorSize(node, width, height);
|
||
node.setDirtyCanvas?.(true, true);
|
||
};
|
||
enforce();
|
||
// DOM widgets are measured once they are attached to the canvas, so re-fit a few times.
|
||
requestAnimationFrame(enforce);
|
||
for (const delay of SETTLE_FIT_DELAYS) {
|
||
setTimeout(() => {
|
||
if (node._o1igPanel) enforce();
|
||
}, delay);
|
||
}
|
||
setTimeout(() => {
|
||
node._o1igSettled = true;
|
||
}, SETTLE_FIT_DELAYS[SETTLE_FIT_DELAYS.length - 1] + 120);
|
||
}
|
||
|
||
function applyGeneratorDefaultSize(node) {
|
||
if (node._o1igDefaultSizeApplied) return;
|
||
node._o1igDefaultSizeApplied = true;
|
||
// Width only: fitNode() then folds the height down to the stacked content.
|
||
applyGeneratorSize(node, GENERATOR_DEFAULT_SIZE[0], GENERATOR_DEFAULT_SIZE[1]);
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
|
||
function generatorOutputs(node) {
|
||
if (!Array.isArray(node?.outputs)) return [];
|
||
if (node.outputs.length >= GENERATOR_OUTPUT_COUNT) {
|
||
node._o1igAllOutputs = node.outputs.slice(0, GENERATOR_OUTPUT_COUNT);
|
||
} else if (Array.isArray(node._o1igAllOutputs)) {
|
||
node.outputs.forEach((output, index) => {
|
||
node._o1igAllOutputs[index] = output;
|
||
});
|
||
}
|
||
return Array.isArray(node._o1igAllOutputs) ? node._o1igAllOutputs : node.outputs;
|
||
}
|
||
|
||
function syncGeneratorOutputVisibility(node) {
|
||
const outputs = generatorOutputs(node);
|
||
if (outputs.length < GENERATOR_OUTPUT_COUNT) return;
|
||
const layerDecomposition = node._o1igModel?.value === "Seedream 5.0 Pro"
|
||
&& node._o1igLayerDecomposition?.value === "开启";
|
||
const connectedOutputCount = outputs.reduce((count, output, index) => (
|
||
output?.links?.length ? Math.max(count, index + 1) : count
|
||
), 1);
|
||
const visibleOutputCount = Math.max(
|
||
layerDecomposition ? GENERATOR_LAYER_OUTPUT_COUNT : 1,
|
||
connectedOutputCount,
|
||
);
|
||
const visibleOutputs = outputs.slice(0, visibleOutputCount);
|
||
if (
|
||
node.outputs.length === visibleOutputs.length
|
||
&& node.outputs.every((output, index) => output === visibleOutputs[index])
|
||
) return;
|
||
node.outputs = visibleOutputs;
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
|
||
function referenceRole(node, role = "references") {
|
||
if (role === "models") {
|
||
return {
|
||
items: node._o1igModelReferences || [],
|
||
pending: node._o1igModelPending || [],
|
||
container: node._o1igModelRefs,
|
||
input: node._o1igModelInput,
|
||
canvasPicker: node._o1igModelCanvasPick,
|
||
widget: "模特图清单",
|
||
label: "目标图",
|
||
commit: "_o1igModelUploadCommit",
|
||
};
|
||
}
|
||
return {
|
||
items: node._o1igReferences || [],
|
||
pending: node._o1igPending || [],
|
||
container: node._o1igRefs,
|
||
input: node._o1igReferenceInput,
|
||
canvasPicker: node._o1igCanvasPick,
|
||
widget: "参考图清单",
|
||
label: node._o1igBatchEnabled ? "素材图" : "参考图",
|
||
commit: "_o1igUploadCommit",
|
||
};
|
||
}
|
||
|
||
const IMAGE_FILE_ACCEPT = "image/png,image/jpeg,image/webp,image/gif,image/bmp";
|
||
|
||
function createReferenceFileInput(node, role = "references") {
|
||
const input = document.createElement("input");
|
||
input.type = "file";
|
||
input.accept = IMAGE_FILE_ACCEPT;
|
||
input.multiple = true;
|
||
input.hidden = true;
|
||
input.addEventListener("change", async () => {
|
||
await acceptFiles(node, input.files, role);
|
||
input.value = "";
|
||
});
|
||
return input;
|
||
}
|
||
|
||
function requestReferenceUpload(node, role = "references") {
|
||
const state = referenceRole(node, role);
|
||
if (!state.input || hasPendingReferenceUploads(node)) return;
|
||
state.input.click();
|
||
}
|
||
|
||
function hasPendingReferenceUploads(node) {
|
||
return Boolean(
|
||
node?._o1igPending?.length
|
||
|| node?._o1igModelPending?.length
|
||
|| node?._o1igReplacing?.size
|
||
|| node?._o1igMaskPending
|
||
);
|
||
}
|
||
|
||
function referenceLimit(node, role = "references") {
|
||
if (node?._o1igLayerDecomposition?.value === "开启") return role === "references" ? 1 : 0;
|
||
if (!node?._o1igBatchEnabled) return MAX_REQUEST_REFERENCES;
|
||
if (role === "models") return MAX_REFERENCES;
|
||
return batchModeOf(node) === BATCH_MODE_GROUP_TO_TARGETS
|
||
? MAX_REQUEST_REFERENCES - 1
|
||
: MAX_REFERENCES;
|
||
}
|
||
|
||
function referenceBadgeDetails(node, role, listIndex) {
|
||
const ordinal = listIndex + 1;
|
||
if (!node?._o1igBatchEnabled) {
|
||
const primary = ordinal === 1 ? " · 主图/色彩基准" : "";
|
||
return {
|
||
label: `图${ordinal}`,
|
||
title: `图${ordinal}${primary}(按当前顺序)`,
|
||
};
|
||
}
|
||
if (batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES) {
|
||
return {
|
||
label: "图1",
|
||
title: `素材图${ordinal} · 作为单张参考图独立生成`,
|
||
};
|
||
}
|
||
const cartesian = batchModeOf(node) === BATCH_MODE_ALL_PAIRS;
|
||
if (role === "models") {
|
||
const referenceCount = node._o1igReferences?.length || 0;
|
||
const requestIndex = referenceCount ? (cartesian ? 2 : referenceCount + 1) : 1;
|
||
return {
|
||
label: `图${requestIndex}`,
|
||
title: `目标图${ordinal} · 在各自请求中是图${requestIndex}`,
|
||
};
|
||
}
|
||
const requestIndex = cartesian ? 1 : ordinal;
|
||
const primary = requestIndex === 1 ? " · 主图/色彩基准" : "";
|
||
return {
|
||
label: `图${requestIndex}`,
|
||
title: `素材图${ordinal} · 在各自请求中是图${requestIndex}${primary}`,
|
||
};
|
||
}
|
||
|
||
function referenceDropDestination(fromIndex, targetIndex, afterTarget) {
|
||
let insertionIndex = targetIndex + (afterTarget ? 1 : 0);
|
||
if (fromIndex < insertionIndex) insertionIndex -= 1;
|
||
return Math.max(0, insertionIndex);
|
||
}
|
||
|
||
function clearReferenceDrag(node) {
|
||
const drag = node?._o1igReferenceDrag;
|
||
if (drag?.tile) drag.tile.classList.remove("o1ig-dragging");
|
||
for (const role of ["references", "models"]) {
|
||
const container = referenceRole(node, role).container;
|
||
container?.classList?.remove("o1ig-reordering");
|
||
for (const child of container?.children || []) {
|
||
child.classList?.remove("o1ig-drop-before");
|
||
child.classList?.remove("o1ig-drop-after");
|
||
}
|
||
}
|
||
if (node) node._o1igReferenceDrag = null;
|
||
}
|
||
|
||
function moveReference(node, role, fromIndex, toIndex, options = {}) {
|
||
const state = referenceRole(node, role);
|
||
if (state.pending.length || state.items.length < 2) return false;
|
||
const from = Math.floor(Number(fromIndex));
|
||
const requestedTarget = Math.floor(Number(toIndex));
|
||
if (!Number.isInteger(from) || !Number.isInteger(requestedTarget)) return false;
|
||
const target = Math.max(0, Math.min(state.items.length - 1, requestedTarget));
|
||
if (from < 0 || from >= state.items.length || from === target) return false;
|
||
const [item] = state.items.splice(from, 1);
|
||
state.items.splice(target, 0, item);
|
||
setWidgetValue(node, state.widget, JSON.stringify(state.items));
|
||
renderReferences(node);
|
||
if (options.focus) {
|
||
requestAnimationFrame(() => node?._o1igReferenceHandles?.[role]?.[target]?.focus?.());
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function handleReferenceOrderKey(event, node, role, index) {
|
||
if (!event.altKey) return false;
|
||
const state = referenceRole(node, role);
|
||
const targets = {
|
||
ArrowLeft: index - 1,
|
||
ArrowRight: index + 1,
|
||
Home: 0,
|
||
End: state.items.length - 1,
|
||
};
|
||
if (!(event.key in targets)) return false;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
moveReference(node, role, index, targets[event.key], { focus: true });
|
||
return true;
|
||
}
|
||
|
||
function beginReferenceDrag(event, node, role, index, tile) {
|
||
const state = referenceRole(node, role);
|
||
if (state.pending.length || state.items.length < 2) {
|
||
event.preventDefault();
|
||
return;
|
||
}
|
||
clearReferenceDrag(node);
|
||
node._o1igReferenceDrag = { role, index, tile };
|
||
node._o1igSuppressReferenceClickUntil = Date.now() + 350;
|
||
tile.classList.add("o1ig-dragging");
|
||
state.container?.classList?.add("o1ig-reordering");
|
||
if (event.dataTransfer) {
|
||
event.dataTransfer.effectAllowed = "move";
|
||
event.dataTransfer.setData?.("text/plain", `${role}:${index}`);
|
||
}
|
||
event.stopPropagation();
|
||
}
|
||
|
||
function markReferenceDrop(event, node, role, targetIndex, tile) {
|
||
const drag = node?._o1igReferenceDrag;
|
||
if (!drag || drag.role !== role) return null;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
const bounds = tile.getBoundingClientRect?.() || { left: 0, width: 0 };
|
||
const afterTarget = Number(event.clientX) >= bounds.left + (bounds.width / 2);
|
||
for (const child of referenceRole(node, role).container?.children || []) {
|
||
child.classList?.remove("o1ig-drop-before");
|
||
child.classList?.remove("o1ig-drop-after");
|
||
}
|
||
if (targetIndex === drag.index) return null;
|
||
tile.classList.add(afterTarget ? "o1ig-drop-after" : "o1ig-drop-before");
|
||
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
|
||
return afterTarget;
|
||
}
|
||
|
||
function completeReferenceDrop(event, node, role, targetIndex, tile) {
|
||
const drag = node?._o1igReferenceDrag;
|
||
if (!drag || drag.role !== role) return;
|
||
const afterTarget = markReferenceDrop(event, node, role, targetIndex, tile);
|
||
const destination = referenceDropDestination(drag.index, targetIndex, afterTarget);
|
||
clearReferenceDrag(node);
|
||
moveReference(node, role, drag.index, destination);
|
||
}
|
||
|
||
async function editReference(node, role, listIndex) {
|
||
const state = referenceRole(node, role);
|
||
const original = state.items[listIndex];
|
||
if (!original) return;
|
||
closeReferenceLightbox();
|
||
try {
|
||
await openReferenceImageEditor({
|
||
sourceUrl: viewUrl(original),
|
||
filename: original.name,
|
||
onConfirm: async ({ blob, filename }) => {
|
||
const file = new File([blob], filename, { type: "image/png" });
|
||
await validateSeedreamReferenceFile(node, file);
|
||
const uploaded = await enqueueImageUpload(file);
|
||
const currentIndex = state.items.indexOf(original);
|
||
if (currentIndex < 0) throw new Error(`${state.label}已被移除,编辑结果未替换`);
|
||
state.items.splice(currentIndex, 1, uploaded);
|
||
setWidgetValue(node, state.widget, JSON.stringify(state.items));
|
||
renderReferences(node);
|
||
toast("success", "图片编辑完成", `${uploaded.name} · 已替换当前${state.label}`);
|
||
},
|
||
});
|
||
} catch (error) {
|
||
toast("error", "无法打开图片编辑器", error?.message || String(error));
|
||
}
|
||
}
|
||
|
||
function requestReferenceReplacement(node, role, original) {
|
||
const input = node?._o1igReplaceInput;
|
||
if (!input || !original || node?._o1igReplacing?.has(original)) return;
|
||
node._o1igReplaceTarget = { role, original };
|
||
input.value = "";
|
||
input.click();
|
||
}
|
||
|
||
async function replaceReference(node, role, original, file) {
|
||
const state = referenceRole(node, role);
|
||
if (!file || !file.type?.startsWith("image/") || !state.items.includes(original)) return false;
|
||
node._o1igReplacing ??= new Map();
|
||
if (node._o1igReplacing.has(original)) return false;
|
||
try {
|
||
await validateSeedreamReferenceFile(node, file);
|
||
} catch (error) {
|
||
toast("error", `无法替换:${file.name}`, error?.message || String(error));
|
||
return false;
|
||
}
|
||
node._o1igReplacing.set(original, file.name);
|
||
renderReferences(node);
|
||
setStatus(node, "替换图片中…", "busy");
|
||
try {
|
||
const uploaded = await enqueueImageUpload(file);
|
||
const currentIndex = state.items.indexOf(original);
|
||
if (currentIndex < 0) throw new Error(`${state.label}已被移除,替换结果未使用`);
|
||
state.items.splice(currentIndex, 1, uploaded);
|
||
setWidgetValue(node, state.widget, JSON.stringify(state.items));
|
||
toast("success", "图片替换完成", `${uploaded.name} · 已替换当前${state.label}`);
|
||
return true;
|
||
} catch (error) {
|
||
toast("error", `替换失败:${file.name}`, error?.message || String(error));
|
||
return false;
|
||
} finally {
|
||
node._o1igReplacing.delete(original);
|
||
renderReferences(node);
|
||
if (hasPendingReferenceUploads(node)) setStatus(node, "上传中…", "busy");
|
||
else if (pendingBatchIds(node).size) updateGeneratorActivity(node);
|
||
else setStatus(node, "", "");
|
||
}
|
||
}
|
||
|
||
function renderReferenceRole(node, role = "references") {
|
||
const state = referenceRole(node, role);
|
||
if (!state.container) return;
|
||
node._o1igReferenceHandles ??= {};
|
||
node._o1igReferenceHandles[role] = [];
|
||
state.container.replaceChildren();
|
||
const entries = [
|
||
...state.items.map((item, index) => ({ item, index, pending: false })),
|
||
...state.pending.map((item) => ({ item, index: -1, pending: true })),
|
||
];
|
||
for (const entry of entries) {
|
||
const tile = document.createElement("div");
|
||
const replacing = !entry.pending && node?._o1igReplacing?.has(entry.item);
|
||
tile.className = `o1ig-thumb${entry.pending ? " pending" : replacing ? " replacing" : " previewable"}`;
|
||
const image = document.createElement("img");
|
||
if (!entry.pending) {
|
||
image.src = thumbnailUrl(entry.item);
|
||
image.loading = "lazy";
|
||
image.decoding = "async";
|
||
}
|
||
image.alt = entry.item.name;
|
||
image.draggable = false;
|
||
if (!entry.pending) {
|
||
const sortingLocked = replacing || state.pending.length > 0 || state.items.length < 2;
|
||
tile.draggable = !sortingLocked;
|
||
tile.classList.toggle("sort-locked", sortingLocked);
|
||
image.className = "o1ig-previewable";
|
||
image.tabIndex = 0;
|
||
image.setAttribute("role", "button");
|
||
image.setAttribute("aria-label", sortingLocked ? "查看大图" : "查看大图;按住拖动可排序");
|
||
image.addEventListener("click", (event) => {
|
||
if (Date.now() < Number(node?._o1igSuppressReferenceClickUntil || 0)) {
|
||
event.preventDefault?.();
|
||
event.stopPropagation();
|
||
return;
|
||
}
|
||
event.stopPropagation();
|
||
showReferenceLightbox(node, role, entry.index);
|
||
});
|
||
image.addEventListener("keydown", (event) => {
|
||
if (handleReferenceOrderKey(event, node, role, entry.index)) return;
|
||
if (event.key !== "Enter" && event.key !== " ") return;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
showReferenceLightbox(node, role, entry.index);
|
||
});
|
||
tile.addEventListener("dragstart", (event) => beginReferenceDrag(event, node, role, entry.index, tile));
|
||
tile.addEventListener("dragend", () => clearReferenceDrag(node));
|
||
tile.addEventListener("dragover", (event) => markReferenceDrop(event, node, role, entry.index, tile));
|
||
tile.addEventListener("drop", (event) => completeReferenceDrop(event, node, role, entry.index, tile));
|
||
node._o1igReferenceHandles[role][entry.index] = image;
|
||
}
|
||
tile.append(image);
|
||
if (!entry.pending) {
|
||
const edit = document.createElement("button");
|
||
edit.type = "button";
|
||
edit.className = "o1ig-edit";
|
||
edit.textContent = "✎";
|
||
edit.title = "编辑图片";
|
||
edit.setAttribute("aria-label", `编辑${state.label}${entry.index + 1}`);
|
||
edit.draggable = false;
|
||
edit.disabled = replacing;
|
||
edit.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||
edit.addEventListener("dragstart", (event) => event.preventDefault());
|
||
edit.addEventListener("click", (event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
editReference(node, role, entry.index);
|
||
});
|
||
tile.append(edit);
|
||
const replace = document.createElement("button");
|
||
replace.type = "button";
|
||
replace.className = "o1ig-replace";
|
||
replace.textContent = "替换";
|
||
replace.title = `替换这张${state.label}`;
|
||
replace.setAttribute("aria-label", `替换${state.label}${entry.index + 1}`);
|
||
replace.draggable = false;
|
||
replace.disabled = replacing;
|
||
replace.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||
replace.addEventListener("dragstart", (event) => event.preventDefault());
|
||
replace.addEventListener("click", (event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
requestReferenceReplacement(node, role, entry.item);
|
||
});
|
||
tile.append(replace);
|
||
const badges = referenceBadgeDetails(node, role, entry.index);
|
||
const index = document.createElement("span");
|
||
index.className = "o1ig-reference-index";
|
||
index.textContent = badges.label;
|
||
index.title = badges.title;
|
||
tile.append(index);
|
||
tile.title = badges.title;
|
||
const remove = document.createElement("button");
|
||
remove.type = "button";
|
||
remove.className = "o1ig-remove";
|
||
remove.textContent = "×";
|
||
remove.title = "移除";
|
||
remove.disabled = replacing;
|
||
remove.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
state.items.splice(entry.index, 1);
|
||
setWidgetValue(node, state.widget, JSON.stringify(state.items));
|
||
renderReferences(node);
|
||
});
|
||
tile.append(remove);
|
||
}
|
||
state.container.append(tile);
|
||
}
|
||
const upload = document.createElement("button");
|
||
upload.type = "button";
|
||
upload.className = "o1ig-empty-reference";
|
||
const icon = document.createElement("b");
|
||
icon.textContent = "+";
|
||
const label = document.createElement("span");
|
||
label.textContent = `添加${state.label}`;
|
||
upload.append(icon, label);
|
||
upload.addEventListener("click", () => requestReferenceUpload(node, role));
|
||
bindImageFileDropTarget(node, upload, role);
|
||
state.container.append(upload);
|
||
}
|
||
|
||
function renderReferences(node) {
|
||
if (node?._o1igReferenceDrag) clearReferenceDrag(node);
|
||
renderReferenceRole(node, "references");
|
||
renderReferenceRole(node, "models");
|
||
updateBatchSummary(node);
|
||
syncGptOutputOptions(node);
|
||
syncClearReferenceButtons(node);
|
||
}
|
||
|
||
function referenceListsAreEmpty(node) {
|
||
return !(
|
||
(node?._o1igReferences?.length || 0)
|
||
|| (node?._o1igPending?.length || 0)
|
||
|| (node?._o1igModelReferences?.length || 0)
|
||
|| (node?._o1igModelPending?.length || 0)
|
||
);
|
||
}
|
||
|
||
function syncClearReferenceButtons(node) {
|
||
const empty = referenceListsAreEmpty(node);
|
||
if (node?._o1igClearReferences) {
|
||
node._o1igClearReferences.disabled = empty;
|
||
node._o1igClearReferences.title = empty ? "暂无参考图可清空" : "清空全部参考图与目标图";
|
||
}
|
||
if (node?._o1igClearModelReferences) {
|
||
node._o1igClearModelReferences.disabled = empty;
|
||
node._o1igClearModelReferences.title = empty ? "暂无图片可清空" : "清空全部素材图与目标图";
|
||
}
|
||
}
|
||
|
||
/** Clear every reference image list the panel uses for generation (batch + non-batch). */
|
||
function clearAllReferences(node) {
|
||
if (!node || referenceListsAreEmpty(node)) return false;
|
||
node._o1igReferences = [];
|
||
node._o1igPending = [];
|
||
node._o1igModelReferences = [];
|
||
node._o1igModelPending = [];
|
||
// Follow single-tile remove: mask stays on its own control.
|
||
setWidgetValue(node, "参考图清单", "[]");
|
||
setWidgetValue(node, "模特图清单", "[]");
|
||
renderReferences(node);
|
||
return true;
|
||
}
|
||
|
||
async function acceptFiles(node, files, role = "references") {
|
||
const state = referenceRole(node, role);
|
||
const limit = referenceLimit(node, role);
|
||
const imageFiles = Array.from(files || []).filter((file) => file.type.startsWith("image/"));
|
||
if (!imageFiles.length) return;
|
||
const remaining = limit - state.items.length - state.pending.length;
|
||
if (remaining <= 0) {
|
||
toast("warn", `${state.label}已满`, `最多 ${limit} 张`);
|
||
return;
|
||
}
|
||
const selected = imageFiles.slice(0, remaining);
|
||
if (selected.length < imageFiles.length) toast("warn", `部分${state.label}未上传`, `最多 ${limit} 张`);
|
||
|
||
const validated = [];
|
||
for (const file of selected) {
|
||
try {
|
||
await validateSeedreamReferenceFile(node, file);
|
||
validated.push(file);
|
||
} catch (error) {
|
||
toast("error", `未上传:${file.name}`, error?.message || String(error));
|
||
}
|
||
}
|
||
if (!validated.length) return;
|
||
|
||
const pendingEntries = validated.map((file) => ({
|
||
file,
|
||
pending: { name: file.name },
|
||
}));
|
||
state.pending.push(...pendingEntries.map((entry) => entry.pending));
|
||
renderReferences(node);
|
||
setStatus(node, "上传中…", "busy");
|
||
|
||
const uploadResults = Promise.allSettled(
|
||
pendingEntries.map((entry) => enqueueImageUpload(entry.file)),
|
||
);
|
||
// Upload groups can overlap, but their files share the serialized upload
|
||
// queue and each group still commits in its original selection order.
|
||
const previousCommit = node[state.commit] || Promise.resolve();
|
||
const commit = previousCommit.then(async () => {
|
||
const results = await uploadResults;
|
||
for (let index = 0; index < results.length; index += 1) {
|
||
const result = results[index];
|
||
const entry = pendingEntries[index];
|
||
if (result.status === "fulfilled") {
|
||
state.items.push(result.value);
|
||
} else {
|
||
toast("error", `上传失败:${entry.file.name}`, result.reason?.message || String(result.reason));
|
||
}
|
||
const pendingIndex = state.pending.indexOf(entry.pending);
|
||
if (pendingIndex >= 0) state.pending.splice(pendingIndex, 1);
|
||
}
|
||
setWidgetValue(node, state.widget, JSON.stringify(state.items));
|
||
renderReferences(node);
|
||
});
|
||
node[state.commit] = commit.catch(() => {});
|
||
await commit;
|
||
if (hasPendingReferenceUploads(node)) {
|
||
setStatus(node, "上传中…", "busy");
|
||
}
|
||
else if (pendingBatchIds(node).size) updateGeneratorActivity(node);
|
||
else setStatus(node, "", "");
|
||
}
|
||
|
||
function isExternalFileDrag(event) {
|
||
const transfer = event?.dataTransfer;
|
||
if (!transfer) return false;
|
||
if (Array.from(transfer.files || []).length) return true;
|
||
if (Array.from(transfer.items || []).some((item) => item?.kind === "file")) return true;
|
||
return Array.from(transfer.types || []).includes("Files");
|
||
}
|
||
|
||
function clearImageFileDropHighlight(node, target, role = "references") {
|
||
target?.classList?.remove("drag");
|
||
const state = referenceRole(node, role);
|
||
state.container?.classList?.remove("drag");
|
||
}
|
||
|
||
function bindImageFileDropTarget(node, target, role = "references") {
|
||
if (!target || target._o1igFileDropBound) return;
|
||
target._o1igFileDropBound = true;
|
||
for (const eventName of ["dragenter", "dragover"]) {
|
||
target.addEventListener(eventName, (event) => {
|
||
if (!isExternalFileDrag(event)) return;
|
||
event.preventDefault();
|
||
event.stopPropagation?.();
|
||
target.classList.add("drag");
|
||
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
|
||
});
|
||
}
|
||
target.addEventListener("dragleave", (event) => {
|
||
if (!isExternalFileDrag(event)) return;
|
||
if (event.relatedTarget && target.contains?.(event.relatedTarget)) return;
|
||
target.classList.remove("drag");
|
||
});
|
||
target.addEventListener("drop", (event) => {
|
||
if (!isExternalFileDrag(event)) return;
|
||
event.preventDefault();
|
||
event.stopPropagation?.();
|
||
clearImageFileDropHighlight(node, target, role);
|
||
void acceptFiles(node, event.dataTransfer?.files, role);
|
||
});
|
||
}
|
||
|
||
function imageMimeForFilename(filename) {
|
||
const extension = String(filename || "").split(".").pop()?.toLowerCase();
|
||
return {
|
||
png: "image/png",
|
||
jpg: "image/jpeg",
|
||
jpeg: "image/jpeg",
|
||
webp: "image/webp",
|
||
gif: "image/gif",
|
||
bmp: "image/bmp",
|
||
}[extension] || "image/png";
|
||
}
|
||
|
||
async function readCanvasImageFile(descriptor) {
|
||
const normalized = canvasImageDescriptor(descriptor);
|
||
const path = viewPath(normalized);
|
||
if (!normalized || !path) throw new Error("画布图片描述无效");
|
||
const response = await api.fetchApi(path, { method: "GET", cache: "no-store" });
|
||
if (!response.ok) throw new Error(`无法读取画布图片:${normalized.filename}`);
|
||
const blob = await response.blob();
|
||
const type = blob.type?.startsWith("image/")
|
||
? blob.type
|
||
: imageMimeForFilename(normalized.filename);
|
||
return new File([blob], normalized.filename, { type });
|
||
}
|
||
|
||
async function importCanvasImage(node, descriptor, role = "references") {
|
||
const file = await readCanvasImageFile(descriptor);
|
||
await acceptFiles(node, [file], role);
|
||
}
|
||
|
||
function closeCanvasImagePicker() {
|
||
const picker = document.getElementById(CANVAS_IMAGE_PICKER_ID);
|
||
if (!picker) return;
|
||
document.removeEventListener("keydown", picker._o1igKeydown);
|
||
picker.remove();
|
||
}
|
||
|
||
function openCanvasImagePicker(node, role = "references", options = null) {
|
||
injectStyles();
|
||
closeCanvasImagePicker();
|
||
const customTarget = options && typeof options.onSelect === "function";
|
||
const state = customTarget
|
||
? { label: String(options.label || "图片") }
|
||
: referenceRole(node, role);
|
||
const limit = customTarget ? Math.max(1, Number(options.limit) || 1) : referenceLimit(node, role);
|
||
const remaining = customTarget
|
||
? Math.max(0, Number(options.remaining ?? limit) || 0)
|
||
: limit - state.items.length - state.pending.length;
|
||
if (remaining <= 0) {
|
||
toast("warn", `${state.label}已满`, `最多 ${limit} 张`);
|
||
return null;
|
||
}
|
||
|
||
const candidates = canvasImageCandidates(node);
|
||
const overlay = document.createElement("div");
|
||
overlay.id = CANVAS_IMAGE_PICKER_ID;
|
||
overlay.className = "o1ig-canvas-picker";
|
||
overlay.setAttribute("role", "dialog");
|
||
overlay.setAttribute("aria-modal", "true");
|
||
overlay.setAttribute("aria-label", "从画布取图");
|
||
|
||
const dialog = document.createElement("div");
|
||
dialog.className = "o1ig-canvas-picker-dialog";
|
||
const header = document.createElement("div");
|
||
header.className = "o1ig-canvas-picker-header";
|
||
const title = document.createElement("strong");
|
||
title.textContent = `从画布添加${state.label}`;
|
||
const hint = document.createElement("span");
|
||
hint.textContent = "选择已执行节点的图片结果";
|
||
const close = document.createElement("button");
|
||
close.type = "button";
|
||
close.className = "o1ig-canvas-picker-close";
|
||
close.textContent = "×";
|
||
close.title = "关闭";
|
||
close.setAttribute("aria-label", "关闭");
|
||
close.addEventListener("click", closeCanvasImagePicker);
|
||
header.append(title, hint, close);
|
||
|
||
const grid = document.createElement("div");
|
||
grid.className = "o1ig-canvas-picker-grid";
|
||
if (!candidates.length) {
|
||
const empty = document.createElement("div");
|
||
empty.className = "o1ig-canvas-picker-empty";
|
||
empty.textContent = "画布中暂无可用图片,请先执行裁剪、预览或保存节点。";
|
||
grid.append(empty);
|
||
} else {
|
||
for (const candidate of candidates) {
|
||
const card = document.createElement("button");
|
||
card.type = "button";
|
||
card.className = "o1ig-canvas-picker-card";
|
||
card.title = `${candidate.sourceLabel} · ${candidate.descriptor.filename}`;
|
||
const image = document.createElement("img");
|
||
image.src = viewUrl(candidate.descriptor);
|
||
image.alt = candidate.descriptor.filename;
|
||
image.loading = "lazy";
|
||
const source = document.createElement("strong");
|
||
source.textContent = candidate.sourceLabel;
|
||
const filename = document.createElement("span");
|
||
filename.textContent = candidate.descriptor.filename;
|
||
card.append(image, source, filename);
|
||
card.addEventListener("click", async () => {
|
||
card.disabled = true;
|
||
try {
|
||
if (customTarget) await options.onSelect(candidate.descriptor);
|
||
else await importCanvasImage(node, candidate.descriptor, role);
|
||
closeCanvasImagePicker();
|
||
toast("success", `${state.label}已添加`, candidate.descriptor.filename);
|
||
} catch (error) {
|
||
card.disabled = false;
|
||
toast("error", "画布取图失败", error?.message || String(error));
|
||
}
|
||
});
|
||
grid.append(card);
|
||
}
|
||
}
|
||
|
||
dialog.append(header, grid);
|
||
overlay.append(dialog);
|
||
overlay.addEventListener("mousedown", (event) => {
|
||
if (event.target === overlay) closeCanvasImagePicker();
|
||
});
|
||
overlay._o1igKeydown = (event) => {
|
||
if (event.key === "Escape") closeCanvasImagePicker();
|
||
};
|
||
document.addEventListener("keydown", overlay._o1igKeydown);
|
||
document.body.append(overlay);
|
||
close.focus();
|
||
return overlay;
|
||
}
|
||
|
||
// Other o1key media panels reuse the exact same candidate discovery, dialog,
|
||
// and /view reader through this namespaced frontend capability.
|
||
window.o1keyCanvasImagePicker = Object.freeze({
|
||
open(node, options) {
|
||
return openCanvasImagePicker(node, "references", options);
|
||
},
|
||
readFile: readCanvasImageFile,
|
||
});
|
||
|
||
function getGraphLink(graph, linkId) {
|
||
return graph?.links?.get?.(linkId) ?? graph?.links?.[linkId] ?? null;
|
||
}
|
||
|
||
function findConnectedSaveNodesAtOutput(node, outputIndex = 0) {
|
||
const graph = node.graph || app.graph;
|
||
const results = [];
|
||
const output = generatorOutputs(node)[outputIndex];
|
||
for (const linkId of output?.links || []) {
|
||
const link = getGraphLink(graph, linkId);
|
||
const target = link ? graph.getNodeById?.(link.target_id) : null;
|
||
if (target?.type === SAVE_NODE_TYPE || target?.comfyClass === SAVE_NODE_TYPE) results.push(target);
|
||
}
|
||
return results;
|
||
}
|
||
|
||
function findConnectedSaveNode(node) {
|
||
return findConnectedSaveNodesAtOutput(node, 0)[0] || null;
|
||
}
|
||
|
||
function findConnectedSaveNodes(node) {
|
||
return findConnectedSaveNodesAtOutput(node, 0);
|
||
}
|
||
|
||
function findAllConnectedSaveNodes(node) {
|
||
const unique = new Map();
|
||
generatorOutputs(node).forEach((_output, outputIndex) => {
|
||
for (const saveNode of findConnectedSaveNodesAtOutput(node, outputIndex)) {
|
||
unique.set(String(saveNode.id), saveNode);
|
||
}
|
||
});
|
||
return [...unique.values()];
|
||
}
|
||
|
||
function isBlankSaveNode(node) {
|
||
if (
|
||
!node
|
||
|| node._o1igsBusy
|
||
|| savingSaveBatchIds(node).size
|
||
|| node._o1igsStandardQueueReserved
|
||
|| node._o1igsStandardExecutionPending
|
||
) return false;
|
||
if (Array.isArray(node.imgs) && node.imgs.length) return false;
|
||
if (normalizeSaveResults(node._o1igsLastResults).length) return false;
|
||
if (storedSaveResults(node).length) return false;
|
||
return !normalizeSaveResults(app.nodeOutputs?.[String(node.id)]?.images).length;
|
||
}
|
||
|
||
function findBlankConnectedSaveNode(node) {
|
||
return findConnectedSaveNodes(node).find(isBlankSaveNode) || null;
|
||
}
|
||
|
||
function bindSaveNodeToBatch(source, saveNode, batchId) {
|
||
saveNode.properties ??= {};
|
||
saveNode.properties.o1keyBatchId = batchId;
|
||
saveNode.properties.o1keyGeneratorNodeId = source.id;
|
||
delete saveNode.properties.o1keyBatchTerminal;
|
||
return saveNode;
|
||
}
|
||
|
||
function findLegacyAutoSaveNodes(node) {
|
||
const graph = node.graph || app.graph;
|
||
const legacyNodes = [];
|
||
for (const linkId of [...(node.outputs?.[0]?.links || [])]) {
|
||
const link = getGraphLink(graph, linkId);
|
||
const target = link ? graph.getNodeById?.(link.target_id) : null;
|
||
const isNativeSave = target?.type === "SaveImage" || target?.comfyClass === "SaveImage";
|
||
const prefix = findWidget(target, "filename_prefix")?.value;
|
||
const isLegacyO1keyNode = target?.properties?.o1keyAutoCreated === true || prefix === "o1key";
|
||
if (isNativeSave && isLegacyO1keyNode) legacyNodes.push(target);
|
||
}
|
||
return legacyNodes;
|
||
}
|
||
|
||
function removeLegacyAutoSaveNodes(node) {
|
||
const graph = node.graph || app.graph;
|
||
if (!graph?.remove) return;
|
||
const legacyNodes = findLegacyAutoSaveNodes(node);
|
||
legacyNodes.forEach((legacyNode) => graph.remove(legacyNode));
|
||
}
|
||
|
||
function ensureSaveNode(node) {
|
||
const existing = findConnectedSaveNode(node);
|
||
const graph = node.graph || app.graph;
|
||
const LiteGraph = window.LiteGraph;
|
||
if (!graph || !LiteGraph?.createNode) throw new Error("无法访问 ComfyUI 画布");
|
||
const legacyNodes = findLegacyAutoSaveNodes(node);
|
||
|
||
if (existing) {
|
||
if (legacyNodes.length) {
|
||
graph.beforeChange?.();
|
||
try {
|
||
removeLegacyAutoSaveNodes(node);
|
||
} finally {
|
||
graph.afterChange?.();
|
||
}
|
||
}
|
||
return existing;
|
||
}
|
||
|
||
const saveNode = LiteGraph.createNode(SAVE_NODE_TYPE);
|
||
if (!saveNode) throw new Error("无法创建 o1key 保存图像节点,请重启 ComfyUI");
|
||
const legacyPosition = legacyNodes[0]?.pos;
|
||
|
||
graph.beforeChange?.();
|
||
try {
|
||
removeLegacyAutoSaveNodes(node);
|
||
saveNode.pos = legacyPosition
|
||
? [legacyPosition[0], legacyPosition[1]]
|
||
: nextHorizontalSaveNodePos(node, findAllConnectedSaveNodes(node));
|
||
saveNode.properties ??= {};
|
||
saveNode.properties.o1keyAutoCreated = true;
|
||
graph.add(saveNode);
|
||
const prefix = saveNode.widgets?.find((widget) => widget.name === "filename_prefix");
|
||
if (prefix) prefix.value = "o1key";
|
||
node.connect(0, saveNode, 0);
|
||
graph.setDirtyCanvas?.(true, true);
|
||
return saveNode;
|
||
} finally {
|
||
graph.afterChange?.();
|
||
}
|
||
}
|
||
|
||
function isVueNodesEnabled() {
|
||
try {
|
||
if (window.LiteGraph?.vueNodesMode === true) return true;
|
||
return Boolean(app?.ui?.settings?.getSettingValue?.("Comfy.VueNodes.Enabled"));
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function nodeTitleChromeHeight() {
|
||
const title = Number(window.LiteGraph?.NODE_TITLE_HEIGHT);
|
||
if (Number.isFinite(title) && title >= 0) {
|
||
// Vue Nodes often keep the title outside the body box (title height 0).
|
||
if (isVueNodesEnabled()) return title > 0 ? title : 0;
|
||
return title > 0 ? title : 30;
|
||
}
|
||
return isVueNodesEnabled() ? 0 : 30;
|
||
}
|
||
|
||
function generatorChromeHeight() {
|
||
// Classic LiteGraph folds title + widget padding into node.size.
|
||
// Vue Nodes body size is closer to content; keep a small inset only.
|
||
return isVueNodesEnabled()
|
||
? 16
|
||
: nodeTitleChromeHeight() + 18;
|
||
}
|
||
|
||
function generatorMinimumHeight(node) {
|
||
const denseLayout = isGptImageModel(node?._o1igModel?.value);
|
||
if (node?._o1igBatchEnabled) {
|
||
return denseLayout ? GENERATOR_DENSE_BATCH_MIN_HEIGHT : GENERATOR_BATCH_MIN_HEIGHT;
|
||
}
|
||
return denseLayout ? GENERATOR_DENSE_MIN_HEIGHT : GENERATOR_MIN_SIZE[1];
|
||
}
|
||
|
||
function domWidgetChrome(widget, element) {
|
||
// LiteGraph reserves a margin around every DOM widget (10px top + bottom by default).
|
||
// Keep the value self-calibrating so a frontend theme change cannot leave a gap.
|
||
const computed = Number(widget?.computedHeight);
|
||
const laidOut = Number(element?.offsetHeight);
|
||
if (computed > 0 && laidOut > 0 && computed > laidOut) {
|
||
const chrome = computed - laidOut;
|
||
if (chrome >= 8 && chrome <= 40) return chrome;
|
||
}
|
||
return DOM_WIDGET_CHROME;
|
||
}
|
||
|
||
function measurePanelContentHeight(node) {
|
||
const panel = node?._o1igPanel;
|
||
const children = panel?.children;
|
||
if (!children?.length) return 0;
|
||
let total = 0;
|
||
let count = 0;
|
||
for (const child of children) {
|
||
// Heights come from layout (offsetHeight) so they stay correct on a zoomed canvas.
|
||
// Flexible children report their current grown height, so fall back to the CSS basis.
|
||
const basis = Number(child?.dataset?.o1igHeight) || 0;
|
||
const height = basis > 0 ? basis : Number(child?.offsetHeight) || 0;
|
||
if (height <= 0) continue;
|
||
total += height;
|
||
count += 1;
|
||
}
|
||
if (count < 2) return 0; // Panel not laid out yet.
|
||
return Math.ceil(total + (count - 1) * PANEL_CONTENT_GAP + PANEL_CONTENT_PADDING);
|
||
}
|
||
|
||
function generatorPanelMinHeight(node) {
|
||
// The dragged-out height belongs to the prompt area: the Vue node grid sizes rows from the
|
||
// panel's min-content height, so folding it in here (instead of leaving it to the node body)
|
||
// is what makes the textarea grow while the parameter rows stay flush against the button.
|
||
const extra = generatorExtraHeight(node);
|
||
if (USE_NATIVE_LITEGRAPH_PARAMETERS) {
|
||
const measured = measurePanelContentHeight(node);
|
||
if (measured > 0) return measured + extra + domWidgetChrome(node?._o1igPanelWidget, node?._o1igPanel);
|
||
return (node?._o1igBatchEnabled ? 500 : 360) + extra;
|
||
}
|
||
const fallback = Math.max(292, generatorMinimumHeight(node) - generatorChromeHeight());
|
||
const measured = measurePanelContentHeight(node);
|
||
return measured > 0 ? measured + extra + domWidgetChrome(node?._o1igPanelWidget, node?._o1igPanel) : fallback + extra;
|
||
}
|
||
|
||
function actionsContentHeight(node) {
|
||
return ACTIONS_BASE_HEIGHT + (statusLineVisible(node) ? ACTIONS_STATUS_HEIGHT : 0);
|
||
}
|
||
|
||
function actionsWidgetHeight(node) {
|
||
return actionsContentHeight(node) + domWidgetChrome(node?._o1igActionsWidget, node?._o1igActions);
|
||
}
|
||
|
||
function generatorContentHeight(node, width) {
|
||
// LiteGraph owns widget stacking: let it sum every widget (panel, native params, action bar).
|
||
const computed = Number(node?.computeSize?.([width])?.[1]) || 0;
|
||
const fallback = generatorMinimumHeight(node);
|
||
return Math.max(GENERATOR_COMPACT_MIN_HEIGHT, computed || fallback);
|
||
}
|
||
|
||
function measureNodeExtent(node, fallbackSize = SAVE_NODE_LAYOUT_SIZE) {
|
||
const rawWidth = Number(node?.size?.[0]) || 0;
|
||
const rawHeight = Number(node?.size?.[1]) || 0;
|
||
const width = rawWidth > 0 ? rawWidth : Number(fallbackSize?.[0]) || 0;
|
||
const height = rawHeight > 0 ? rawHeight : Number(fallbackSize?.[1]) || 0;
|
||
const x = Number(node?.pos?.[0]) || 0;
|
||
const y = Number(node?.pos?.[1]) || 0;
|
||
return {
|
||
x,
|
||
y,
|
||
width,
|
||
height,
|
||
right: x + width,
|
||
bottom: y + height,
|
||
};
|
||
}
|
||
|
||
function nextHorizontalSaveNodePos(generator, existingNodes = [], outputIndex = 0) {
|
||
const generatorExtent = measureNodeExtent(generator, [
|
||
Math.max(Number(generator?.size?.[0]) || 0, GENERATOR_MIN_SIZE[0]),
|
||
Math.max(Number(generator?.size?.[1]) || 0, GENERATOR_MIN_SIZE[1]),
|
||
]);
|
||
const originGap = SAVE_NODE_LAYOUT_ORIGIN_GAP_X;
|
||
const gapX = SAVE_NODE_LAYOUT_GAP_X;
|
||
// Keep classic optical offset under LiteGraph; Vue body already aligns with the title bar.
|
||
const defaultY = generatorExtent.y + (isVueNodesEnabled() ? 0 : 30);
|
||
void outputIndex;
|
||
|
||
const peers = (Array.isArray(existingNodes) ? existingNodes : []).filter(Boolean);
|
||
if (!peers.length) {
|
||
return [generatorExtent.right + originGap, defaultY];
|
||
}
|
||
|
||
let rightmost = null;
|
||
for (const peer of peers) {
|
||
const extent = measureNodeExtent(peer);
|
||
if (!rightmost || extent.right > rightmost.right + 0.5) rightmost = extent;
|
||
else if (rightmost && Math.abs(extent.right - rightmost.right) <= 0.5 && extent.y < rightmost.y) {
|
||
rightmost = extent;
|
||
}
|
||
}
|
||
|
||
let x = rightmost.right + gapX;
|
||
const y = Number.isFinite(rightmost.y) ? rightmost.y : defaultY;
|
||
// Push further right until the reserved layout box no longer overlaps peers.
|
||
for (let guard = 0; guard < 64; guard += 1) {
|
||
let hit = null;
|
||
for (const peer of peers) {
|
||
const extent = measureNodeExtent(peer);
|
||
const overlapsX = x < extent.right + 1 && (x + SAVE_NODE_LAYOUT_SIZE[0]) > extent.x - 1;
|
||
const overlapsY = y < extent.bottom + 1 && (y + SAVE_NODE_LAYOUT_SIZE[1]) > extent.y - 1;
|
||
if (overlapsX && overlapsY) {
|
||
hit = extent;
|
||
break;
|
||
}
|
||
}
|
||
if (!hit) break;
|
||
x = hit.right + gapX;
|
||
}
|
||
return [x, y];
|
||
}
|
||
|
||
function estimateSaveNodeChromeHeight(node) {
|
||
// Prefer a style-aware constant. Deriving chrome from current node.height
|
||
// while resizing creates a feedback loop that prevents shrinking.
|
||
void node;
|
||
return isVueNodesEnabled() ? SAVE_NODE_CHROME_VUE_FALLBACK : SAVE_NODE_CHROME_FALLBACK;
|
||
}
|
||
|
||
function createSaveNodeForBatch(node, batchId = createBatchId(), outputIndex = 0) {
|
||
const graph = node.graph || app.graph;
|
||
const LiteGraph = window.LiteGraph;
|
||
if (!graph || !LiteGraph?.createNode) throw new Error("无法访问 ComfyUI 画布");
|
||
|
||
const saveNode = LiteGraph.createNode(SAVE_NODE_TYPE);
|
||
if (!saveNode) throw new Error("无法创建 o1key 保存图像节点,请重启 ComfyUI");
|
||
|
||
const connectedSaveNodes = findAllConnectedSaveNodes(node);
|
||
const batchIndex = connectedSaveNodes.reduce((maximum, connectedNode, index) => {
|
||
const savedIndex = Number(connectedNode.properties?.o1keyBatchIndex) || index + 1;
|
||
return Math.max(maximum, savedIndex);
|
||
}, 0);
|
||
|
||
graph.beforeChange?.();
|
||
try {
|
||
saveNode.pos = nextHorizontalSaveNodePos(node, connectedSaveNodes, outputIndex);
|
||
saveNode.properties ??= {};
|
||
saveNode.properties.o1keyAutoCreated = true;
|
||
saveNode.properties.o1keyBatchIndex = batchIndex + 1;
|
||
if (batchId) bindSaveNodeToBatch(node, saveNode, batchId);
|
||
else saveNode.properties.o1keyGeneratorNodeId = node.id;
|
||
graph.add(saveNode);
|
||
node.connect(outputIndex, saveNode, 0);
|
||
graph.setDirtyCanvas?.(true, true);
|
||
return saveNode;
|
||
} finally {
|
||
graph.afterChange?.();
|
||
}
|
||
}
|
||
|
||
function acquireSaveNodeForBatch(node, batchId) {
|
||
const blank = findBlankConnectedSaveNode(node);
|
||
if (blank) return bindSaveNodeToBatch(node, blank, batchId);
|
||
return createSaveNodeForBatch(node, batchId);
|
||
}
|
||
|
||
function findLayerSaveNode(node, imageSaveNode) {
|
||
const imageSaveNodeId = String(imageSaveNode?.id ?? "");
|
||
const candidates = findConnectedSaveNodesAtOutput(node, 1);
|
||
return candidates.find((candidate) => (
|
||
String(candidate.properties?.o1keyImageSaveNodeId ?? "") === imageSaveNodeId
|
||
)) || null;
|
||
}
|
||
|
||
function acquireLayerSaveNodeForBatch(node, imageSaveNode) {
|
||
let layerSaveNode = findLayerSaveNode(node, imageSaveNode);
|
||
if (!layerSaveNode) {
|
||
layerSaveNode = findConnectedSaveNodesAtOutput(node, 1).find((candidate) => (
|
||
isBlankSaveNode(candidate)
|
||
&& candidate.properties?.o1keySaveRole === "layers"
|
||
&& candidate.properties?.o1keyImageSaveNodeId == null
|
||
)) || createSaveNodeForBatch(node, "", 1);
|
||
}
|
||
layerSaveNode.properties ??= {};
|
||
layerSaveNode.properties.o1keySaveRole = "layers";
|
||
layerSaveNode.properties.o1keyImageSaveNodeId = imageSaveNode.id;
|
||
layerSaveNode.properties.o1keyGeneratorNodeId = node.id;
|
||
delete layerSaveNode.properties.o1keyBatchId;
|
||
layerSaveNode.title = "o1key 保存图层";
|
||
return layerSaveNode;
|
||
}
|
||
|
||
function isLayerDecompositionEnabled(node) {
|
||
return node?._o1igModel?.value === "Seedream 5.0 Pro"
|
||
&& node?._o1igLayerDecomposition?.value === "开启";
|
||
}
|
||
|
||
function splitLayerSaveResults(images) {
|
||
const normalized = normalizeSaveResults(images);
|
||
return {
|
||
imageResults: normalized.slice(0, 1),
|
||
layerResults: normalized.slice(1),
|
||
};
|
||
}
|
||
|
||
function findConnectedGenerator(saveNode) {
|
||
const graph = saveNode?.graph || app.graph;
|
||
const link = getGraphLink(graph, saveNode?.inputs?.[0]?.link);
|
||
const source = link ? graph?.getNodeById?.(link.origin_id) : null;
|
||
return source?.type === NODE_TYPE || source?.comfyClass === NODE_TYPE ? source : null;
|
||
}
|
||
|
||
function chooseStandardSaveNode(generator) {
|
||
return findBlankConnectedSaveNode(generator) || createSaveNodeForBatch(generator, "");
|
||
}
|
||
|
||
function reserveStandardExecution(generator, saveNode) {
|
||
generator._o1igsQueuedStandardSaveNodeIds ??= [];
|
||
if (!generator._o1igsQueuedStandardSaveNodeIds.includes(saveNode.id)) {
|
||
generator._o1igsQueuedStandardSaveNodeIds.push(saveNode.id);
|
||
}
|
||
saveNode._o1igsStandardQueueReserved = true;
|
||
saveNode._o1igsSourceGeneratorId = generator.id;
|
||
}
|
||
|
||
function startNextStandardExecution(generator) {
|
||
const queued = generator._o1igsQueuedStandardSaveNodeIds || [];
|
||
while (queued.length) {
|
||
const saveNodeId = queued.shift();
|
||
const saveNode = (generator.graph || app.graph)?.getNodeById?.(saveNodeId);
|
||
if (!saveNode) continue;
|
||
delete saveNode._o1igsStandardQueueReserved;
|
||
saveNode._o1igsStandardExecutionPending = true;
|
||
generator._o1igsActiveStandardSaveNodeId = saveNode.id;
|
||
setSaveBusy(saveNode, true, "running", 0);
|
||
return saveNode;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function activeStandardSaveNode(generator) {
|
||
const graph = generator?.graph || app.graph;
|
||
const activeId = generator?._o1igsActiveStandardSaveNodeId;
|
||
if (activeId != null) return graph?.getNodeById?.(activeId) || null;
|
||
const queuedId = generator?._o1igsQueuedStandardSaveNodeIds?.[0];
|
||
return queuedId != null ? graph?.getNodeById?.(queuedId) || null : null;
|
||
}
|
||
|
||
function clearStandardExecution(saveNode) {
|
||
const source = findConnectedGenerator(saveNode)
|
||
|| saveNode?.graph?.getNodeById?.(saveNode?._o1igsSourceGeneratorId);
|
||
delete saveNode._o1igsStandardQueueReserved;
|
||
delete saveNode._o1igsStandardExecutionPending;
|
||
if (!source) return null;
|
||
if (String(source._o1igsActiveStandardSaveNodeId) === String(saveNode.id)) {
|
||
delete source._o1igsActiveStandardSaveNodeId;
|
||
}
|
||
source._o1igsQueuedStandardSaveNodeIds = (
|
||
source._o1igsQueuedStandardSaveNodeIds || []
|
||
).filter((nodeId) => String(nodeId) !== String(saveNode.id));
|
||
return source;
|
||
}
|
||
|
||
function prepareStandardQueue(generator, { isPartialExecution = false } = {}) {
|
||
let saveNode = null;
|
||
if (isPartialExecution) {
|
||
const requestedId = generator._o1igsRequestedStandardSaveNodeId;
|
||
if (requestedId == null) return null;
|
||
saveNode = (generator.graph || app.graph)?.getNodeById?.(requestedId) || null;
|
||
if (!findConnectedSaveNodes(generator).includes(saveNode)) saveNode = null;
|
||
}
|
||
saveNode ||= chooseStandardSaveNode(generator);
|
||
const layerDecomposition = isLayerDecompositionEnabled(generator);
|
||
const layerSaveNode = layerDecomposition
|
||
? acquireLayerSaveNodeForBatch(generator, saveNode)
|
||
: null;
|
||
reserveStandardExecution(generator, saveNode);
|
||
generator._o1igsStandardQueueSaveNodeId = saveNode.id;
|
||
generator._o1igsStandardQueueLayerSaveNodeId = layerSaveNode?.id;
|
||
return saveNode;
|
||
}
|
||
|
||
function finishStandardQueue(generator) {
|
||
delete generator._o1igsRequestedStandardSaveNodeId;
|
||
delete generator._o1igsStandardQueueSaveNodeId;
|
||
delete generator._o1igsStandardQueueLayerSaveNodeId;
|
||
}
|
||
|
||
function graphNodes(graph) {
|
||
if (Array.isArray(graph?._nodes)) return graph._nodes;
|
||
const values = graph?.nodes?.values?.();
|
||
return values ? Array.from(values) : [];
|
||
}
|
||
|
||
function takeStandardQueueRoutes() {
|
||
const routes = [];
|
||
for (const generator of graphNodes(app.graph)) {
|
||
if (generator?.type !== NODE_TYPE && generator?.comfyClass !== NODE_TYPE) continue;
|
||
const saveNodeId = generator._o1igsStandardQueueSaveNodeId;
|
||
if (saveNodeId == null) continue;
|
||
routes.push({
|
||
generator,
|
||
saveNodeId,
|
||
layerSaveNodeId: generator._o1igsStandardQueueLayerSaveNodeId,
|
||
});
|
||
delete generator._o1igsStandardQueueSaveNodeId;
|
||
delete generator._o1igsStandardQueueLayerSaveNodeId;
|
||
}
|
||
return routes;
|
||
}
|
||
|
||
function filterStandardQueueOutputs(promptResult, routes) {
|
||
const output = promptResult?.output;
|
||
if (!output || !routes.length) return promptResult;
|
||
const removed = new Set();
|
||
for (const { generator, saveNodeId, layerSaveNodeId } of routes) {
|
||
for (const saveNode of findConnectedSaveNodes(generator)) {
|
||
if (String(saveNode.id) !== String(saveNodeId)) removed.add(String(saveNode.id));
|
||
}
|
||
for (const saveNode of findConnectedSaveNodesAtOutput(generator, 1)) {
|
||
if (String(saveNode.id) !== String(layerSaveNodeId)) removed.add(String(saveNode.id));
|
||
}
|
||
}
|
||
let changed = true;
|
||
while (changed) {
|
||
changed = false;
|
||
for (const [nodeId, promptNode] of Object.entries(output)) {
|
||
if (removed.has(String(nodeId))) continue;
|
||
const dependsOnRemoved = Object.values(promptNode?.inputs || {}).some((value) => (
|
||
Array.isArray(value)
|
||
&& value.length === 2
|
||
&& removed.has(String(value[0]))
|
||
));
|
||
if (dependsOnRemoved) {
|
||
removed.add(String(nodeId));
|
||
changed = true;
|
||
}
|
||
}
|
||
}
|
||
for (const nodeId of removed) delete output[nodeId];
|
||
return promptResult;
|
||
}
|
||
|
||
function findUpstreamSaveNodes(node) {
|
||
const graph = node?.graph || app.graph;
|
||
const pending = [node];
|
||
const visited = new Set();
|
||
const results = [];
|
||
while (pending.length) {
|
||
const current = pending.pop();
|
||
if (!current || visited.has(current.id)) continue;
|
||
visited.add(current.id);
|
||
if (current.type === SAVE_NODE_TYPE || current.comfyClass === SAVE_NODE_TYPE) {
|
||
results.push(current);
|
||
continue;
|
||
}
|
||
for (const input of current.inputs || []) {
|
||
const link = getGraphLink(graph, input?.link);
|
||
const source = link ? graph?.getNodeById?.(link.origin_id) : null;
|
||
if (source) pending.push(source);
|
||
}
|
||
}
|
||
return results;
|
||
}
|
||
|
||
function reroutePartialExecutionTargets(queueNodeIds) {
|
||
if (!Array.isArray(queueNodeIds) || !queueNodeIds.length) return queueNodeIds;
|
||
const routed = [];
|
||
for (const rawId of queueNodeIds) {
|
||
const node = app.graph?.getNodeById?.(rawId)
|
||
|| app.graph?.getNodeById?.(Number(rawId));
|
||
if (node?.type !== SAVE_NODE_TYPE && node?.comfyClass !== SAVE_NODE_TYPE) {
|
||
for (const upstreamSave of findUpstreamSaveNodes(node)) {
|
||
const generator = findConnectedGenerator(upstreamSave);
|
||
if (generator) generator._o1igsRequestedStandardSaveNodeId = upstreamSave.id;
|
||
}
|
||
routed.push(rawId);
|
||
continue;
|
||
}
|
||
const generator = findConnectedGenerator(node);
|
||
if (!generator) {
|
||
routed.push(rawId);
|
||
continue;
|
||
}
|
||
const saveNode = chooseStandardSaveNode(generator);
|
||
generator._o1igsRequestedStandardSaveNodeId = saveNode.id;
|
||
routed.push(saveNode.id);
|
||
}
|
||
return [...new Set(routed)];
|
||
}
|
||
|
||
function installStandardQueueRouting() {
|
||
if (app.__o1keyImageQueueRoutingInstalled) return;
|
||
if (typeof app.queuePrompt !== "function" || typeof app.graphToPrompt !== "function") return;
|
||
app.__o1keyImageQueueRoutingInstalled = true;
|
||
|
||
const originalQueuePrompt = app.queuePrompt;
|
||
app.queuePrompt = function (number, batchCount = 1, queueNodeIds) {
|
||
return originalQueuePrompt.call(
|
||
this,
|
||
number,
|
||
batchCount,
|
||
reroutePartialExecutionTargets(queueNodeIds),
|
||
);
|
||
};
|
||
|
||
const originalGraphToPrompt = app.graphToPrompt;
|
||
app.graphToPrompt = async function () {
|
||
const routes = takeStandardQueueRoutes();
|
||
const result = await originalGraphToPrompt.apply(this, arguments);
|
||
return filterStandardQueueOutputs(result, routes);
|
||
};
|
||
}
|
||
|
||
function installStandardQueueWidget(node) {
|
||
const widget = findWidget(node, "prompt") || node.widgets?.[0];
|
||
if (!widget || widget.__o1keyStandardQueueInstalled) return;
|
||
widget.__o1keyStandardQueueInstalled = true;
|
||
const originalBeforeQueued = widget.beforeQueued;
|
||
widget.beforeQueued = function (options = {}) {
|
||
const result = originalBeforeQueued?.apply(this, arguments);
|
||
prepareStandardQueue(node, options);
|
||
return result;
|
||
};
|
||
const originalAfterQueued = widget.afterQueued;
|
||
widget.afterQueued = function () {
|
||
const result = originalAfterQueued?.apply(this, arguments);
|
||
finishStandardQueue(node);
|
||
return result;
|
||
};
|
||
}
|
||
|
||
function clearNativePreview(node) {
|
||
node.imgs = null;
|
||
node.imageIndex = null;
|
||
if ("previewMediaType" in node) node.previewMediaType = null;
|
||
}
|
||
|
||
function mediaIdentity(url) {
|
||
try {
|
||
const parsed = new URL(String(url || ""), document.baseURI || "http://localhost/");
|
||
return ["filename", "subfolder", "type"]
|
||
.map((key) => parsed.searchParams.get(key) || "")
|
||
.join("\n");
|
||
} catch {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
function getNativePreviewImageIndex(node, preview) {
|
||
const fallback = Math.max(0, Number(node.imageIndex) || 0);
|
||
const mainImage = preview?.querySelector?.('[data-testid="main-image"]');
|
||
const currentIdentity = mediaIdentity(mainImage?.currentSrc || mainImage?.src);
|
||
if (!currentIdentity) return fallback;
|
||
const index = (node._o1igsLastResults || [])
|
||
.findIndex((item) => mediaIdentity(viewUrl(item)) === currentIdentity);
|
||
return index >= 0 ? index : fallback;
|
||
}
|
||
|
||
function syncNativePreviewAction(node) {
|
||
const nodeId = Number(node?.id);
|
||
if (!Number.isFinite(nodeId)) return;
|
||
const preview = document.querySelector?.(`[data-node-id="${nodeId}"] .image-preview`);
|
||
if (!preview) return;
|
||
for (const button of preview.querySelectorAll?.("button") || []) {
|
||
if (button.dataset?.o1keyRegenerate === String(nodeId)) {
|
||
button.disabled = Boolean(node._o1igsBusy);
|
||
continue;
|
||
}
|
||
const icon = button.querySelector?.('i[class*="lucide--download"]');
|
||
if (!icon) continue;
|
||
button.dataset.o1keyRegenerate = String(nodeId);
|
||
const label = "重新生成";
|
||
button.title = label;
|
||
button.setAttribute("aria-label", label);
|
||
icon.className = String(icon.className).replace("lucide--download", "lucide--refresh-cw");
|
||
button.disabled = Boolean(node._o1igsBusy);
|
||
button.addEventListener("click", (event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
event.stopImmediatePropagation();
|
||
regenerateFromSaveNode(node, getNativePreviewImageIndex(node, preview));
|
||
}, true);
|
||
}
|
||
}
|
||
|
||
function syncSaveProgressOverlay(node) {
|
||
const nodeId = Number(node?.id);
|
||
if (!Number.isFinite(nodeId)) return;
|
||
const container = document.querySelector?.(`[data-node-id="${nodeId}"]`);
|
||
container?.classList?.add?.("o1key-image-save-node");
|
||
const body = container?.querySelector?.(`[data-testid="node-body-${nodeId}"]`);
|
||
if (!body) return;
|
||
body.classList.add("o1igs-progress-host");
|
||
let track = body.querySelector?.(`[data-o1key-save-progress="${nodeId}"]`);
|
||
if (!track) {
|
||
track = document.createElement("div");
|
||
track.className = "o1igs-progress-track";
|
||
track.dataset.o1keySaveProgress = String(nodeId);
|
||
track.setAttribute("aria-hidden", "true");
|
||
body.append(track);
|
||
}
|
||
node._o1igsProgressTrack = track;
|
||
track.classList.toggle("busy", Boolean(node._o1igsBusy));
|
||
const percent = Math.max(0, Math.min(100, Math.round(Number(node._o1igsProgress) * 100 || 0)));
|
||
track.style.setProperty("--o1igs-progress", `${node._o1igsBusy ? percent : 0}%`);
|
||
}
|
||
|
||
let nativePreviewSyncScheduled = false;
|
||
|
||
function syncAllNativePreviewActions() {
|
||
for (const node of app.graph?._nodes || []) {
|
||
if (node?.comfyClass === SAVE_NODE_TYPE || node?.type === SAVE_NODE_TYPE) {
|
||
syncNativePreviewAction(node);
|
||
syncSaveProgressOverlay(node);
|
||
}
|
||
}
|
||
syncNativeQueueCounts();
|
||
}
|
||
|
||
function syncNativeQueueCounts() {
|
||
if (typeof document.querySelectorAll !== "function") return;
|
||
for (const job of nativeQueueBridge.jobs.values()) {
|
||
const count = Math.max(0, Math.floor(Number(job.o1key_total_count) || 0));
|
||
if (!count) continue;
|
||
const selector = `[data-job-id="${job.id}"]`;
|
||
for (const row of document.querySelectorAll(selector)) {
|
||
const item = row.firstElementChild || row.children?.[0] || row;
|
||
let badge = item.querySelector?.(`[data-o1key-queue-count="${job.id}"]`);
|
||
if (!badge) {
|
||
badge = document.createElement("button");
|
||
badge.type = "button";
|
||
badge.className = [
|
||
"o1key-queue-count",
|
||
"relative", "z-1", "inline-flex", "shrink-0", "items-center", "justify-center",
|
||
"gap-2", "cursor-pointer", "touch-manipulation", "whitespace-nowrap", "appearance-none",
|
||
"border-none", "rounded-md", "text-sm", "font-medium", "font-inter",
|
||
"transition-colors", "hover:bg-secondary-background-hover",
|
||
"focus-visible:outline-none", "focus-visible:ring-1", "focus-visible:ring-ring",
|
||
"text-secondary-foreground", "bg-secondary-background",
|
||
"h-8", "rounded-lg", "p-2", "text-xs",
|
||
].join(" ");
|
||
badge.dataset.o1keyQueueCount = job.id;
|
||
const icon = document.createElement("i");
|
||
icon.className = "icon-[lucide--layers] size-4";
|
||
icon.setAttribute("aria-hidden", "true");
|
||
const value = document.createElement("span");
|
||
badge.append(icon, value);
|
||
badge.addEventListener("click", (event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
item.dispatchEvent?.(new MouseEvent("dblclick", { bubbles: true }));
|
||
});
|
||
item.append?.(badge);
|
||
}
|
||
badge.children?.[1] && (badge.children[1].textContent = String(count));
|
||
badge.title = `批次共 ${count} 张`;
|
||
badge.setAttribute?.("aria-label", badge.title);
|
||
}
|
||
}
|
||
}
|
||
|
||
function scheduleNativePreviewActionSync() {
|
||
if (nativePreviewSyncScheduled) return;
|
||
nativePreviewSyncScheduled = true;
|
||
requestAnimationFrame(() => {
|
||
nativePreviewSyncScheduled = false;
|
||
syncAllNativePreviewActions();
|
||
});
|
||
}
|
||
|
||
function installNativePreviewActionSync() {
|
||
document.__o1keyNativePreviewObserver?.disconnect?.();
|
||
if (!document.body || typeof MutationObserver === "undefined") return;
|
||
const observer = new MutationObserver(scheduleNativePreviewActionSync);
|
||
observer.observe(document.body, { childList: true, subtree: true });
|
||
document.__o1keyNativePreviewObserver = observer;
|
||
scheduleNativePreviewActionSync();
|
||
}
|
||
|
||
function normalizeLayerMetadata(value) {
|
||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||
const zIndex = Math.max(0, Math.min(16, Math.floor(Number(value.z_index) || 0)));
|
||
const normalized = { z_index: zIndex };
|
||
for (const [key, limit] of [["name", 200], ["description", 1000], ["size", 64], ["output_format", 16]]) {
|
||
const text = typeof value[key] === "string" ? value[key].trim().slice(0, limit) : "";
|
||
if (text) normalized[key] = text;
|
||
}
|
||
const box = value.bounding_box;
|
||
if (box && typeof box === "object" && !Array.isArray(box)) {
|
||
const safeBox = {};
|
||
for (const key of ["absolute", "normalized"]) {
|
||
if (Array.isArray(box[key]) && box[key].length === 4) {
|
||
const values = box[key].map((item) => Math.floor(Number(item)));
|
||
if (values.every(Number.isFinite)) safeBox[key] = values;
|
||
}
|
||
}
|
||
if (Object.keys(safeBox).length) normalized.bounding_box = safeBox;
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
function isGifSaveResult(item) {
|
||
const name = String(item?.filename || item?.name || "");
|
||
return /\.gif$/i.test(name) || item?.media === "gif" || item?.animated === true;
|
||
}
|
||
|
||
function animatedFlagsForSaveResults(images) {
|
||
const list = normalizeSaveResults(images);
|
||
if (!list.some(isGifSaveResult)) return null;
|
||
return list.map(isGifSaveResult);
|
||
}
|
||
|
||
function normalizeSaveResults(images) {
|
||
|
||
if (!Array.isArray(images)) return [];
|
||
return images.map((item) => {
|
||
const filename = String(item?.filename || item?.name || "");
|
||
if (!filename) return null;
|
||
const normalized = {
|
||
filename,
|
||
subfolder: String(item?.subfolder || ""),
|
||
type: String(item?.type || "output"),
|
||
};
|
||
if (item?.external_saved === true) normalized.external_saved = true;
|
||
if (item?.batch_id) normalized.batch_id = String(item.batch_id);
|
||
if (item?.media) normalized.media = String(item.media);
|
||
if (item?.animated === true) normalized.animated = true;
|
||
const requestIndex = Math.max(0, Math.floor(Number(item?.request_index) || 0));
|
||
const resultIndex = Math.max(0, Math.floor(Number(item?.result_index) || 0));
|
||
if (requestIndex) normalized.request_index = requestIndex;
|
||
if (resultIndex) normalized.result_index = resultIndex;
|
||
const layer = normalizeLayerMetadata(item?.layer);
|
||
if (layer) normalized.layer = layer;
|
||
return normalized;
|
||
}).filter((item) => item && viewUrl(item));
|
||
}
|
||
|
||
function storedSaveResults(node, data = null) {
|
||
const candidates = [
|
||
data?.o1key_image_save_results,
|
||
data?.properties?.o1keyImageSaveResults,
|
||
node?.properties?.o1keyImageSaveResults,
|
||
];
|
||
for (const candidate of candidates) {
|
||
if (Array.isArray(candidate) && candidate.length) return normalizeSaveResults(candidate);
|
||
}
|
||
return [];
|
||
}
|
||
|
||
function persistSaveResults(node, images) {
|
||
const previous = normalizeSaveResults(node?.properties?.o1keyImageSaveResults);
|
||
if (JSON.stringify(previous) === JSON.stringify(images)) return;
|
||
const graph = node.graph || app.graph;
|
||
graph?.beforeChange?.();
|
||
try {
|
||
node.properties ??= {};
|
||
node.properties.o1keyImageSaveResults = images;
|
||
} finally {
|
||
graph?.afterChange?.();
|
||
}
|
||
}
|
||
|
||
function expandPanelPromptTasks(prompt, imageCount) {
|
||
const lines = String(prompt || "").split(/\r?\n/);
|
||
const hasSeparator = lines.some((line) => line.trim() === "---");
|
||
const prompts = [];
|
||
if (!hasSeparator) {
|
||
if (String(prompt || "").trim()) prompts.push(String(prompt).trim());
|
||
} else {
|
||
let current = [];
|
||
for (const line of lines) {
|
||
if (line.trim() === "---") {
|
||
const value = current.join("\n").trim();
|
||
if (value) prompts.push(value);
|
||
current = [];
|
||
} else {
|
||
current.push(line);
|
||
}
|
||
}
|
||
const value = current.join("\n").trim();
|
||
if (value) prompts.push(value);
|
||
}
|
||
const count = Math.max(1, Math.floor(Number(imageCount) || 1));
|
||
return prompts.flatMap((value) => Array.from({ length: count }, () => value));
|
||
}
|
||
|
||
function expandPanelGenerationTasks({
|
||
prompt,
|
||
imageCount = 1,
|
||
batchEnabled = false,
|
||
batchMode = BATCH_MODE_GROUP_TO_TARGETS,
|
||
references = [],
|
||
modelReferences = [],
|
||
} = {}) {
|
||
const prompts = expandPanelPromptTasks(prompt, 1);
|
||
const count = Math.max(1, Math.floor(Number(imageCount) || 1));
|
||
batchMode = normalizeBatchMode(batchMode);
|
||
let pairings = [{ references: [...references], outfitIndex: null, modelIndex: null }];
|
||
if (batchEnabled) {
|
||
if (batchMode === BATCH_MODE_SINGLE_REFERENCES) {
|
||
pairings = references.map((reference, outfitIndex) => ({
|
||
references: [reference],
|
||
outfitIndex,
|
||
modelIndex: null,
|
||
}));
|
||
} else {
|
||
if (!references.length || !modelReferences.length) return [];
|
||
pairings = batchMode === BATCH_MODE_ALL_PAIRS
|
||
? references.flatMap((outfit, outfitIndex) => modelReferences.map((model, modelIndex) => ({
|
||
references: [outfit, model],
|
||
outfitIndex,
|
||
modelIndex,
|
||
})))
|
||
: modelReferences.map((model, modelIndex) => ({
|
||
references: [...references, model],
|
||
outfitIndex: null,
|
||
modelIndex,
|
||
}));
|
||
}
|
||
}
|
||
return prompts.flatMap((taskPrompt) => pairings.flatMap((pairing) => (
|
||
Array.from({ length: count }, () => ({ prompt: taskPrompt, ...pairing }))
|
||
)));
|
||
}
|
||
|
||
function panelGenerationTasks(node, prompt, imageCount) {
|
||
return expandPanelGenerationTasks({
|
||
prompt,
|
||
imageCount,
|
||
batchEnabled: Boolean(node?._o1igBatchEnabled),
|
||
batchMode: batchModeOf(node),
|
||
references: node?._o1igReferences || [],
|
||
modelReferences: node?._o1igModelReferences || [],
|
||
});
|
||
}
|
||
|
||
function updateBatchReferenceHint(node) {
|
||
const hint = node?._o1igReferenceHint;
|
||
if (!hint) return;
|
||
const enabled = Boolean(node._o1igBatchEnabled);
|
||
const referenceCount = node._o1igReferences?.length || 0;
|
||
const modelCount = node._o1igModelReferences?.length || 0;
|
||
if (node._o1igReferenceTitle) {
|
||
node._o1igReferenceTitle.textContent = enabled ? "素材图" : "参考图";
|
||
}
|
||
hint.textContent = !enabled
|
||
? `${referenceCount} 张 · 最多 ${MAX_REQUEST_REFERENCES} 张`
|
||
: batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES
|
||
? `${referenceCount} 张 · 各自独立`
|
||
: batchModeOf(node) === BATCH_MODE_ALL_PAIRS
|
||
? `${referenceCount} 张 · 两两匹配`
|
||
: `${referenceCount} 张 · 整组共用`;
|
||
if (node?._o1igModel?.value === "Seedream 5.0 Pro") {
|
||
const layerDecomposition = node?._o1igLayerDecomposition?.value === "开启";
|
||
hint.title = layerDecomposition
|
||
? "Seedream 图层拆分:单图不超过 30MB,宽高比 1:16~16:1,总像素 512×512~6000×6000"
|
||
: "Seedream 参考图:单图不超过 30MB,宽和高均 >14px,宽高比 1:16~16:1,总像素不超过 6000×6000";
|
||
} else {
|
||
hint.title = "";
|
||
}
|
||
if (node._o1igModelHint) {
|
||
node._o1igModelHint.textContent = `${modelCount} 张 · 每张单独参与组合`;
|
||
}
|
||
// In batch mode the pairing preview below the tracks already carries the counts,
|
||
// so the header hints are dropped to keep the lane titles clean.
|
||
hint.classList?.toggle("hidden", enabled);
|
||
node._o1igModelHint?.classList?.toggle("hidden", enabled);
|
||
}
|
||
|
||
// Pairing preview shared by the panel row and the queue check: one source of truth.
|
||
function batchGenerationPreview(node) {
|
||
if (!node?._o1igBatchEnabled) return null;
|
||
const sources = node._o1igReferences?.length || 0;
|
||
const targets = node._o1igModelReferences?.length || 0;
|
||
const perPair = Math.max(1, Math.floor(Number(node._o1igCount?.value) || 1));
|
||
const promptCount = Math.max(1, expandPanelPromptTasks(node._o1igPrompt?.value || "", 1).length);
|
||
const mode = batchModeOf(node);
|
||
const singleReferences = mode === BATCH_MODE_SINGLE_REFERENCES;
|
||
const allPairs = mode === BATCH_MODE_ALL_PAIRS;
|
||
const pairCount = singleReferences ? sources : allPairs ? sources * targets : targets;
|
||
if (singleReferences ? !sources : (!sources || !targets)) return null;
|
||
const parts = [];
|
||
if (singleReferences) {
|
||
parts.push(`${sources} 张素材·各自独立`);
|
||
} else if (allPairs) {
|
||
parts.push(`${sources} 张素材 × ${targets} 个目标 = ${pairCount} 组`);
|
||
} else {
|
||
parts.push(`整组 ${sources} 张素材 × ${targets} 个目标 = ${pairCount} 组`);
|
||
}
|
||
parts.push(`每组 ${perPair} 张`);
|
||
if (promptCount > 1) parts.push(`${promptCount} 条提示词`);
|
||
return {
|
||
detail: parts.join(" · "),
|
||
totalCount: pairCount * perPair * promptCount,
|
||
total: `共 ${pairCount * perPair * promptCount} 张`,
|
||
};
|
||
}
|
||
|
||
function updateBatchSummary(node) {
|
||
const summary = node?._o1igBatchSummary;
|
||
if (!summary) return;
|
||
updateBatchReferenceHint(node);
|
||
const preview = batchGenerationPreview(node);
|
||
const detail = node._o1igBatchSummaryDetail;
|
||
const total = node._o1igBatchSummaryTotal;
|
||
if (!preview) {
|
||
// Clear the spans instead of the container: writing to `summary.textContent`
|
||
// would detach them, and the preview could never render again.
|
||
summary.classList.remove("visible");
|
||
if (detail) detail.textContent = "";
|
||
if (total) total.textContent = "";
|
||
return;
|
||
}
|
||
summary.classList.add("visible");
|
||
if (detail) detail.textContent = preview.detail;
|
||
if (total) total.textContent = preview.total;
|
||
}
|
||
|
||
function normalizeSaveSlots(slots) {
|
||
if (!Array.isArray(slots)) return [];
|
||
const allowedStates = new Set(["pending", "running", "success", "failed", "cancelled"]);
|
||
return slots.map((slot, offset) => {
|
||
const index = Math.max(1, Math.floor(Number(slot?.index) || offset + 1));
|
||
const image = normalizeSaveResults(slot?.image ? [slot.image] : [])[0] || null;
|
||
const state = allowedStates.has(slot?.state) ? slot.state : image ? "success" : "pending";
|
||
return {
|
||
index,
|
||
state: image ? "success" : state,
|
||
prompt: String(slot?.prompt || ""),
|
||
references: parseReferences(slot?.references || []),
|
||
error: String(slot?.error || ""),
|
||
image,
|
||
};
|
||
}).sort((left, right) => left.index - right.index);
|
||
}
|
||
|
||
function reconcileSaveSlotsWithResults(slots, images) {
|
||
const normalizedSlots = normalizeSaveSlots(slots);
|
||
const normalizedImages = normalizeSaveResults(images);
|
||
if (!normalizedSlots.length || !normalizedImages.length) return normalizedSlots;
|
||
|
||
const imageByIndex = new Map();
|
||
for (const [offset, image] of normalizedImages.entries()) {
|
||
const index = Math.max(1, Number(image.request_index) || offset + 1);
|
||
if (!imageByIndex.has(index)) imageByIndex.set(index, image);
|
||
}
|
||
return normalizedSlots.map((slot) => {
|
||
const image = imageByIndex.get(slot.index);
|
||
return image
|
||
? { ...slot, state: "success", image: { ...image, request_index: slot.index }, error: "" }
|
||
: slot;
|
||
});
|
||
}
|
||
|
||
function applyPartialSaveSlots(node, images, retrySlotIndex = 0) {
|
||
const normalizedImages = normalizeSaveResults(images);
|
||
if (!normalizedImages.length) return;
|
||
const slots = normalizeSaveSlots(node?._o1igsSlots);
|
||
if (retrySlotIndex) {
|
||
const image = normalizedImages[0];
|
||
node._o1igsSlots = slots.map((slot) => slot.index === retrySlotIndex
|
||
? {
|
||
...slot,
|
||
state: "success",
|
||
image: { ...image, request_index: retrySlotIndex },
|
||
error: "",
|
||
}
|
||
: slot);
|
||
} else {
|
||
node._o1igsSlots = reconcileSaveSlotsWithResults(slots, normalizedImages);
|
||
}
|
||
syncSaveSlotsWidget(node);
|
||
}
|
||
|
||
function storedSaveSlots(node, data = null) {
|
||
const candidates = [
|
||
data?.o1key_image_slots,
|
||
data?.properties?.o1keyImageSlots,
|
||
node?.properties?.o1keyImageSlots,
|
||
];
|
||
for (const candidate of candidates) {
|
||
if (Array.isArray(candidate) && candidate.length) return normalizeSaveSlots(candidate);
|
||
}
|
||
return [];
|
||
}
|
||
|
||
function persistSaveSlots(node) {
|
||
const slots = normalizeSaveSlots(node?._o1igsSlots);
|
||
const previous = normalizeSaveSlots(node?.properties?.o1keyImageSlots);
|
||
if (JSON.stringify(previous) === JSON.stringify(slots)) return;
|
||
const graph = node.graph || app.graph;
|
||
graph?.beforeChange?.();
|
||
try {
|
||
node.properties ??= {};
|
||
node.properties.o1keyImageSlots = slots;
|
||
} finally {
|
||
graph?.afterChange?.();
|
||
}
|
||
}
|
||
|
||
function saveSlotsVisible(node) {
|
||
const slots = normalizeSaveSlots(node?._o1igsSlots);
|
||
return Boolean(slots.length && (node?._o1igsBusy || slots.some((slot) => slot.state !== "success")));
|
||
}
|
||
|
||
function saveSlotsColumnCount(total) {
|
||
if (total <= 1) return 1;
|
||
if (total <= 4) return 2;
|
||
if (total <= 9) return 3;
|
||
return 4;
|
||
}
|
||
|
||
function saveSlotsWidgetHeight(node, availableWidth = 0) {
|
||
const total = normalizeSaveSlots(node?._o1igsSlots).length;
|
||
const columns = saveSlotsColumnCount(total);
|
||
const rows = Math.ceil(total / columns);
|
||
const measuredWidth = Number(node?._o1igsSlotsElement?.offsetWidth) || 0;
|
||
const fallbackWidth = Math.max(
|
||
220,
|
||
Number(availableWidth) || Number(node?.size?.[0]) || 300,
|
||
) - SAVE_SLOT_GRID_NODE_INSET;
|
||
const gridWidth = measuredWidth > 0 ? measuredWidth : fallbackWidth;
|
||
const contentWidth = Math.max(
|
||
columns * 54,
|
||
gridWidth - SAVE_SLOT_GRID_PADDING_BORDER,
|
||
);
|
||
const cell = Math.max(
|
||
54,
|
||
(contentWidth - (columns - 1) * SAVE_SLOT_GRID_GAP) / columns,
|
||
);
|
||
const contentHeight = rows * cell + Math.max(0, rows - 1) * SAVE_SLOT_GRID_GAP;
|
||
return Math.min(420, Math.ceil(contentHeight + SAVE_SLOT_GRID_PADDING_BORDER));
|
||
}
|
||
|
||
function ensureSaveSlotsWidget(node) {
|
||
if (node._o1igsSlotsWidget || typeof node.addDOMWidget !== "function") return;
|
||
const grid = document.createElement("div");
|
||
grid.className = "o1igs-slots";
|
||
const widget = node.addDOMWidget("o1key_image_slots", "div", grid, {
|
||
serialize: false,
|
||
hideOnZoom: false,
|
||
getMinHeight: () => saveSlotsVisible(node) ? saveSlotsWidgetHeight(node) : 0,
|
||
});
|
||
widget.computeSize = (width) => saveSlotsVisible(node)
|
||
? [Math.max(0, Number(width) || Number(node?.size?.[0]) || 0), saveSlotsWidgetHeight(node, width)]
|
||
: [0, -4];
|
||
node._o1igsSlotsElement = grid;
|
||
node._o1igsSlotsWidget = widget;
|
||
}
|
||
|
||
function removeSaveSlotsWidget(node) {
|
||
const widget = node?._o1igsSlotsWidget;
|
||
const grid = node?._o1igsSlotsElement;
|
||
if (!widget && !grid) return false;
|
||
|
||
const widgets = Array.isArray(node?.widgets) ? node.widgets : null;
|
||
const widgetIndex = widget && widgets ? widgets.indexOf(widget) : -1;
|
||
let removedByNode = false;
|
||
if (widgetIndex >= 0 && typeof node.removeWidget === "function") {
|
||
try {
|
||
node.removeWidget(widget);
|
||
removedByNode = true;
|
||
} catch {
|
||
// Fall back to the array path for older LiteGraph builds.
|
||
}
|
||
}
|
||
if (widgetIndex >= 0 && !removedByNode) {
|
||
widget.onRemove?.();
|
||
widgets.splice(widgetIndex, 1);
|
||
} else if (widget && widgetIndex < 0) {
|
||
widget.onRemove?.();
|
||
}
|
||
grid?.remove?.();
|
||
node._o1igsSlotsWidget = null;
|
||
node._o1igsSlotsElement = null;
|
||
node.setDirtyCanvas?.(true, true);
|
||
return true;
|
||
}
|
||
|
||
function syncSaveSlotsWidget(node) {
|
||
const slots = normalizeSaveSlots(node?._o1igsSlots);
|
||
node._o1igsSlots = slots;
|
||
const visible = saveSlotsVisible(node);
|
||
const container = Number.isFinite(Number(node?.id))
|
||
? document.querySelector?.(`[data-node-id="${Number(node.id)}"]`)
|
||
: null;
|
||
container?.classList?.toggle?.("o1key-slots-visible", visible);
|
||
if (!visible) {
|
||
removeSaveSlotsWidget(node);
|
||
return;
|
||
}
|
||
|
||
ensureSaveSlotsWidget(node);
|
||
const grid = node._o1igsSlotsElement;
|
||
if (!grid) return;
|
||
grid.style.display = "grid";
|
||
grid.style.gridTemplateColumns = `repeat(${saveSlotsColumnCount(slots.length)},minmax(0,1fr))`;
|
||
const widgetHeight = saveSlotsWidgetHeight(node);
|
||
grid.style.maxHeight = `${widgetHeight}px`;
|
||
grid.replaceChildren();
|
||
|
||
for (const slot of slots) {
|
||
const card = document.createElement("div");
|
||
card.className = `o1igs-slot ${slot.state}`;
|
||
card.dataset.o1keySlotIndex = String(slot.index);
|
||
const index = document.createElement("span");
|
||
index.className = "o1igs-slot-index";
|
||
index.textContent = String(slot.index);
|
||
card.append(index);
|
||
if (slot.state === "success" && slot.image) {
|
||
const image = document.createElement("img");
|
||
image.src = viewUrl(slot.image);
|
||
image.alt = `第 ${slot.index} 张`;
|
||
card.append(image);
|
||
} else if (slot.state === "failed") {
|
||
const retry = document.createElement("button");
|
||
retry.type = "button";
|
||
retry.className = "o1igs-slot-retry";
|
||
retry.disabled = false;
|
||
retry.title = slot.error || `重新生成第 ${slot.index} 张`;
|
||
const icon = document.createElement("b");
|
||
icon.textContent = "↻";
|
||
const label = document.createElement("span");
|
||
label.textContent = `失败 · 点击重试`;
|
||
retry.append(icon, label);
|
||
retry.addEventListener("click", () => retryFailedSaveSlot(node, slot.index));
|
||
card.append(retry);
|
||
} else {
|
||
const label = document.createElement("span");
|
||
label.textContent = slot.state === "cancelled"
|
||
? "已取消"
|
||
: slot.state === "running" ? "生成中" : "等待中";
|
||
card.append(label);
|
||
}
|
||
grid.append(card);
|
||
}
|
||
const desiredHeight = widgetHeight + estimateSaveNodeChromeHeight(node);
|
||
if (Array.isArray(node.size) && Math.abs(Number(node.size[1]) - desiredHeight) > 1) {
|
||
node.setSize?.([node.size[0], desiredHeight]);
|
||
}
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
|
||
function initializeSaveSlots(node, tasks) {
|
||
clearTimeout(node?._o1igsPreviewFitTimer);
|
||
node._o1igsSlots = (tasks || []).map((task, offset) => {
|
||
const structured = task && typeof task === "object";
|
||
return {
|
||
index: offset + 1,
|
||
state: "pending",
|
||
prompt: String(structured ? task.prompt || "" : task || ""),
|
||
references: structured ? parseReferences(task.references || []) : [],
|
||
error: "",
|
||
image: null,
|
||
};
|
||
});
|
||
persistSaveSlots(node);
|
||
syncSaveSlotsWidget(node);
|
||
}
|
||
|
||
function updateSaveSlotsForState(node, detail, retrySlotIndex = 0) {
|
||
const state = String(detail?.state || "");
|
||
const targetState = state === "cancelled" ? "cancelled" : state === "failed" ? "failed" : state;
|
||
const error = String(detail?.error || "");
|
||
node._o1igsSlots = normalizeSaveSlots(node._o1igsSlots).map((slot) => {
|
||
if (retrySlotIndex && slot.index !== retrySlotIndex) return slot;
|
||
if (slot.state === "success") return slot;
|
||
return {
|
||
...slot,
|
||
state: targetState === "queued" ? "pending" : targetState,
|
||
error: targetState === "failed" ? error : slot.error,
|
||
};
|
||
});
|
||
if (state === "failed" || state === "cancelled") persistSaveSlots(node);
|
||
syncSaveSlotsWidget(node);
|
||
}
|
||
|
||
function applyCompletedSaveSlots(
|
||
node,
|
||
detail,
|
||
savedImages,
|
||
retrySlotIndex = 0,
|
||
layerDecomposition = false,
|
||
) {
|
||
const normalizedImages = normalizeSaveResults(savedImages);
|
||
let slots = normalizeSaveSlots(node._o1igsSlots);
|
||
const multiResultRequest = layerDecomposition
|
||
&& Number(detail?.result_count || normalizedImages.length)
|
||
> Number(detail?.request_count || detail?.total_count || slots.length || 1);
|
||
if (multiResultRequest && normalizedImages.length) {
|
||
if (slots.length) {
|
||
slots[0] = { ...slots[0], state: "success", image: normalizedImages[0], error: "" };
|
||
node._o1igsSlots = slots;
|
||
persistSaveSlots(node);
|
||
syncSaveSlotsWidget(node);
|
||
}
|
||
return normalizedImages;
|
||
}
|
||
if (!slots.length) {
|
||
const total = Math.max(
|
||
1,
|
||
Math.floor(Number(detail?.total_count) || 0),
|
||
retrySlotIndex,
|
||
...normalizedImages.map((image, offset) => Number(image.request_index) || offset + 1),
|
||
);
|
||
slots = Array.from({ length: total }, (_, offset) => ({
|
||
index: offset + 1,
|
||
state: "pending",
|
||
prompt: "",
|
||
error: "",
|
||
image: null,
|
||
}));
|
||
}
|
||
const retryImage = retrySlotIndex ? normalizedImages[0] || null : null;
|
||
const imageByIndex = new Map();
|
||
for (const image of normalizedImages) {
|
||
const index = Math.max(1, Number(image.request_index) || retrySlotIndex || imageByIndex.size + 1);
|
||
if (!imageByIndex.has(index)) imageByIndex.set(index, image);
|
||
}
|
||
const failedByIndex = new Map((detail?.failed_items || []).map((item) => [
|
||
Math.max(1, Math.floor(Number(item?.request_index) || 1)),
|
||
String(item?.error || "图片生成失败"),
|
||
]));
|
||
node._o1igsSlots = slots.map((slot) => {
|
||
if (retrySlotIndex && slot.index !== retrySlotIndex) return slot;
|
||
const image = retryImage || imageByIndex.get(slot.index);
|
||
if (image) return {
|
||
...slot,
|
||
state: "success",
|
||
image: { ...image, request_index: slot.index },
|
||
error: "",
|
||
};
|
||
const failure = failedByIndex.get(slot.index) || "本次没有返回图片";
|
||
return { ...slot, state: "failed", image: null, error: failure };
|
||
});
|
||
persistSaveSlots(node);
|
||
syncSaveSlotsWidget(node);
|
||
const completedSlotImages = normalizeSaveSlots(node._o1igsSlots)
|
||
.filter((slot) => slot.state === "success" && slot.image)
|
||
.map((slot) => slot.image);
|
||
return retrySlotIndex ? completedSlotImages : normalizedImages;
|
||
}
|
||
|
||
function renderSaveResults(node, images, { persist = true } = {}) {
|
||
node._o1igsLastResults = normalizeSaveResults(images);
|
||
if (persist) persistSaveResults(node, node._o1igsLastResults);
|
||
syncSaveSlotsWidget(node);
|
||
scheduleNativePreviewActionSync();
|
||
}
|
||
|
||
function nativeSavePreviewWidget(node) {
|
||
return (node?.widgets || []).find((widget) => (
|
||
widget?.constructor?.name === "ImagePreviewWidget"
|
||
|| (widget?.type === "custom" && widget?.serialize === false && Number(widget?.computedHeight) > 0)
|
||
));
|
||
}
|
||
|
||
function preferredNativeSavePreviewHeight(node, images = node?.imgs || []) {
|
||
const sourceImages = Array.isArray(images) ? images : [];
|
||
const loaded = sourceImages.filter((image) => (
|
||
Number(image?.naturalWidth || image?.width) > 0
|
||
&& Number(image?.naturalHeight || image?.height) > 0
|
||
));
|
||
if (!sourceImages.length || loaded.length !== sourceImages.length) return 0;
|
||
|
||
const width = Math.max(1, Number(node?.size?.[0]) || SAVE_NODE_LAYOUT_SIZE[0]);
|
||
const selectedIndex = Number.isInteger(node?.imageIndex)
|
||
&& node.imageIndex >= 0
|
||
&& node.imageIndex < loaded.length
|
||
? node.imageIndex
|
||
: null;
|
||
let imageHeight = 0;
|
||
if (selectedIndex != null || loaded.length === 1) {
|
||
const image = loaded[selectedIndex ?? 0];
|
||
imageHeight = width * Number(image.naturalHeight || image.height)
|
||
/ Number(image.naturalWidth || image.width);
|
||
} else {
|
||
const columns = saveSlotsColumnCount(loaded.length);
|
||
const cellWidth = width / columns;
|
||
for (let offset = 0; offset < loaded.length; offset += columns) {
|
||
const row = loaded.slice(offset, offset + columns);
|
||
const tallestRatio = Math.max(...row.map((image) => (
|
||
Number(image.naturalHeight || image.height)
|
||
/ Number(image.naturalWidth || image.width)
|
||
)));
|
||
imageHeight += cellWidth * tallestRatio;
|
||
}
|
||
}
|
||
return Math.max(
|
||
SAVE_PREVIEW_MIN_HEIGHT,
|
||
Math.min(SAVE_PREVIEW_MAX_HEIGHT, Math.ceil(imageHeight + SAVE_PREVIEW_SIZE_LABEL_HEIGHT)),
|
||
);
|
||
}
|
||
|
||
function fitSaveNodeToNativeImages(node) {
|
||
if (!node || saveSlotsVisible(node)) return false;
|
||
const preview = nativeSavePreviewWidget(node);
|
||
const currentPreviewHeight = Number(preview?.computedHeight) || 0;
|
||
const preferredPreviewHeight = preferredNativeSavePreviewHeight(node);
|
||
const currentNodeHeight = Number(node?.size?.[1]) || 0;
|
||
if (!currentPreviewHeight || !preferredPreviewHeight || !currentNodeHeight) return false;
|
||
|
||
const fixedHeight = Math.max(0, currentNodeHeight - currentPreviewHeight);
|
||
const targetHeight = Math.ceil(fixedHeight + preferredPreviewHeight);
|
||
if (Math.abs(targetHeight - currentNodeHeight) > 1) {
|
||
node.setSize?.([node.size[0], targetHeight]);
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function scheduleSaveNodeImageFit(node, attempt = 0) {
|
||
clearTimeout(node?._o1igsPreviewFitTimer);
|
||
if (!node || saveSlotsVisible(node)) return;
|
||
const run = () => {
|
||
if (fitSaveNodeToNativeImages(node) || attempt >= 20 || saveSlotsVisible(node)) return;
|
||
node._o1igsPreviewFitTimer = setTimeout(() => scheduleSaveNodeImageFit(node, attempt + 1), 50);
|
||
};
|
||
requestAnimationFrame(run);
|
||
}
|
||
|
||
function restoreNativeSavePreview(node) {
|
||
const images = normalizeSaveResults(node?._o1igsLastResults);
|
||
if (!images.length) return;
|
||
const signature = JSON.stringify(images);
|
||
requestAnimationFrame(() => {
|
||
if (node._o1igsNativeRestoreSignature === signature) return;
|
||
const current = normalizeSaveResults(app.nodeOutputs?.[String(node.id)]?.images);
|
||
if (JSON.stringify(current) === signature) {
|
||
node._o1igsNativeRestoreSignature = signature;
|
||
scheduleNativePreviewActionSync();
|
||
return;
|
||
}
|
||
const output = { images };
|
||
node._o1igsRestoringPreview = true;
|
||
try {
|
||
if (typeof api.dispatchCustomEvent === "function") {
|
||
api.dispatchCustomEvent("executed", {
|
||
node: node.id,
|
||
display_node: node.id,
|
||
output,
|
||
prompt_id: `o1key-restored-${node.id}`,
|
||
});
|
||
} else {
|
||
node.onExecuted?.(output);
|
||
}
|
||
node._o1igsNativeRestoreSignature = signature;
|
||
} finally {
|
||
node._o1igsRestoringPreview = false;
|
||
}
|
||
scheduleNativePreviewActionSync();
|
||
});
|
||
}
|
||
|
||
function setSaveBusy(node, busy, state = "running", progress = 0) {
|
||
node._o1igsBusy = busy;
|
||
node._o1igsState = busy ? state : "";
|
||
node._o1igsProgress = busy ? Math.max(0, Math.min(1, Number(progress) || 0)) : 0;
|
||
if (node._o1igsProgressTrack) node._o1igsProgressTrack.title = busy ? state : "";
|
||
syncSaveProgressOverlay(node);
|
||
syncSaveSlotsWidget(node);
|
||
syncNativePreviewAction(node);
|
||
}
|
||
|
||
function activeSaveBatchIds(node) {
|
||
node._o1igsActiveBatchIds ??= new Set();
|
||
return node._o1igsActiveBatchIds;
|
||
}
|
||
|
||
function terminalSaveBatchIds(node) {
|
||
node._o1igsTerminalBatchIds ??= new Set();
|
||
return node._o1igsTerminalBatchIds;
|
||
}
|
||
|
||
function savingSaveBatchIds(node) {
|
||
node._o1igsSavingBatchIds ??= new Set();
|
||
return node._o1igsSavingBatchIds;
|
||
}
|
||
|
||
function pendingBatchIds(node) {
|
||
node._o1igPendingBatchIds ??= new Set();
|
||
return node._o1igPendingBatchIds;
|
||
}
|
||
|
||
function updateGeneratorActivity(node, completedText = "") {
|
||
void completedText;
|
||
const remaining = pendingBatchIds(node).size;
|
||
node._o1igRunning = remaining > 0;
|
||
if (!node._o1igPending?.length && !node._o1igMaskPending) {
|
||
setStatus(node, "", "");
|
||
}
|
||
}
|
||
|
||
function beginGenerationBatch(source, saveNode, batchId = "") {
|
||
pendingBatchIds(source).add(saveNode.id);
|
||
const effectiveBatchId = String(batchId || saveNode.properties?.o1keyBatchId || "");
|
||
if (effectiveBatchId) {
|
||
activeSaveBatchIds(saveNode).add(effectiveBatchId);
|
||
terminalSaveBatchIds(saveNode).delete(effectiveBatchId);
|
||
}
|
||
saveNode._o1igsSourceGeneratorId = source.id;
|
||
setSaveBusy(saveNode, true, "queued", 0);
|
||
updateGeneratorActivity(source);
|
||
}
|
||
|
||
function beginLayerGenerationBatch(source, layerSaveNode, batchId = "") {
|
||
if (!layerSaveNode) return;
|
||
const effectiveBatchId = String(batchId || "");
|
||
if (effectiveBatchId) {
|
||
activeSaveBatchIds(layerSaveNode).add(effectiveBatchId);
|
||
terminalSaveBatchIds(layerSaveNode).delete(effectiveBatchId);
|
||
}
|
||
layerSaveNode._o1igsSourceGeneratorId = source.id;
|
||
layerSaveNode._o1igsLayerBatchId = effectiveBatchId;
|
||
setSaveBusy(layerSaveNode, true, "queued", 0);
|
||
}
|
||
|
||
function finishLayerGenerationBatch(layerSaveNode, batchId = "") {
|
||
if (!layerSaveNode) return;
|
||
const effectiveBatchId = String(batchId || layerSaveNode._o1igsLayerBatchId || "");
|
||
if (effectiveBatchId) {
|
||
activeSaveBatchIds(layerSaveNode).delete(effectiveBatchId);
|
||
savingSaveBatchIds(layerSaveNode).delete(effectiveBatchId);
|
||
}
|
||
if (String(layerSaveNode._o1igsLayerBatchId || "") === effectiveBatchId) {
|
||
delete layerSaveNode._o1igsLayerBatchId;
|
||
}
|
||
const stillBusy = activeSaveBatchIds(layerSaveNode).size > 0;
|
||
setSaveBusy(layerSaveNode, stillBusy, stillBusy ? "running" : "", layerSaveNode._o1igsProgress);
|
||
}
|
||
|
||
function finishGenerationBatch(saveNode, completedText = "生成完成", batchId = "") {
|
||
const source = findUpstreamGenerator(saveNode)
|
||
|| saveNode.graph?.getNodeById?.(saveNode._o1igsSourceGeneratorId);
|
||
const standardExecution = Boolean(
|
||
saveNode._o1igsStandardQueueReserved || saveNode._o1igsStandardExecutionPending,
|
||
);
|
||
if (standardExecution) {
|
||
setSaveBusy(saveNode, false);
|
||
const standardSource = clearStandardExecution(saveNode) || source;
|
||
if (standardSource) {
|
||
if (pendingBatchIds(standardSource).size) updateGeneratorActivity(standardSource);
|
||
else {
|
||
standardSource._o1igRunning = false;
|
||
setStatus(standardSource, "", "");
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
const effectiveBatchId = String(batchId || saveNode.properties?.o1keyBatchId || "");
|
||
if (effectiveBatchId) {
|
||
parallelBatches.delete(effectiveBatchId);
|
||
activeSaveBatchIds(saveNode).delete(effectiveBatchId);
|
||
savingSaveBatchIds(saveNode).delete(effectiveBatchId);
|
||
}
|
||
const stillBusy = activeSaveBatchIds(saveNode).size > 0;
|
||
setSaveBusy(saveNode, stillBusy, stillBusy ? "running" : "", saveNode._o1igsProgress);
|
||
if (!stillBusy) delete saveNode.properties?.o1keyRetrySlotIndex;
|
||
if (!source) return;
|
||
if (!stillBusy) pendingBatchIds(source).delete(saveNode.id);
|
||
updateGeneratorActivity(source, completedText);
|
||
}
|
||
|
||
function findBatchNodes(detail) {
|
||
const batchId = String(detail?.batch_id || "");
|
||
if (!batchId) return {};
|
||
const registered = parallelBatches.get(batchId);
|
||
const saveNodeId = detail?.save_node_id ?? registered?.saveNodeId ?? registered?.saveNode?.id;
|
||
const generatorNodeId = detail?.generator_node_id
|
||
?? registered?.generatorNodeId
|
||
?? registered?.source?.id;
|
||
if (saveNodeId == null || generatorNodeId == null) return {};
|
||
|
||
const registeredSaveNode = isActiveGraphNode(registered?.saveNode)
|
||
&& String(registered.saveNode.id) === String(saveNodeId)
|
||
? registered.saveNode
|
||
: null;
|
||
const saveNode = registeredSaveNode || activeGraphNodeById(saveNodeId);
|
||
const registeredSource = isActiveGraphNode(registered?.source)
|
||
&& String(registered.source.id) === String(generatorNodeId)
|
||
? registered.source
|
||
: null;
|
||
const source = (saveNode ? findUpstreamGenerator(saveNode) : null) || registeredSource;
|
||
if (!saveNode || !source) return {};
|
||
if (!registered && saveNode.properties?.o1keyBatchId !== batchId) return {};
|
||
if (String(saveNode.id) !== String(saveNodeId)) return {};
|
||
if (String(source.id) !== String(generatorNodeId)) return {};
|
||
const registeredLayerSaveNode = isActiveGraphNode(registered?.layerSaveNode)
|
||
&& String(registered.layerSaveNode.id) === String(registered?.layerSaveNodeId)
|
||
? registered.layerSaveNode
|
||
: null;
|
||
const layerSaveNode = registeredLayerSaveNode || findLayerSaveNode(source, saveNode);
|
||
if (registered) Object.assign(registered, {
|
||
source,
|
||
saveNode,
|
||
generatorNodeId: source.id,
|
||
saveNodeId: saveNode.id,
|
||
layerSaveNode,
|
||
layerSaveNodeId: layerSaveNode?.id,
|
||
});
|
||
return { batchId, saveNode, source, layerSaveNode };
|
||
}
|
||
|
||
async function saveWorkflowMetadata() {
|
||
let prompt = null;
|
||
let workflow = null;
|
||
try {
|
||
const promptData = await app.graphToPrompt?.();
|
||
prompt = promptData?.output || null;
|
||
workflow = promptData?.workflow || null;
|
||
} catch {
|
||
// Saving the generated pixels must not fail because prompt serialization did.
|
||
}
|
||
if (!workflow) {
|
||
try {
|
||
workflow = app.graph?.serialize?.() || null;
|
||
} catch {
|
||
// Keep the save path available even in older frontend builds.
|
||
}
|
||
}
|
||
return {
|
||
prompt,
|
||
extra_pnginfo: workflow ? { workflow } : null,
|
||
};
|
||
}
|
||
|
||
async function promoteTempResults(batchId, saveNode, images) {
|
||
const metadata = await saveWorkflowMetadata();
|
||
const saveSettings = generatorSaveSettings(findConnectedGenerator(saveNode));
|
||
const response = await api.fetchApi("/o1key/image/save", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
batch_id: batchId,
|
||
save_node_id: saveNode.id,
|
||
images,
|
||
filename_prefix: saveSettings.filename_prefix,
|
||
format: saveSettings.format,
|
||
save_location: saveSettings.save_location,
|
||
naming_rule: saveSettings.naming_rule,
|
||
prompt: metadata.prompt,
|
||
extra_pnginfo: metadata.extra_pnginfo,
|
||
}),
|
||
});
|
||
const result = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(result?.error || `保存图片失败(HTTP ${response.status})`);
|
||
const saved = normalizeSaveResults(result?.images)
|
||
.filter((item) => item.type === "output" || item.external_saved === true)
|
||
.map((item) => ({ ...item, batch_id: item.batch_id || batchId }));
|
||
if (!saved.length) throw new Error("保存节点没有返回图片结果");
|
||
return saved;
|
||
}
|
||
|
||
function dispatchSaveResults(saveNode, batchId, images) {
|
||
const output = { images };
|
||
const animated = animatedFlagsForSaveResults(images);
|
||
if (animated) output.animated = animated;
|
||
saveNode._o1igsDispatchBatchId = batchId;
|
||
if (typeof api.dispatchCustomEvent === "function") {
|
||
api.dispatchCustomEvent("executed", {
|
||
node: saveNode.id,
|
||
display_node: saveNode.id,
|
||
output,
|
||
prompt_id: batchId,
|
||
});
|
||
} else if (typeof saveNode.onExecuted === "function") {
|
||
saveNode.onExecuted(output);
|
||
} else {
|
||
renderSaveResults(saveNode, images);
|
||
finishGenerationBatch(saveNode, "生成完成", batchId);
|
||
}
|
||
if (saveNode._o1igsDispatchBatchId === batchId) {
|
||
delete saveNode._o1igsDispatchBatchId;
|
||
}
|
||
}
|
||
|
||
async function fetchParallelBatchStatus(batchId) {
|
||
const registered = parallelBatches.get(batchId);
|
||
const params = new URLSearchParams();
|
||
const generatorNodeId = registered?.generatorNodeId ?? registered?.source?.id;
|
||
const saveNodeId = registered?.saveNodeId ?? registered?.saveNode?.id;
|
||
if (generatorNodeId != null) params.set("generator_node_id", String(generatorNodeId));
|
||
if (saveNodeId != null) params.set("save_node_id", String(saveNodeId));
|
||
const query = params.toString();
|
||
const response = await api.fetchApi(`/o1key/image/jobs/${encodeURIComponent(batchId)}${query ? `?${query}` : ""}`, {
|
||
cache: "no-store",
|
||
});
|
||
if (response.status === 404) return { notFound: true };
|
||
const result = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(result?.error || `HTTP ${response.status}`);
|
||
return { detail: result };
|
||
}
|
||
|
||
async function recoverParallelBatch(saveNode) {
|
||
const batchId = String(saveNode?.properties?.o1keyBatchId || "");
|
||
if (!batchId) return;
|
||
const existing = parallelBatches.get(batchId);
|
||
if (terminalSaveBatchIds(saveNode).has(batchId)) {
|
||
setSaveBusy(saveNode, false);
|
||
return;
|
||
}
|
||
if (saveNode._o1igsLastResults?.length) {
|
||
if (
|
||
existing
|
||
&& String(existing.saveNodeId ?? existing.saveNode?.id) === String(saveNode.id)
|
||
) parallelBatches.delete(batchId);
|
||
setSaveBusy(saveNode, false);
|
||
return;
|
||
}
|
||
const source = findUpstreamGenerator(saveNode);
|
||
if (!source) return;
|
||
if (Number(saveNode.properties?.o1keyGeneratorNodeId) !== Number(source.id)) return;
|
||
if (existing?.source === source && existing?.saveNode === saveNode) return;
|
||
|
||
const retrySlotIndex = Math.max(
|
||
0,
|
||
Math.floor(Number(saveNode.properties?.o1keyRetrySlotIndex) || 0),
|
||
);
|
||
const layerDecomposition = isLayerDecompositionEnabled(source);
|
||
const layerSaveNode = layerDecomposition
|
||
? findLayerSaveNode(source, saveNode) || acquireLayerSaveNodeForBatch(source, saveNode)
|
||
: null;
|
||
const registered = existing || {};
|
||
Object.assign(registered, {
|
||
source,
|
||
saveNode,
|
||
generatorNodeId: source.id,
|
||
saveNodeId: saveNode.id,
|
||
layerSaveNode,
|
||
layerSaveNodeId: layerSaveNode?.id,
|
||
layerDecomposition,
|
||
progress: Number(existing?.progress) || 0,
|
||
recovering: true,
|
||
retrySlotIndex,
|
||
});
|
||
parallelBatches.set(batchId, registered);
|
||
updateNativeQueueJob({
|
||
batch_id: batchId,
|
||
generator_node_id: source.id,
|
||
save_node_id: saveNode.id,
|
||
state: "queued",
|
||
});
|
||
beginGenerationBatch(source, saveNode, batchId);
|
||
beginLayerGenerationBatch(source, layerSaveNode, batchId);
|
||
if (registered.lastDetail) {
|
||
handleParallelImageJob(registered.lastDetail);
|
||
if (["completed", "failed", "cancelled"].includes(String(registered.lastDetail.state || ""))) return;
|
||
if (registered.monitoring) return;
|
||
}
|
||
try {
|
||
const status = await fetchParallelBatchStatus(batchId);
|
||
if (status.notFound) {
|
||
handleParallelImageJob({
|
||
batch_id: batchId,
|
||
generator_node_id: source.id,
|
||
save_node_id: saveNode.id,
|
||
state: "failed",
|
||
error: "任务不存在或未成功提交",
|
||
});
|
||
return;
|
||
}
|
||
handleParallelImageJob(status.detail);
|
||
if (status.detail?.state === "queued" || status.detail?.state === "running") {
|
||
monitorParallelBatch(batchId);
|
||
}
|
||
} catch {
|
||
monitorParallelBatch(batchId);
|
||
}
|
||
}
|
||
|
||
async function monitorParallelBatch(batchId) {
|
||
const registered = parallelBatches.get(batchId);
|
||
if (!registered || registered.monitoring) return;
|
||
registered.monitoring = true;
|
||
try {
|
||
while (parallelBatches.has(batchId)) {
|
||
await new Promise((resolve) => setTimeout(resolve, 2500));
|
||
if (!parallelBatches.has(batchId)) break;
|
||
try {
|
||
const status = await fetchParallelBatchStatus(batchId);
|
||
if (status.notFound) {
|
||
const current = parallelBatches.get(batchId);
|
||
handleParallelImageJob({
|
||
batch_id: batchId,
|
||
generator_node_id: current?.generatorNodeId ?? current?.source?.id,
|
||
save_node_id: current?.saveNodeId ?? current?.saveNode?.id,
|
||
state: "failed",
|
||
error: "任务不存在或未成功提交",
|
||
});
|
||
break;
|
||
}
|
||
handleParallelImageJob(status.detail);
|
||
if (["completed", "failed", "cancelled"].includes(String(status.detail?.state || ""))) {
|
||
break;
|
||
}
|
||
} catch {
|
||
// A local ComfyUI reconnect is normally brief. Keep the paid task
|
||
// registered and retry instead of detaching its result node.
|
||
}
|
||
}
|
||
} finally {
|
||
if (parallelBatches.get(batchId) === registered) registered.monitoring = false;
|
||
}
|
||
}
|
||
|
||
function handleParallelImageJob(detail) {
|
||
const rawBatchId = String(detail?.batch_id || "");
|
||
if (!rawBatchId) return;
|
||
const registered = parallelBatches.get(rawBatchId);
|
||
const expectedGeneratorNodeId = registered?.generatorNodeId ?? registered?.source?.id;
|
||
const expectedSaveNodeId = registered?.saveNodeId ?? registered?.saveNode?.id;
|
||
if (
|
||
expectedGeneratorNodeId != null
|
||
&& detail?.generator_node_id != null
|
||
&& String(expectedGeneratorNodeId) !== String(detail.generator_node_id)
|
||
) return;
|
||
if (
|
||
expectedSaveNodeId != null
|
||
&& detail?.save_node_id != null
|
||
&& String(expectedSaveNodeId) !== String(detail.save_node_id)
|
||
) return;
|
||
|
||
const state = String(detail?.state || "");
|
||
if (state === "queued" && registered?.state === "running") return;
|
||
if (registered) Object.assign(registered, {
|
||
lastDetail: detail,
|
||
state,
|
||
progress: Math.max(0, Math.min(1, Number(detail?.progress) || 0)),
|
||
queuePosition: Number(detail?.queue_position) || 0,
|
||
});
|
||
const { batchId, saveNode, source, layerSaveNode } = findBatchNodes(detail);
|
||
if (!batchId) {
|
||
updateNativeQueueJob(detail);
|
||
return;
|
||
}
|
||
const routeLayerResults = Boolean(registered?.layerDecomposition && layerSaveNode);
|
||
if (terminalSaveBatchIds(saveNode).has(batchId)) return;
|
||
if (state === "queued" || state === "running") {
|
||
const progress = Math.max(0, Math.min(1, Number(detail?.progress) || 0));
|
||
updateNativeQueueJob(detail);
|
||
const retrySlotIndex = Number(registered?.retrySlotIndex) || 0;
|
||
updateSaveSlotsForState(saveNode, detail, retrySlotIndex);
|
||
if (state === "running") {
|
||
applyPartialSaveSlots(saveNode, detail?.images, retrySlotIndex);
|
||
}
|
||
setSaveBusy(saveNode, true, state, progress);
|
||
if (routeLayerResults) setSaveBusy(layerSaveNode, true, state, progress);
|
||
updateGeneratorActivity(source);
|
||
return;
|
||
}
|
||
if (state === "completed") {
|
||
const retrySlotIndex = Number(registered?.retrySlotIndex) || 0;
|
||
const images = Array.isArray(detail?.images) ? detail.images.filter((item) => (
|
||
item?.batch_id === batchId
|
||
)) : [];
|
||
if (!images.length) {
|
||
updateNativeQueueJob(detail, { forceState: "failed", error: "生成完成但没有图片结果" });
|
||
updateSaveSlotsForState(saveNode, {
|
||
...detail,
|
||
state: "failed",
|
||
error: "生成完成但没有图片结果",
|
||
}, retrySlotIndex);
|
||
terminalSaveBatchIds(saveNode).add(batchId);
|
||
finishLayerGenerationBatch(layerSaveNode, batchId);
|
||
finishGenerationBatch(saveNode, "生成完成但没有图片结果", batchId);
|
||
return;
|
||
}
|
||
const tempImages = images.filter((item) => (
|
||
item?.type === "temp" && item?.external_saved !== true
|
||
));
|
||
if (tempImages.length) {
|
||
if (savingSaveBatchIds(saveNode).has(batchId)) return;
|
||
savingSaveBatchIds(saveNode).add(batchId);
|
||
updateNativeQueueJob(detail, { forceState: "saving" });
|
||
setSaveBusy(saveNode, true, "saving", 1);
|
||
if (routeLayerResults) setSaveBusy(layerSaveNode, true, "saving", 1);
|
||
updateGeneratorActivity(source);
|
||
void promoteTempResults(batchId, saveNode, tempImages).then((savedImages) => {
|
||
savingSaveBatchIds(saveNode).delete(batchId);
|
||
handleParallelImageJob({ ...detail, images: savedImages });
|
||
}).catch((error) => {
|
||
savingSaveBatchIds(saveNode).delete(batchId);
|
||
const message = error?.message || String(error);
|
||
handleParallelImageJob({
|
||
...detail,
|
||
state: "failed",
|
||
error: message,
|
||
});
|
||
});
|
||
return;
|
||
}
|
||
terminalSaveBatchIds(saveNode).add(batchId);
|
||
updateNativeQueueJob(detail, { forceState: "completed", images });
|
||
const completeImages = applyCompletedSaveSlots(
|
||
saveNode,
|
||
detail,
|
||
images,
|
||
retrySlotIndex,
|
||
Boolean(registered?.layerDecomposition),
|
||
);
|
||
if (routeLayerResults) {
|
||
const { imageResults, layerResults } = splitLayerSaveResults(completeImages);
|
||
terminalSaveBatchIds(layerSaveNode).add(batchId);
|
||
if (layerResults.length) dispatchSaveResults(layerSaveNode, batchId, layerResults);
|
||
else finishLayerGenerationBatch(layerSaveNode, batchId);
|
||
dispatchSaveResults(saveNode, batchId, imageResults);
|
||
} else {
|
||
dispatchSaveResults(saveNode, batchId, completeImages);
|
||
}
|
||
if (detail?.warnings?.length) {
|
||
toast("warn", "部分图片生成失败", formatImageGenerationError(detail.warnings[0]));
|
||
}
|
||
return;
|
||
}
|
||
if (state === "failed" || state === "cancelled") {
|
||
terminalSaveBatchIds(saveNode).add(batchId);
|
||
const message = state === "cancelled" ? "任务已取消" : formatImageGenerationError(detail?.error);
|
||
updateNativeQueueJob(detail, { forceState: state, error: message });
|
||
updateSaveSlotsForState(saveNode, { ...detail, error: message }, Number(registered?.retrySlotIndex) || 0);
|
||
finishLayerGenerationBatch(layerSaveNode, batchId);
|
||
finishGenerationBatch(saveNode, message, batchId);
|
||
toast(state === "cancelled" ? "info" : "error", state === "cancelled" ? "已取消" : "生成失败", message);
|
||
}
|
||
}
|
||
|
||
function failOldestGenerationBatch(source, message) {
|
||
const standardSaveNode = activeStandardSaveNode(source);
|
||
if (standardSaveNode) {
|
||
setSaveBusy(standardSaveNode, false);
|
||
clearStandardExecution(standardSaveNode);
|
||
source._o1igRunning = false;
|
||
setStatus(source, "", "");
|
||
return true;
|
||
}
|
||
const oldestId = pendingBatchIds(source).values().next().value;
|
||
if (oldestId == null) {
|
||
source._o1igRunning = false;
|
||
setStatus(source, message, "error");
|
||
return false;
|
||
}
|
||
const saveNode = (source.graph || app.graph)?.getNodeById?.(oldestId);
|
||
if (saveNode) finishGenerationBatch(saveNode, message);
|
||
else {
|
||
pendingBatchIds(source).delete(oldestId);
|
||
updateGeneratorActivity(source, message);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function findUpstreamGenerator(node) {
|
||
const graph = node.graph || app.graph;
|
||
const link = getGraphLink(graph, node.inputs?.[0]?.link);
|
||
const source = link ? graph?.getNodeById?.(link.origin_id) : null;
|
||
return source?.comfyClass === NODE_TYPE || source?.type === NODE_TYPE ? source : null;
|
||
}
|
||
|
||
async function regenerateFromSaveNode(node, imageIndex = 0) {
|
||
const source = findUpstreamGenerator(node);
|
||
if (!source) {
|
||
toast("warn", "无法重新生成", "请连接 o1key 图片生成节点");
|
||
return;
|
||
}
|
||
|
||
const nextSeed = Math.floor(Math.random() * 0x7fffffff);
|
||
setWidgetValue(source, "seed", nextSeed);
|
||
await queueGeneration(source, 1);
|
||
}
|
||
|
||
async function retryFailedSaveSlot(node, slotIndex) {
|
||
const slot = normalizeSaveSlots(node?._o1igsSlots).find(
|
||
(item) => item.index === Number(slotIndex),
|
||
);
|
||
if (!slot || slot.state !== "failed") return;
|
||
const source = findUpstreamGenerator(node);
|
||
if (!source) {
|
||
toast("warn", "无法重新生成", "请连接 o1key 图片生成节点");
|
||
return;
|
||
}
|
||
const nextSeed = Math.floor(Math.random() * 0x7fffffff);
|
||
setWidgetValue(source, "seed", nextSeed);
|
||
await queueGeneration(source, 1, {
|
||
targetSaveNode: node,
|
||
retrySlotIndex: slot.index,
|
||
promptOverride: slot.prompt || source._o1igPrompt?.value || "",
|
||
referenceOverride: slot.references || [],
|
||
});
|
||
}
|
||
|
||
function syncBatchLayout(node) {
|
||
if (!node?._o1igBatchToggle) return;
|
||
const enabled = Boolean(node._o1igBatchEnabled);
|
||
const singleReferences = enabled
|
||
&& batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES;
|
||
node._o1igBatchToggle.classList.toggle("enabled", enabled);
|
||
node._o1igBatchToggle.setAttribute("aria-pressed", enabled ? "true" : "false");
|
||
node._o1igBatchModeWrap?.classList.toggle("visible", enabled);
|
||
node._o1igModelAssets?.classList.toggle("visible", enabled && !singleReferences);
|
||
if (node._o1igCountLabel) {
|
||
node._o1igCountLabel.textContent = singleReferences ? "每图生成数" : enabled ? "每组生图数" : "生图数量";
|
||
}
|
||
const capabilities = MODEL_CAPABILITIES[node._o1igModel?.value] || MODEL_CAPABILITIES["Nano Banana 2"];
|
||
setFieldVisible(node._o1igMaskField, Boolean(capabilities.mask && !enabled));
|
||
setWidgetValue(node, "批量出图", enabled);
|
||
setWidgetValue(node, "批量模式", batchModeOf(node));
|
||
setWidgetValue(node, "模特图清单", JSON.stringify(node._o1igModelReferences || []));
|
||
renderReferences(node);
|
||
updateBatchSummary(node);
|
||
fitNode(node);
|
||
}
|
||
|
||
function syncModelOptions(node) {
|
||
const model = normalizeUnifiedModel(node._o1igModel.value);
|
||
node._o1igModel.value = model;
|
||
const capabilities = MODEL_CAPABILITIES[model] || MODEL_CAPABILITIES["Nano Banana 2"];
|
||
const isGptImage = isGptImageModel(model);
|
||
if (isGptImage && node._o1igApplyGptDefaults) {
|
||
if (!node._o1igOutputTouched) node._o1igOutputFormat.value = "png";
|
||
if (!node._o1igResizeTouched) node._o1igResize.value = "智能缩放";
|
||
node._o1igApplyGptDefaults = false;
|
||
}
|
||
const isSeedream = model === "Seedream 5.0 Pro";
|
||
if (!isSeedream && node._o1igLayerDecomposition) {
|
||
node._o1igLayerDecomposition.value = "关闭";
|
||
}
|
||
const layerDecomposition = isSeedream
|
||
&& node._o1igLayerDecomposition?.value === "开启";
|
||
const isNano2 = model === "Nano Banana 2.1" || model === "Nano Banana 2";
|
||
const resolutions = isSeedream
|
||
? layerDecomposition ? SEEDREAM_LAYER_RESOLUTIONS : SEEDREAM_RESOLUTIONS
|
||
: isGptImage
|
||
? GPT_RESOLUTIONS
|
||
: ["智能", "1K", "2K", "4K"];
|
||
const ratios = isSeedream
|
||
? SEEDREAM_RATIOS
|
||
: isGptImage
|
||
? GPT_RATIOS
|
||
: isNano2
|
||
? ALL_RATIOS
|
||
: ALL_RATIOS.filter((ratio) => !NANO2_ONLY_RATIOS.has(ratio));
|
||
replaceOptions(node._o1igResolution, resolutions, findWidget(node, "分辨率")?.value || "智能");
|
||
replaceOptions(node._o1igRatio, ratios, findWidget(node, "宽高比")?.value || "智能");
|
||
replaceOptions(node._o1igCount, imageCountOptions(model, node._o1igCount.value), node._o1igCount.value);
|
||
if (isGptImage) {
|
||
const qualities = /^gpt-image-2\.[56]-/.test(model) ? GPT_25_QUALITIES : GPT_QUALITIES;
|
||
replaceOptions(
|
||
node._o1igQuality,
|
||
qualities,
|
||
qualities.includes(node._o1igQuality.value) ? node._o1igQuality.value : "自动",
|
||
);
|
||
}
|
||
if (layerDecomposition) {
|
||
node._o1igBatchEnabled = false;
|
||
node._o1igCount.value = "1";
|
||
node._o1igOutputFormat.value = "png";
|
||
}
|
||
if (node._o1igLayerDecompositionField) {
|
||
setFieldVisible(node._o1igLayerDecompositionField, isSeedream);
|
||
setFieldVisible(node._o1igRatioField, !layerDecomposition);
|
||
setFieldVisible(node._o1igCountField, !layerDecomposition);
|
||
}
|
||
setFieldVisible(node._o1igThinkingField, capabilities.thinking);
|
||
setFieldVisible(node._o1igQualityField, capabilities.quality);
|
||
setFieldVisible(node._o1igComplexityField, capabilities.complexity === true);
|
||
setFieldVisible(node._o1igOutputFormatField, capabilities.output && !layerDecomposition);
|
||
setFieldVisible(node._o1igBackgroundField, isGptImage);
|
||
setFieldVisible(node._o1igResizeField, capabilities.resize);
|
||
setFieldVisible(node._o1igMaskField, capabilities.mask && !node._o1igBatchEnabled);
|
||
if (USE_NATIVE_LITEGRAPH_PARAMETERS) {
|
||
setNativeWidgetVisible(node, "思考等级", capabilities.thinking);
|
||
setNativeWidgetVisible(node, "质量", capabilities.quality);
|
||
setNativeWidgetVisible(node, "复杂度", capabilities.complexity === true);
|
||
setNativeWidgetVisible(node, "输出格式", capabilities.output && !layerDecomposition);
|
||
setNativeWidgetVisible(node, "背景", isGptImage);
|
||
setNativeWidgetVisible(node, "缩放图片", capabilities.resize);
|
||
setNativeWidgetVisible(node, "图层拆分", isSeedream);
|
||
setNativeWidgetVisible(node, "格式", capabilities.saveFormat);
|
||
setNativeWidgetVisible(node, "批量模式", Boolean(node._o1igBatchEnabled));
|
||
setNativeWidgetVisible(
|
||
node,
|
||
"帧数",
|
||
capabilities.frames === true && node._o1igOutputFormat?.value === "gif",
|
||
);
|
||
setNativeWidgetVisible(
|
||
node,
|
||
"帧时长ms",
|
||
capabilities.frames === true && node._o1igOutputFormat?.value === "gif",
|
||
);
|
||
}
|
||
syncGptOutputOptions(node);
|
||
syncGeneratorSaveControls(node);
|
||
syncResizeWarning(node);
|
||
setWidgetValue(node, "模型", model);
|
||
setWidgetValue(node, "分辨率", node._o1igResolution.value);
|
||
setWidgetValue(node, "宽高比", node._o1igRatio.value);
|
||
setWidgetValue(node, "质量", node._o1igQuality.value);
|
||
setWidgetValue(node, "缩放图片", node._o1igResize.value);
|
||
setWidgetValue(
|
||
node,
|
||
"生图数量",
|
||
layerDecomposition ? "1" : node._o1igCount?.value || findWidget(node, "生图数量")?.value || "1",
|
||
);
|
||
setWidgetValue(node, "输出格式", node._o1igOutputFormat.value);
|
||
setWidgetValue(node, "图层拆分", layerDecomposition);
|
||
if (node._o1igOutputsReady) syncGeneratorOutputVisibility(node);
|
||
if (node._o1igBatchBar) {
|
||
node._o1igBatchBar.style.display = USE_NATIVE_LITEGRAPH_PARAMETERS || layerDecomposition ? "none" : "";
|
||
}
|
||
syncBatchLayout(node);
|
||
syncNativeWidgetOptions(node);
|
||
}
|
||
|
||
async function optimizePrompt(node) {
|
||
if (node._o1igOptimizing) return;
|
||
const prompt = node._o1igPrompt?.value.trim() || "";
|
||
if (!prompt) {
|
||
setPromptOptimizeStatus(node, "请先输入提示词", "error");
|
||
node._o1igPrompt?.focus();
|
||
return;
|
||
}
|
||
if (hasPendingReferenceUploads(node)) {
|
||
setPromptOptimizeStatus(node, "请等待参考图上传完成", "error");
|
||
return;
|
||
}
|
||
if (node._o1igRunning) {
|
||
setPromptOptimizeStatus(node, "请等待当前生成任务提交完成", "error");
|
||
return;
|
||
}
|
||
|
||
node._o1igOptimizing = true;
|
||
node._o1igPrompt.readOnly = true;
|
||
node._o1igPromptOptimize.disabled = true;
|
||
node._o1igPromptOptimize.classList.add("busy");
|
||
setPromptOptimizeStatus(node, "AI帮写中…", "busy");
|
||
node._o1igGenerate.disabled = true;
|
||
try {
|
||
const response = await api.fetchApi("/o1key/image/prompt-optimize", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
prompt,
|
||
references: node._o1igReferences.map((item) => ({
|
||
name: String(item.name),
|
||
subfolder: String(item.subfolder || ""),
|
||
type: "input",
|
||
})),
|
||
}),
|
||
});
|
||
const payload = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(payload.error || `AI帮写失败 (${response.status})`);
|
||
const optimized = String(payload.prompt || "").trim();
|
||
if (!optimized) throw new Error("AI帮写结果为空");
|
||
node._o1igPrompt.value = optimized;
|
||
setWidgetValue(node, "prompt", optimized);
|
||
setPromptOptimizeStatus(node, "AI帮写完成", "ok");
|
||
toast("success", "AI帮写完成", "已结合当前参考图重新整理视觉需求");
|
||
} catch (error) {
|
||
const message = formatImageGenerationError(error?.message || error);
|
||
setPromptOptimizeStatus(node, message, "error");
|
||
toast("error", "AI帮写失败", message);
|
||
} finally {
|
||
node._o1igOptimizing = false;
|
||
node._o1igPrompt.readOnly = false;
|
||
node._o1igPromptOptimize.disabled = false;
|
||
node._o1igPromptOptimize.classList.remove("busy");
|
||
node._o1igGenerate.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function queueGeneration(node, imageCountOverride = null, options = {}) {
|
||
let saveNode = null;
|
||
let layerSaveNode = null;
|
||
let batchId = "";
|
||
const retrySlotIndex = Math.max(0, Math.floor(Number(options?.retrySlotIndex) || 0));
|
||
const storedReferenceOverride = parseReferences(options?.referenceOverride || []);
|
||
const layerDecomposition = isLayerDecompositionEnabled(node);
|
||
const requestedImageCount = layerDecomposition
|
||
? "1"
|
||
: normalizeImageCount(imageCountOverride ?? node._o1igCount.value, node._o1igModel.value);
|
||
const prompt = String(options?.promptOverride ?? node._o1igPrompt.value).trim();
|
||
const saveSettings = generatorSaveSettings(node);
|
||
if (!prompt && !layerDecomposition) {
|
||
flagEmptyPrompt(node);
|
||
return;
|
||
}
|
||
if (node._o1igOptimizing) {
|
||
setPromptOptimizeStatus(node, "请等待 AI帮写完成", "error");
|
||
return;
|
||
}
|
||
if (hasPendingReferenceUploads(node)) {
|
||
setStatus(node, "请等待图片上传完成", "error");
|
||
return;
|
||
}
|
||
if (layerDecomposition && node._o1igReferences.length !== 1) {
|
||
setStatus(node, "图层拆分必须且只能上传1张参考图", "error");
|
||
return;
|
||
}
|
||
if (node._o1igBatchEnabled && !retrySlotIndex) {
|
||
const singleReferences = batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES;
|
||
if (singleReferences && !node._o1igReferences.length) {
|
||
setStatus(node, "每张素材单独出图至少需要上传1张素材图", "error");
|
||
return;
|
||
}
|
||
if (!singleReferences && !node._o1igReferences.length) {
|
||
setStatus(node, "批量出图至少需要上传1张素材图", "error");
|
||
return;
|
||
}
|
||
if (!singleReferences && !node._o1igModelReferences.length) {
|
||
setStatus(node, "批量出图至少需要上传1张目标图", "error");
|
||
return;
|
||
}
|
||
if (
|
||
batchModeOf(node) === BATCH_MODE_GROUP_TO_TARGETS
|
||
&& node._o1igReferences.length >= MAX_REQUEST_REFERENCES
|
||
) {
|
||
setStatus(node, "整组素材模式最多上传9张素材图(另加1张目标图)", "error");
|
||
return;
|
||
}
|
||
if (node._o1igMask) {
|
||
setStatus(node, "批量出图暂不支持蒙版,请先移除蒙版", "error");
|
||
return;
|
||
}
|
||
}
|
||
if (!node._o1igBatchEnabled && node._o1igReferences.length > MAX_REQUEST_REFERENCES) {
|
||
setStatus(node, `普通模式最多支持 ${MAX_REQUEST_REFERENCES} 张参考图`, "error");
|
||
return;
|
||
}
|
||
if (!retrySlotIndex) setWidgetValue(node, "prompt", prompt);
|
||
setWidgetValue(node, "模型", node._o1igModel.value);
|
||
setWidgetValue(node, "模型线路", node._o1igRoute.value);
|
||
setWidgetValue(node, "思考等级", node._o1igThinking.value);
|
||
setWidgetValue(node, "分辨率", node._o1igResolution.value);
|
||
setWidgetValue(node, "宽高比", node._o1igRatio.value);
|
||
if (!retrySlotIndex) setWidgetValue(node, "生图数量", normalizeImageCount(node._o1igCount.value, node._o1igModel.value));
|
||
// The native seed widget already holds the value the queue will read.
|
||
setWidgetValue(node, "参考图清单", JSON.stringify(node._o1igReferences));
|
||
setWidgetValue(node, "质量", node._o1igQuality.value);
|
||
setWidgetValue(node, "输出格式", node._o1igOutputFormat.value);
|
||
setWidgetValue(node, "蒙版清单", JSON.stringify(node._o1igMask || {}));
|
||
setWidgetValue(node, "缩放图片", node._o1igResize.value);
|
||
setWidgetValue(node, "背景", node._o1igBackground.value);
|
||
setWidgetValue(node, "复杂度", normalizeGptComplexityLabel(node._o1igComplexity?.value));
|
||
setWidgetValue(node, "批量出图", Boolean(node._o1igBatchEnabled));
|
||
setWidgetValue(node, "批量模式", batchModeOf(node));
|
||
setWidgetValue(node, "模特图清单", JSON.stringify(node._o1igModelReferences));
|
||
setWidgetValue(node, "命名规则", saveSettings.naming_rule);
|
||
setWidgetValue(node, "filename_prefix", saveSettings.filename_prefix);
|
||
setWidgetValue(node, "格式", node._o1igSaveFormat.value);
|
||
setWidgetValue(node, "保存位置", saveSettings.save_location);
|
||
setWidgetValue(node, "图层拆分", layerDecomposition);
|
||
|
||
try {
|
||
setStatus(node, "", "busy");
|
||
batchId = createBatchId();
|
||
saveNode = options?.targetSaveNode
|
||
? bindSaveNodeToBatch(node, options.targetSaveNode, batchId)
|
||
: acquireSaveNodeForBatch(node, batchId);
|
||
if (layerDecomposition) {
|
||
layerSaveNode = acquireLayerSaveNodeForBatch(node, saveNode);
|
||
}
|
||
const fullTaskPlan = panelGenerationTasks(
|
||
node,
|
||
retrySlotIndex ? node._o1igPrompt.value : prompt,
|
||
retrySlotIndex ? normalizeImageCount(node._o1igCount.value, node._o1igModel.value) : requestedImageCount,
|
||
);
|
||
if (!fullTaskPlan.length && !storedReferenceOverride.length) {
|
||
throw new Error("批量组合为空,请检查目标图");
|
||
}
|
||
if (fullTaskPlan.length > 1000) throw new Error("单次生成任务最多支持 1000 个");
|
||
const retryTask = retrySlotIndex
|
||
? storedReferenceOverride.length
|
||
? { prompt, references: storedReferenceOverride }
|
||
: fullTaskPlan[retrySlotIndex - 1]
|
||
: null;
|
||
if (retrySlotIndex && !retryTask) throw new Error("无法恢复该失败任务的原始组合");
|
||
const submittedTasks = retryTask ? [retryTask] : fullTaskPlan;
|
||
const taskPrompts = submittedTasks.map((task) => task.prompt);
|
||
if (retrySlotIndex) {
|
||
saveNode.properties.o1keyRetrySlotIndex = retrySlotIndex;
|
||
saveNode._o1igsSlots = normalizeSaveSlots(saveNode._o1igsSlots).map((slot) => (
|
||
slot.index === retrySlotIndex
|
||
? { ...slot, state: "pending", error: "", image: null }
|
||
: slot
|
||
));
|
||
persistSaveSlots(saveNode);
|
||
syncSaveSlotsWidget(saveNode);
|
||
} else {
|
||
delete saveNode.properties.o1keyRetrySlotIndex;
|
||
initializeSaveSlots(saveNode, submittedTasks);
|
||
}
|
||
beginGenerationBatch(node, saveNode, batchId);
|
||
beginLayerGenerationBatch(node, layerSaveNode, batchId);
|
||
parallelBatches.set(batchId, {
|
||
source: node,
|
||
saveNode,
|
||
generatorNodeId: node.id,
|
||
saveNodeId: saveNode.id,
|
||
layerSaveNode,
|
||
layerSaveNodeId: layerSaveNode?.id,
|
||
layerDecomposition,
|
||
retrySlotIndex,
|
||
});
|
||
updateNativeQueueJob({
|
||
batch_id: batchId,
|
||
generator_node_id: node.id,
|
||
save_node_id: saveNode.id,
|
||
state: "queued",
|
||
total_count: taskPrompts.length,
|
||
});
|
||
const jobPayload = {
|
||
batch_id: batchId,
|
||
generator_node_id: node.id,
|
||
save_node_id: saveNode.id,
|
||
prompt: retryTask?.prompt || prompt,
|
||
model: node._o1igModel.value,
|
||
model_route: node._o1igRoute.value,
|
||
thinking_level: node._o1igThinking.value,
|
||
resolution: node._o1igResolution.value,
|
||
aspect_ratio: node._o1igRatio.value,
|
||
image_count: retryTask ? 1 : Number(requestedImageCount),
|
||
seed: generatorSeed(node),
|
||
quality: node._o1igQuality.value,
|
||
resize_mode: node._o1igResize.value,
|
||
filename_prefix: saveSettings.filename_prefix,
|
||
save_format: saveSettings.format,
|
||
save_location: saveSettings.save_location,
|
||
naming_rule: saveSettings.naming_rule,
|
||
references: (retryTask?.references || node._o1igReferences).map((item) => ({
|
||
name: String(item.name),
|
||
subfolder: String(item.subfolder || ""),
|
||
type: "input",
|
||
})),
|
||
mask: isGptImageModel(node._o1igModel.value) && node._o1igMask
|
||
? {
|
||
name: String(node._o1igMask.name),
|
||
subfolder: String(node._o1igMask.subfolder || ""),
|
||
type: "input",
|
||
}
|
||
: null,
|
||
batch_enabled: retryTask ? false : Boolean(node._o1igBatchEnabled),
|
||
batch_mode: batchModeOf(node),
|
||
model_references: retryTask || batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES
|
||
? []
|
||
: node._o1igModelReferences.map((item) => ({
|
||
name: String(item.name),
|
||
subfolder: String(item.subfolder || ""),
|
||
type: "input",
|
||
})),
|
||
};
|
||
if (isGptImageModel(node._o1igModel.value)) {
|
||
jobPayload.output_format = node._o1igOutputFormat.value;
|
||
jobPayload.background = node._o1igBackground.value;
|
||
if (MODEL_CAPABILITIES[node._o1igModel.value]?.complexity) {
|
||
jobPayload.complexity = normalizeGptComplexityLabel(node._o1igComplexity.value);
|
||
}
|
||
if (node._o1igOutputFormat.value === "gif") {
|
||
jobPayload.frame_count = Number(node._o1igFrameCount?.value) || 9;
|
||
jobPayload.frame_duration_ms = Number(node._o1igFrameDuration?.value) || 200;
|
||
}
|
||
} else if (node._o1igModel.value === "Seedream 5.0 Pro") {
|
||
jobPayload.output_format = node._o1igOutputFormat.value;
|
||
if (layerDecomposition) jobPayload.layer_decomposition = true;
|
||
}
|
||
const response = await api.fetchApi("/o1key/image/jobs", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(jobPayload),
|
||
});
|
||
const result = await response.json().catch(() => ({}));
|
||
if (!response.ok) throw new Error(result?.error || `提交任务失败(HTTP ${response.status})`);
|
||
handleParallelImageJob({ ...result, generator_node_id: node.id, save_node_id: saveNode.id });
|
||
monitorParallelBatch(batchId);
|
||
updateGeneratorActivity(node);
|
||
} catch (error) {
|
||
const message = formatImageGenerationError(error?.message || error);
|
||
let recovered = false;
|
||
if (saveNode && batchId) {
|
||
try {
|
||
const status = await fetchParallelBatchStatus(batchId);
|
||
if (status.detail) {
|
||
recovered = true;
|
||
handleParallelImageJob(status.detail);
|
||
monitorParallelBatch(batchId);
|
||
}
|
||
} catch {
|
||
// The POST response may have been lost after the server accepted
|
||
// the job. Retain its exact node binding and confirm by polling.
|
||
recovered = true;
|
||
setSaveBusy(saveNode, true, "queued");
|
||
monitorParallelBatch(batchId);
|
||
}
|
||
}
|
||
if (recovered) {
|
||
toast("warn", "正在确认任务状态", "连接短暂中断,结果节点会继续自动接收该批次。");
|
||
return;
|
||
}
|
||
if (saveNode) {
|
||
updateNativeQueueJob({
|
||
batch_id: batchId,
|
||
generator_node_id: node.id,
|
||
save_node_id: saveNode.id,
|
||
state: "failed",
|
||
error: message,
|
||
}, { forceState: "failed", error: message });
|
||
updateSaveSlotsForState(saveNode, {
|
||
state: "failed",
|
||
error: message,
|
||
}, retrySlotIndex);
|
||
finishLayerGenerationBatch(layerSaveNode, batchId);
|
||
finishGenerationBatch(saveNode, message, batchId);
|
||
}
|
||
else setStatus(node, message, "error");
|
||
toast("error", "生成失败", message);
|
||
}
|
||
}
|
||
|
||
function buildPanel(node) {
|
||
if (node._o1igPanel) {
|
||
installStandardQueueWidget(node);
|
||
return;
|
||
}
|
||
injectStyles();
|
||
hideBackendWidgets(node);
|
||
installStandardQueueWidget(node);
|
||
node._o1igReferences = parseReferences(findWidget(node, "参考图清单")?.value);
|
||
node._o1igModelReferences = parseReferences(findWidget(node, "模特图清单")?.value);
|
||
node._o1igMask = parseMask(findWidget(node, "蒙版清单")?.value);
|
||
node._o1igPending = [];
|
||
node._o1igModelPending = [];
|
||
node._o1igMaskPending = false;
|
||
const rawBatchEnabled = findWidget(node, "批量出图")?.value;
|
||
node._o1igBatchEnabled = rawBatchEnabled === true
|
||
|| String(rawBatchEnabled || "").toLowerCase() === "true"
|
||
|| rawBatchEnabled === "开启";
|
||
const panel = document.createElement("div");
|
||
panel.className = "o1ig-panel";
|
||
panel.addEventListener("pointerdown", (event) => {
|
||
if (openDropdown && !openDropdown.contains(event.target)) closeDropdown();
|
||
event.stopPropagation();
|
||
});
|
||
|
||
const refs = document.createElement("div");
|
||
refs.className = "o1ig-refs";
|
||
refs.addEventListener("wheel", (event) => event.stopPropagation());
|
||
bindImageFileDropTarget(node, refs);
|
||
// The trailing "+ 添加…" card is the only upload entry point; the header keeps
|
||
// 清空参考图 + 画布取图, so the picker input lives beside the track instead of inside a button.
|
||
const fileInput = createReferenceFileInput(node, "references");
|
||
const canvasPick = document.createElement("button");
|
||
canvasPick.type = "button";
|
||
canvasPick.className = "o1ig-add o1ig-canvas-pick";
|
||
canvasPick.title = "从画布中选择已处理的图片";
|
||
const canvasPickIcon = document.createElement("b");
|
||
canvasPickIcon.textContent = "▣";
|
||
const canvasPickLabel = document.createElement("span");
|
||
canvasPickLabel.textContent = "画布取图";
|
||
canvasPick.append(canvasPickIcon, canvasPickLabel);
|
||
canvasPick.addEventListener("click", () => openCanvasImagePicker(node));
|
||
|
||
const referenceHeader = document.createElement("div");
|
||
referenceHeader.className = "o1ig-asset-header";
|
||
const referenceTitle = document.createElement("strong");
|
||
referenceTitle.textContent = "素材图";
|
||
const referenceHint = document.createElement("span");
|
||
referenceHint.className = "o1ig-asset-hint";
|
||
referenceHint.textContent = "";
|
||
const referenceMeta = document.createElement("div");
|
||
referenceMeta.className = "o1ig-asset-meta";
|
||
referenceMeta.append(referenceTitle, referenceHint);
|
||
const referenceActions = document.createElement("div");
|
||
const clearReferences = document.createElement("button");
|
||
clearReferences.type = "button";
|
||
clearReferences.className = "o1ig-clear-refs";
|
||
clearReferences.title = "清空全部参考图与目标图";
|
||
const clearReferencesLabel = document.createElement("span");
|
||
clearReferencesLabel.textContent = "清空参考图";
|
||
clearReferences.append(clearReferencesLabel);
|
||
clearReferences.addEventListener("click", () => clearAllReferences(node));
|
||
referenceActions.className = "o1ig-asset-actions";
|
||
referenceActions.append(clearReferences, canvasPick);
|
||
referenceHeader.append(referenceMeta, referenceActions);
|
||
const referenceAssets = document.createElement("div");
|
||
referenceAssets.className = "o1ig-assets";
|
||
const replaceInput = document.createElement("input");
|
||
replaceInput.type = "file";
|
||
replaceInput.accept = IMAGE_FILE_ACCEPT;
|
||
replaceInput.hidden = true;
|
||
replaceInput.addEventListener("change", async () => {
|
||
const target = node._o1igReplaceTarget;
|
||
const file = replaceInput.files?.[0];
|
||
node._o1igReplaceTarget = null;
|
||
replaceInput.value = "";
|
||
if (target && file) await replaceReference(node, target.role, target.original, file);
|
||
});
|
||
referenceAssets.append(referenceHeader, refs, replaceInput, fileInput);
|
||
|
||
const modelRefs = document.createElement("div");
|
||
modelRefs.className = "o1ig-refs";
|
||
modelRefs.addEventListener("wheel", (event) => event.stopPropagation());
|
||
bindImageFileDropTarget(node, modelRefs, "models");
|
||
const modelFileInput = createReferenceFileInput(node, "models");
|
||
const modelCanvasPick = document.createElement("button");
|
||
modelCanvasPick.type = "button";
|
||
modelCanvasPick.className = "o1ig-add o1ig-canvas-pick";
|
||
modelCanvasPick.title = "从画布中选择已处理的目标图";
|
||
const modelCanvasPickIcon = document.createElement("b");
|
||
modelCanvasPickIcon.textContent = "▣";
|
||
const modelCanvasPickLabel = document.createElement("span");
|
||
modelCanvasPickLabel.textContent = "画布取图";
|
||
modelCanvasPick.append(modelCanvasPickIcon, modelCanvasPickLabel);
|
||
modelCanvasPick.addEventListener("click", () => openCanvasImagePicker(node, "models"));
|
||
const modelHeader = document.createElement("div");
|
||
modelHeader.className = "o1ig-asset-header visible";
|
||
const modelTitle = document.createElement("strong");
|
||
modelTitle.textContent = "目标图";
|
||
const modelHint = document.createElement("span");
|
||
modelHint.className = "o1ig-asset-hint";
|
||
modelHint.textContent = "";
|
||
const modelMeta = document.createElement("div");
|
||
modelMeta.className = "o1ig-asset-meta";
|
||
modelMeta.append(modelTitle, modelHint);
|
||
const modelActions = document.createElement("div");
|
||
const clearModelReferences = document.createElement("button");
|
||
clearModelReferences.type = "button";
|
||
clearModelReferences.className = "o1ig-clear-refs";
|
||
clearModelReferences.title = "清空全部素材图与目标图";
|
||
const clearModelReferencesLabel = document.createElement("span");
|
||
clearModelReferencesLabel.textContent = "清空";
|
||
clearModelReferences.append(clearModelReferencesLabel);
|
||
clearModelReferences.addEventListener("click", () => clearAllReferences(node));
|
||
modelActions.className = "o1ig-asset-actions";
|
||
modelActions.append(clearModelReferences, modelCanvasPick);
|
||
modelHeader.append(modelMeta, modelActions);
|
||
const modelAssets = document.createElement("div");
|
||
modelAssets.className = "o1ig-assets o1ig-model-assets";
|
||
modelAssets.append(modelHeader, modelRefs, modelFileInput);
|
||
|
||
const batchToggle = document.createElement("button");
|
||
batchToggle.type = "button";
|
||
batchToggle.className = "o1ig-batch-toggle";
|
||
const batchToggleLabel = document.createElement("span");
|
||
batchToggleLabel.textContent = "批量出图";
|
||
const batchSwitch = document.createElement("span");
|
||
batchSwitch.className = "o1ig-batch-switch";
|
||
batchToggle.append(batchToggleLabel, batchSwitch);
|
||
const batchMode = makeSelect(
|
||
BATCH_MODE_OPTIONS,
|
||
normalizeBatchMode(findWidget(node, "批量模式")?.value),
|
||
"批量模式",
|
||
);
|
||
const batchModeWrap = document.createElement("div");
|
||
batchModeWrap.className = "o1ig-batch-mode";
|
||
batchModeWrap.append(batchMode);
|
||
const batchBar = document.createElement("div");
|
||
batchBar.className = "o1ig-batch-bar";
|
||
batchBar.append(batchToggle, batchModeWrap);
|
||
const batchSummary = document.createElement("div");
|
||
batchSummary.className = "o1ig-batch-summary";
|
||
batchSummary.title = "预计出图张数 = 组合数 × 每组张数 × 提示词条数,实际以队列结果为准";
|
||
const batchSummaryDetail = document.createElement("span");
|
||
batchSummaryDetail.className = "o1ig-batch-summary-detail";
|
||
const batchSummaryTotal = document.createElement("span");
|
||
batchSummaryTotal.className = "o1ig-batch-summary-total";
|
||
batchSummary.append(batchSummaryDetail, batchSummaryTotal);
|
||
|
||
const prompt = document.createElement("textarea");
|
||
prompt.className = "o1ig-prompt";
|
||
prompt.placeholder = PROMPT_PLACEHOLDER;
|
||
prompt.value = findWidget(node, "prompt")?.value || "";
|
||
prompt.addEventListener("wheel", (event) => event.stopPropagation());
|
||
const promptOptimize = document.createElement("button");
|
||
promptOptimize.type = "button";
|
||
promptOptimize.className = "o1ig-prompt-optimize";
|
||
promptOptimize.title = "AI帮写";
|
||
promptOptimize.setAttribute("aria-label", "AI帮写");
|
||
const promptOptimizeIcon = document.createElement("span");
|
||
promptOptimizeIcon.className = "o1ig-prompt-optimize-icon";
|
||
promptOptimizeIcon.textContent = "✨";
|
||
promptOptimizeIcon.setAttribute("aria-hidden", "true");
|
||
const promptOptimizeLabel = document.createElement("span");
|
||
promptOptimizeLabel.textContent = "AI帮写";
|
||
promptOptimize.append(promptOptimizeIcon, promptOptimizeLabel);
|
||
const promptOptimizeStatus = document.createElement("div");
|
||
promptOptimizeStatus.className = "o1ig-prompt-optimize-status";
|
||
promptOptimizeStatus.setAttribute("role", "status");
|
||
promptOptimizeStatus.setAttribute("aria-live", "polite");
|
||
const promptWrap = document.createElement("div");
|
||
promptWrap.className = "o1ig-prompt-wrap";
|
||
// Flexible child: report its CSS basis when the panel is measured for the node height.
|
||
promptWrap.dataset.o1igHeight = String(PROMPT_DEFAULT_HEIGHT);
|
||
promptWrap.append(prompt, promptOptimizeStatus, promptOptimize);
|
||
|
||
const toolbar = document.createElement("div");
|
||
toolbar.className = "o1ig-toolbar";
|
||
const model = makeSelect(
|
||
MODEL_OPTIONS,
|
||
normalizeUnifiedModel(findWidget(node, "模型")?.value || "Nano Banana 2.1"),
|
||
"模型",
|
||
);
|
||
const resolution = makeSelect(ALL_RESOLUTIONS, findWidget(node, "分辨率")?.value || "智能", "分辨率");
|
||
const ratio = makeSelect(ALL_RATIOS, findWidget(node, "宽高比")?.value || "智能", "宽高比");
|
||
const ratioField = makeAdvancedField("宽高比", ratio);
|
||
const count = makeImageCountSelect(findWidget(node, "生图数量")?.value, model.value);
|
||
const countField = makeAdvancedField("生图数量", count);
|
||
const countLabel = countField.children?.[0] || null;
|
||
const route = makeSelect(ROUTES, findWidget(node, "模型线路")?.value || "畅速");
|
||
const thinking = makeSelect(THINKING_LEVEL_OPTIONS, findWidget(node, "思考等级")?.value || "高");
|
||
const thinkingField = makeAdvancedField("思考等级", thinking);
|
||
const layerDecomposition = makeSelect(
|
||
["关闭", "开启"],
|
||
findWidget(node, "图层拆分")?.value === true ? "开启" : "关闭",
|
||
"图层拆分",
|
||
);
|
||
const layerDecompositionField = makeAdvancedField("图层拆分", layerDecomposition);
|
||
const quality = makeSelect(
|
||
/^gpt-image-2\.[56]-/.test(model.value) ? GPT_25_QUALITIES : GPT_QUALITIES,
|
||
findWidget(node, "质量")?.value || "自动",
|
||
"质量",
|
||
);
|
||
const qualityField = makeAdvancedField("质量", quality);
|
||
const complexity = makeSelect(
|
||
GPT_COMPLEXITY_OPTIONS,
|
||
normalizeGptComplexityLabel(findWidget(node, "复杂度")?.value),
|
||
"复杂度",
|
||
);
|
||
const complexityField = makeAdvancedField("复杂度", complexity);
|
||
const frameCount = document.createElement("input");
|
||
frameCount.className = "o1ig-control";
|
||
frameCount.type = "number";
|
||
frameCount.min = "2";
|
||
frameCount.max = "64";
|
||
frameCount.step = "1";
|
||
frameCount.value = String(findWidget(node, "帧数")?.value ?? 9);
|
||
const frameCountField = makeAdvancedField("GIF帧数", frameCount);
|
||
const frameDuration = document.createElement("input");
|
||
frameDuration.className = "o1ig-control";
|
||
frameDuration.type = "number";
|
||
frameDuration.min = "20";
|
||
frameDuration.max = "2000";
|
||
frameDuration.step = "10";
|
||
frameDuration.value = String(findWidget(node, "帧时长ms")?.value ?? 200);
|
||
const frameDurationField = makeAdvancedField("GIF帧时长ms", frameDuration);
|
||
const background = makeSelect(
|
||
GPT_BACKGROUNDS,
|
||
findWidget(node, "背景")?.value || "auto",
|
||
"背景",
|
||
);
|
||
const backgroundField = makeAdvancedField("背景", background);
|
||
const outputFormat = makeSelect(
|
||
GPT_OUTPUT_FORMATS,
|
||
findWidget(node, "输出格式")?.value || "jpeg",
|
||
"输出格式",
|
||
);
|
||
const outputFormatField = makeAdvancedField("输出格式", outputFormat);
|
||
const resize = makeSelect(
|
||
RESIZE_OPTIONS,
|
||
findWidget(node, "缩放图片")?.value || "智能缩放",
|
||
"缩放图片",
|
||
);
|
||
const resizeWarning = document.createElement("div");
|
||
resizeWarning.className = "o1ig-resize-warning";
|
||
resizeWarning.textContent = "可能发生像素偏移";
|
||
const resizeField = makeAdvancedField("缩放图片", resize);
|
||
resizeField.append(resizeWarning);
|
||
const namingRule = makeSelect(
|
||
SAVE_NAMING_RULES,
|
||
findWidget(node, "命名规则")?.value || "自定义前缀",
|
||
"命名规则",
|
||
);
|
||
const namingRuleField = makeAdvancedField("命名规则", namingRule);
|
||
const filenamePrefix = document.createElement("input");
|
||
filenamePrefix.className = "o1ig-control";
|
||
filenamePrefix.type = "text";
|
||
filenamePrefix.maxLength = 512;
|
||
filenamePrefix.value = findWidget(node, "filename_prefix")?.value || "o1key";
|
||
filenamePrefix.placeholder = "o1key";
|
||
const filenamePrefixField = makeAdvancedField("文件名前缀", filenamePrefix);
|
||
filenamePrefixField.classList.add("o1ig-field-wide");
|
||
const saveFormat = makeSelect(
|
||
SAVE_FORMATS,
|
||
findWidget(node, "格式")?.value || "原始",
|
||
"格式",
|
||
);
|
||
const saveFormatField = makeAdvancedField("格式", saveFormat);
|
||
const saveLocation = document.createElement("input");
|
||
saveLocation.className = "o1ig-control";
|
||
saveLocation.type = "text";
|
||
saveLocation.value = findWidget(node, "保存位置")?.value || "";
|
||
saveLocation.placeholder = "留空为 output;或填写 D:/图片";
|
||
saveLocation.title = "相对路径保存到 output 内;绝对路径可保存到任意磁盘目录";
|
||
const saveLocationField = makeAdvancedField("保存位置", saveLocation);
|
||
saveLocationField.classList.add("o1ig-field-wide");
|
||
const maskFileInput = document.createElement("input");
|
||
maskFileInput.type = "file";
|
||
maskFileInput.accept = "image/png,image/jpeg,image/webp,image/gif,image/bmp";
|
||
maskFileInput.hidden = true;
|
||
const maskButton = document.createElement("button");
|
||
maskButton.type = "button";
|
||
maskButton.className = "o1ig-control o1ig-mask-button";
|
||
const maskClear = document.createElement("button");
|
||
maskClear.type = "button";
|
||
maskClear.className = "o1ig-control o1ig-mask-clear";
|
||
maskClear.textContent = "×";
|
||
maskClear.title = "移除蒙版";
|
||
const maskWrap = document.createElement("div");
|
||
maskWrap.className = "o1ig-mask-wrap";
|
||
maskWrap.append(maskButton, maskClear, maskFileInput);
|
||
const maskField = makeAdvancedField("蒙版", maskWrap);
|
||
toolbar.append(
|
||
makeInlineLabelField("模型", model),
|
||
makeAdvancedField("模型线路", route),
|
||
makeAdvancedField("分辨率", resolution),
|
||
ratioField,
|
||
countField,
|
||
thinkingField,
|
||
layerDecompositionField,
|
||
qualityField,
|
||
complexityField,
|
||
frameCountField,
|
||
frameDurationField,
|
||
backgroundField,
|
||
outputFormatField,
|
||
resizeField,
|
||
maskField,
|
||
namingRuleField,
|
||
saveFormatField,
|
||
filenamePrefixField,
|
||
saveLocationField,
|
||
);
|
||
if (USE_NATIVE_LITEGRAPH_PARAMETERS) {
|
||
toolbar.style.display = "none";
|
||
batchBar.style.display = "none";
|
||
toolbar.removeChild?.(maskField);
|
||
}
|
||
|
||
const generate = document.createElement("button");
|
||
generate.type = "button";
|
||
generate.className = "o1ig-generate";
|
||
generate.textContent = "开始生成";
|
||
const status = document.createElement("div");
|
||
status.className = "o1ig-status";
|
||
const actions = document.createElement("div");
|
||
actions.className = "o1ig-actions";
|
||
actions.addEventListener("pointerdown", (event) => {
|
||
if (openDropdown && !openDropdown.contains(event.target)) closeDropdown();
|
||
event.stopPropagation();
|
||
});
|
||
actions.append(status, generate);
|
||
|
||
panel.append(
|
||
batchBar,
|
||
referenceAssets,
|
||
modelAssets,
|
||
batchSummary,
|
||
promptWrap,
|
||
...(USE_NATIVE_LITEGRAPH_PARAMETERS ? [maskField] : []),
|
||
toolbar,
|
||
);
|
||
const panelWidget = node.addDOMWidget(PANEL_WIDGET_NAME, "div", panel, {
|
||
serialize: false,
|
||
hideOnZoom: false,
|
||
getMinHeight: () => generatorPanelMinHeight(node),
|
||
});
|
||
movePanelWidgetToFront(node, panelWidget);
|
||
// The action bar owns the last row of the node: it sits under every native parameter row.
|
||
const actionsWidget = node.addDOMWidget(ACTIONS_WIDGET_NAME, "div", actions, {
|
||
serialize: false,
|
||
hideOnZoom: false,
|
||
getMinHeight: () => actionsWidgetHeight(node),
|
||
getMaxHeight: () => actionsWidgetHeight(node),
|
||
});
|
||
node._o1igActions = actions;
|
||
node._o1igActionsWidget = actionsWidget;
|
||
moveWidgetToEnd(node, actionsWidget);
|
||
// LiteGraph restores widgets_values by position, so the DOM widgets must stay out of that
|
||
// list; otherwise every backend value after them shifts by one slot.
|
||
for (const widget of [panelWidget, actionsWidget]) {
|
||
widget.serialize = false;
|
||
widget.options ??= {};
|
||
widget.options.serialize = false;
|
||
}
|
||
|
||
Object.assign(node, {
|
||
_o1igPanel: panel,
|
||
_o1igPanelWidget: panelWidget,
|
||
_o1igActions: actions,
|
||
_o1igActionsWidget: actionsWidget,
|
||
_o1igToolbar: toolbar,
|
||
_o1igRefs: refs,
|
||
_o1igReplaceInput: replaceInput,
|
||
_o1igReferenceInput: fileInput,
|
||
_o1igCanvasPick: canvasPick,
|
||
_o1igClearReferences: clearReferences,
|
||
_o1igReferenceHeader: referenceHeader,
|
||
_o1igReferenceTitle: referenceTitle,
|
||
_o1igReferenceHint: referenceHint,
|
||
_o1igModelRefs: modelRefs,
|
||
_o1igModelInput: modelFileInput,
|
||
_o1igModelCanvasPick: modelCanvasPick,
|
||
_o1igClearModelReferences: clearModelReferences,
|
||
_o1igModelAssets: modelAssets,
|
||
_o1igModelHint: modelHint,
|
||
_o1igBatchToggle: batchToggle,
|
||
_o1igBatchMode: batchMode,
|
||
_o1igBatchModeWrap: batchModeWrap,
|
||
_o1igBatchSummary: batchSummary,
|
||
_o1igBatchSummaryDetail: batchSummaryDetail,
|
||
_o1igBatchSummaryTotal: batchSummaryTotal,
|
||
_o1igBatchBar: batchBar,
|
||
_o1igModel: model,
|
||
_o1igResolution: resolution,
|
||
_o1igRatio: ratio,
|
||
_o1igRatioField: ratioField,
|
||
_o1igCount: count,
|
||
_o1igCountField: countField,
|
||
_o1igCountLabel: countLabel,
|
||
_o1igRoute: route,
|
||
_o1igThinking: thinking,
|
||
_o1igThinkingField: thinkingField,
|
||
_o1igLayerDecomposition: layerDecomposition,
|
||
_o1igLayerDecompositionField: layerDecompositionField,
|
||
_o1igQuality: quality,
|
||
_o1igQualityField: qualityField,
|
||
_o1igComplexity: complexity,
|
||
_o1igComplexityField: complexityField,
|
||
_o1igFrameCount: frameCount,
|
||
_o1igFrameCountField: frameCountField,
|
||
_o1igFrameDuration: frameDuration,
|
||
_o1igFrameDurationField: frameDurationField,
|
||
_o1igBackground: background,
|
||
_o1igBackgroundField: backgroundField,
|
||
_o1igOutputFormat: outputFormat,
|
||
_o1igOutputFormatField: outputFormatField,
|
||
_o1igResize: resize,
|
||
_o1igResizeField: resizeField,
|
||
_o1igResizeWarning: resizeWarning,
|
||
_o1igNamingRule: namingRule,
|
||
_o1igNamingRuleField: namingRuleField,
|
||
_o1igFilenamePrefix: filenamePrefix,
|
||
_o1igFilenamePrefixField: filenamePrefixField,
|
||
_o1igSaveFormat: saveFormat,
|
||
_o1igSaveFormatField: saveFormatField,
|
||
_o1igSaveLocation: saveLocation,
|
||
_o1igSaveLocationField: saveLocationField,
|
||
_o1igMaskButton: maskButton,
|
||
_o1igMaskClear: maskClear,
|
||
_o1igMaskField: maskField,
|
||
_o1igPrompt: prompt,
|
||
_o1igPromptOptimize: promptOptimize,
|
||
_o1igPromptOptimizeStatus: promptOptimizeStatus,
|
||
_o1igGenerate: generate,
|
||
_o1igStatus: status,
|
||
});
|
||
installNativeParameterBridge(node);
|
||
|
||
model.addEventListener("change", () => syncModelOptions(node));
|
||
layerDecomposition.addEventListener("change", () => syncModelOptions(node));
|
||
batchToggle.addEventListener("click", () => {
|
||
node._o1igBatchEnabled = !node._o1igBatchEnabled;
|
||
syncBatchLayout(node);
|
||
});
|
||
batchMode.addEventListener("change", () => {
|
||
setWidgetValue(node, "批量模式", batchMode.value);
|
||
syncBatchLayout(node);
|
||
});
|
||
resolution.addEventListener("change", () => setWidgetValue(node, "分辨率", resolution.value));
|
||
ratio.addEventListener("change", () => setWidgetValue(node, "宽高比", ratio.value));
|
||
count.addEventListener("change", () => {
|
||
setWidgetValue(node, "生图数量", normalizeImageCount(count.value, model.value));
|
||
updateBatchSummary(node);
|
||
});
|
||
route.addEventListener("change", () => setWidgetValue(node, "模型线路", route.value));
|
||
thinking.addEventListener("change", () => setWidgetValue(node, "思考等级", thinking.value));
|
||
quality.addEventListener("change", () => setWidgetValue(node, "质量", quality.value));
|
||
complexity.addEventListener("change", () => {
|
||
complexity.value = normalizeGptComplexityLabel(complexity.value);
|
||
setWidgetValue(node, "复杂度", complexity.value);
|
||
});
|
||
frameCount.addEventListener("change", () => {
|
||
setWidgetValue(node, "帧数", Number(frameCount.value) || 9);
|
||
syncGptOutputOptions(node);
|
||
});
|
||
frameDuration.addEventListener("change", () => {
|
||
setWidgetValue(node, "帧时长ms", Number(frameDuration.value) || 200);
|
||
syncGptOutputOptions(node);
|
||
});
|
||
background.addEventListener("change", () => syncGptOutputOptions(node));
|
||
outputFormat.addEventListener("change", () => {
|
||
node._o1igOutputTouched = true;
|
||
setWidgetValue(node, "输出格式", outputFormat.value);
|
||
syncGptOutputOptions(node);
|
||
});
|
||
resize.addEventListener("change", () => {
|
||
node._o1igResizeTouched = true;
|
||
setWidgetValue(node, "缩放图片", resize.value);
|
||
syncResizeWarning(node);
|
||
});
|
||
namingRule.addEventListener("change", () => {
|
||
setWidgetValue(node, "命名规则", namingRule.value);
|
||
syncGeneratorSaveControls(node);
|
||
fitNode(node);
|
||
});
|
||
filenamePrefix.addEventListener("change", () => {
|
||
filenamePrefix.value = filenamePrefix.value.trim() || "o1key";
|
||
setWidgetValue(node, "filename_prefix", filenamePrefix.value);
|
||
});
|
||
saveFormat.addEventListener("change", () => setWidgetValue(node, "格式", saveFormat.value));
|
||
saveLocation.addEventListener("change", () => {
|
||
saveLocation.value = saveLocation.value.trim();
|
||
setWidgetValue(node, "保存位置", saveLocation.value);
|
||
});
|
||
maskButton.addEventListener("click", () => maskFileInput.click());
|
||
maskFileInput.addEventListener("change", async () => {
|
||
const file = maskFileInput.files?.[0];
|
||
maskFileInput.value = "";
|
||
if (!file) return;
|
||
try {
|
||
node._o1igMaskPending = true;
|
||
setStatus(node, "上传中…", "busy");
|
||
node._o1igMask = await enqueueImageUpload(file);
|
||
setWidgetValue(node, "蒙版清单", JSON.stringify(node._o1igMask));
|
||
syncMaskControl(node);
|
||
setStatus(node, "", "");
|
||
} catch (error) {
|
||
const message = error?.message || String(error);
|
||
setStatus(node, message, "error");
|
||
toast("error", "蒙版上传失败", message);
|
||
} finally {
|
||
node._o1igMaskPending = false;
|
||
}
|
||
});
|
||
maskClear.addEventListener("click", () => {
|
||
node._o1igMask = null;
|
||
setWidgetValue(node, "蒙版清单", "{}");
|
||
syncMaskControl(node);
|
||
});
|
||
prompt.addEventListener("input", () => {
|
||
setWidgetValue(node, "prompt", prompt.value);
|
||
updateBatchSummary(node);
|
||
if (!node._o1igOptimizing) setPromptOptimizeStatus(node);
|
||
});
|
||
promptOptimize.addEventListener("click", () => optimizePrompt(node));
|
||
generate.addEventListener("click", () => queueGeneration(node));
|
||
|
||
renderReferences(node);
|
||
syncMaskControl(node);
|
||
syncModelOptions(node);
|
||
syncResizeWarning(node);
|
||
syncBatchLayout(node);
|
||
syncNativeWidgetOptions(node);
|
||
fitNode(node);
|
||
// Node creation runs before LiteGraph restores widgets_values, so the visual reorder
|
||
// waits for the next frame to keep the positional restore aligned with the schema.
|
||
requestAnimationFrame(() => applyNativeParameterOrder(node));
|
||
requestAnimationFrame(() => {
|
||
node._o1igOutputsReady = true;
|
||
syncGeneratorOutputVisibility(node);
|
||
});
|
||
}
|
||
|
||
function buildSavePanel(node) {
|
||
if (node._o1igsPanelReady) return;
|
||
injectStyles();
|
||
Object.assign(node, {
|
||
_o1igsPanelReady: true,
|
||
_o1igsLastResults: node._o1igsLastResults || [],
|
||
_o1igsSlots: node._o1igsSlots || storedSaveSlots(node),
|
||
_o1igsBusy: false,
|
||
_o1igsProgress: 0,
|
||
});
|
||
syncSaveProgressOverlay(node);
|
||
syncSaveSlotsWidget(node);
|
||
renderSaveResults(node, node._o1igsLastResults, { persist: false });
|
||
}
|
||
|
||
function installNativeMinimumSize(nodeType, minimum) {
|
||
const originalComputeSize = nodeType.prototype.computeSize;
|
||
nodeType.prototype.computeSize = function (size) {
|
||
const computed = originalComputeSize?.call(this, size) || size || [0, 0];
|
||
// Width stays clamped for the field layout; height follows the stacked widgets so the
|
||
// node can shrink to its content instead of keeping a fixed blank strip at the bottom.
|
||
computed[0] = Math.max(Number(computed[0]) || 0, minimum[0]);
|
||
computed[1] = Math.max(Number(computed[1]) || 0, GENERATOR_COMPACT_MIN_HEIGHT);
|
||
return computed;
|
||
};
|
||
}
|
||
|
||
function restorePanelFromWidgets(node) {
|
||
if (!node._o1igPanel) return;
|
||
hideBackendWidgets(node);
|
||
node._o1igReferences = parseReferences(findWidget(node, "参考图清单")?.value);
|
||
node._o1igModelReferences = parseReferences(findWidget(node, "模特图清单")?.value);
|
||
node._o1igMask = parseMask(findWidget(node, "蒙版清单")?.value);
|
||
const rawBatchEnabled = findWidget(node, "批量出图")?.value;
|
||
node._o1igBatchEnabled = rawBatchEnabled === true
|
||
|| String(rawBatchEnabled || "").toLowerCase() === "true"
|
||
|| rawBatchEnabled === "开启";
|
||
node._o1igBatchMode.value = normalizeBatchMode(
|
||
findWidget(node, "批量模式")?.value || BATCH_MODE_GROUP_TO_TARGETS,
|
||
);
|
||
node._o1igModel.value = normalizeUnifiedModel(findWidget(node, "模型")?.value || "Nano Banana 2.1");
|
||
node._o1igRoute.value = findWidget(node, "模型线路")?.value || "畅速";
|
||
node._o1igThinking.value = findWidget(node, "思考等级")?.value || "高";
|
||
node._o1igQuality.value = findWidget(node, "质量")?.value || "自动";
|
||
node._o1igComplexity.value = normalizeGptComplexityLabel(findWidget(node, "复杂度")?.value);
|
||
if (node._o1igFrameCount) node._o1igFrameCount.value = String(findWidget(node, "帧数")?.value ?? 9);
|
||
if (node._o1igFrameDuration) node._o1igFrameDuration.value = String(findWidget(node, "帧时长ms")?.value ?? 200);
|
||
node._o1igOutputFormat.value = findWidget(node, "输出格式")?.value || "jpeg";
|
||
node._o1igBackground.value = findWidget(node, "背景")?.value || "auto";
|
||
node._o1igResize.value = findWidget(node, "缩放图片")?.value || "智能缩放";
|
||
node._o1igNamingRule.value = findWidget(node, "命名规则")?.value || "自定义前缀";
|
||
node._o1igFilenamePrefix.value = findWidget(node, "filename_prefix")?.value || "o1key";
|
||
node._o1igSaveFormat.value = findWidget(node, "格式")?.value || "原始";
|
||
node._o1igSaveLocation.value = findWidget(node, "保存位置")?.value || "";
|
||
node._o1igPrompt.value = findWidget(node, "prompt")?.value || "";
|
||
node._o1igCount.value = normalizeImageCount(findWidget(node, "生图数量")?.value, node._o1igModel.value);
|
||
syncModelOptions(node);
|
||
syncResizeWarning(node);
|
||
syncBatchLayout(node);
|
||
renderReferences(node);
|
||
syncMaskControl(node);
|
||
}
|
||
|
||
const GENERATOR_SERIALIZED_WIDGETS = BACKEND_WIDGETS.filter(name => !RETIRED_BACKEND_WIDGETS.has(name));
|
||
|
||
function serializeGeneratorWidgets(node, data) {
|
||
// widgets_values is positional, so it is always written in schema order. The on-canvas
|
||
// order can differ (批量出图 sits above 模型) without touching saved workflows.
|
||
const values = [];
|
||
for (const name of GENERATOR_SERIALIZED_WIDGETS) {
|
||
const widget = findWidget(node, name);
|
||
if (widget) values.push(widget.value);
|
||
}
|
||
data.widgets_values = values;
|
||
}
|
||
|
||
const PANEL_WIDGET_NAME = "o1key_image_generator_panel";
|
||
const ACTIONS_WIDGET_NAME = "o1key_image_generator_actions";
|
||
|
||
const GENERATOR_LEADING_WIDGETS = ["批量出图", "批量模式"];
|
||
const GENERATOR_DISPLAY_WIDGETS = (() => {
|
||
const leading = GENERATOR_LEADING_WIDGETS.filter(name => GENERATOR_SERIALIZED_WIDGETS.includes(name));
|
||
const rest = GENERATOR_SERIALIZED_WIDGETS.filter(name => !leading.includes(name));
|
||
const modelIndex = rest.indexOf("模型");
|
||
if (modelIndex < 0) return [...GENERATOR_SERIALIZED_WIDGETS];
|
||
const display = [...rest];
|
||
display.splice(modelIndex, 0, ...leading);
|
||
return display;
|
||
})();
|
||
|
||
function orderNativeWidgets(node, order) {
|
||
const widgets = node?.widgets;
|
||
if (!Array.isArray(widgets) || !order?.length) return;
|
||
const rank = new Map(order.map((name, index) => [name, index]));
|
||
const keyed = widgets.map((widget, index) => ({
|
||
widget,
|
||
index,
|
||
key: widget?.name === PANEL_WIDGET_NAME
|
||
? -1
|
||
: widget?.name === ACTIONS_WIDGET_NAME
|
||
? Number.MAX_SAFE_INTEGER
|
||
: rank.has(widget?.name) ? rank.get(widget.name) : 500000 + index,
|
||
}));
|
||
keyed.sort((a, b) => (a.key - b.key) || (a.index - b.index));
|
||
const ordered = keyed.map(item => item.widget);
|
||
if (ordered.every((widget, index) => widgets[index] === widget)) return;
|
||
widgets.splice(0, widgets.length, ...ordered);
|
||
node.setDirtyCanvas?.(true, true);
|
||
}
|
||
|
||
function applyNativeParameterOrder(node) {
|
||
// Display-only: LiteGraph and the Vue nodes render widgets in node.widgets order, so the
|
||
// batch rows are pulled up in front of 模型. Saved data keeps the schema order above.
|
||
if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return;
|
||
orderNativeWidgets(node, GENERATOR_DISPLAY_WIDGETS);
|
||
}
|
||
|
||
app.registerExtension({
|
||
name: "o1key.imageGeneratorPanel",
|
||
|
||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||
if (nodeData.name === SAVE_NODE_TYPE) {
|
||
const originalCreated = nodeType.prototype.onNodeCreated;
|
||
nodeType.prototype.onNodeCreated = function () {
|
||
originalCreated?.apply(this, arguments);
|
||
buildSavePanel(this);
|
||
};
|
||
|
||
const originalConfigure = nodeType.prototype.onConfigure;
|
||
nodeType.prototype.onConfigure = function (data) {
|
||
const result = originalConfigure?.apply(this, arguments);
|
||
buildSavePanel(this);
|
||
const storedResults = storedSaveResults(this, data);
|
||
this._o1igsSlots = reconcileSaveSlotsWithResults(
|
||
storedSaveSlots(this, data),
|
||
storedResults,
|
||
);
|
||
syncSaveSlotsWidget(this);
|
||
renderSaveResults(this, storedResults, { persist: false });
|
||
return result;
|
||
};
|
||
|
||
const originalSerialize = nodeType.prototype.onSerialize;
|
||
nodeType.prototype.onSerialize = function (data) {
|
||
originalSerialize?.apply(this, arguments);
|
||
const images = normalizeSaveResults(this._o1igsLastResults);
|
||
const slots = normalizeSaveSlots(this._o1igsSlots);
|
||
this.properties ??= {};
|
||
this.properties.o1keyImageSaveResults = images;
|
||
this.properties.o1keyImageSlots = slots;
|
||
data.properties ??= {};
|
||
data.properties.o1keyImageSaveResults = images;
|
||
data.properties.o1keyImageSlots = slots;
|
||
data.o1key_image_save_results = images;
|
||
data.o1key_image_slots = slots;
|
||
};
|
||
|
||
const originalExecutionStart = nodeType.prototype.onExecutionStart;
|
||
nodeType.prototype.onExecutionStart = function () {
|
||
originalExecutionStart?.apply(this, arguments);
|
||
buildSavePanel(this);
|
||
if (
|
||
this._o1igsStandardQueueReserved
|
||
|| this._o1igsStandardExecutionPending
|
||
|| this._o1igsBusy
|
||
) setSaveBusy(this, true);
|
||
};
|
||
|
||
const originalExecuted = nodeType.prototype.onExecuted;
|
||
nodeType.prototype.onExecuted = function (message) {
|
||
const images = Array.isArray(message?.images) ? message.images : [];
|
||
const restoringPreview = Boolean(this._o1igsRestoringPreview);
|
||
originalExecuted?.apply(this, arguments);
|
||
buildSavePanel(this);
|
||
renderSaveResults(this, images, { persist: !restoringPreview });
|
||
if (images.length) scheduleSaveNodeImageFit(this);
|
||
if (restoringPreview) setSaveBusy(this, false);
|
||
else finishGenerationBatch(
|
||
this,
|
||
"生成完成",
|
||
String(this._o1igsDispatchBatchId || ""),
|
||
);
|
||
this.setDirtyCanvas?.(true, true);
|
||
};
|
||
|
||
const originalRemoved = nodeType.prototype.onRemoved;
|
||
nodeType.prototype.onRemoved = function () {
|
||
clearTimeout(this._o1igsPreviewFitTimer);
|
||
detachParallelBatchNode(this);
|
||
originalRemoved?.apply(this, arguments);
|
||
};
|
||
|
||
return;
|
||
}
|
||
|
||
if (nodeData.name !== NODE_TYPE) return;
|
||
// A running ComfyUI server can still serve the previous schema until restart.
|
||
if (nodeData.input?.optional) delete nodeData.input.optional.external_prompt;
|
||
installNativeMinimumSize(nodeType, GENERATOR_MIN_SIZE);
|
||
|
||
const originalSerialize = nodeType.prototype.onSerialize;
|
||
nodeType.prototype.onSerialize = function (data) {
|
||
originalSerialize?.apply(this, arguments);
|
||
serializeGeneratorWidgets(this, data);
|
||
};
|
||
|
||
const originalCreated = nodeType.prototype.onNodeCreated;
|
||
nodeType.prototype.onNodeCreated = function () {
|
||
originalCreated?.apply(this, arguments);
|
||
this._o1igApplyGptDefaults = true;
|
||
applyGeneratorDefaultSize(this);
|
||
buildPanel(this);
|
||
};
|
||
|
||
const originalConfigureMethod = nodeType.prototype.configure;
|
||
nodeType.prototype.configure = function (data) {
|
||
// widgets_values is positional, so it is restored against the schema order and only
|
||
// then re-ordered for display. Keeps paste / workflow loads aligned no matter when
|
||
// applyNativeParameterOrder() already ran.
|
||
orderNativeWidgets(this, GENERATOR_SERIALIZED_WIDGETS);
|
||
const result = originalConfigureMethod?.apply(this, arguments);
|
||
applyNativeParameterOrder(this);
|
||
return result;
|
||
};
|
||
|
||
const originalConfigure = nodeType.prototype.onConfigure;
|
||
nodeType.prototype.onConfigure = function (data) {
|
||
this._o1igApplyGptDefaults = false;
|
||
// A workflow (re)load is not a gesture: drop a press that never got its pointerup.
|
||
resetCanvasPointerGesture();
|
||
const result = originalConfigure?.apply(this, arguments);
|
||
buildPanel(this);
|
||
restorePanelFromWidgets(this);
|
||
fitNode(this);
|
||
return result;
|
||
};
|
||
|
||
const originalResize = nodeType.prototype.onResize;
|
||
nodeType.prototype.onResize = function (size) {
|
||
originalResize?.apply(this, arguments);
|
||
// Engine-driven resizes (creation, workflow restore, Vue re-layout after rows
|
||
// appear/disappear) must not be treated as a manual resize, otherwise the node
|
||
// keeps the taller body and leaves an empty strip when 批量出图 is turned off.
|
||
if (this._o1igAutoSizing) return; // Our own setSize(): keep the drag anchor.
|
||
if (!this._o1igSettled || !canvasPointerDown) {
|
||
this._o1igDragAnchor = null;
|
||
return;
|
||
}
|
||
// Only a press that started on this node can be resizing it. A press on a menu row
|
||
// (重启/设置) never restores its pointerup, so without this check the next engine
|
||
// re-layout behaves like a drag and the node grows by the mouse travel.
|
||
if (!pointerStartsInsideNode(this, canvasPointerStartX, canvasPointerStartY)) {
|
||
this._o1igDragAnchor = null;
|
||
return;
|
||
}
|
||
const height = Number(size?.[1]) || 0;
|
||
if (!(height > 0)) return;
|
||
// While the pointer is down the Vue body is still on the previous layout, so
|
||
// computeSize lags behind; follow the pointer delta from the drag start instead.
|
||
if (!this._o1igDragAnchor) {
|
||
// Anchor on the last programmatic height, not on this event's size: the first
|
||
// resize already carries part of the drag.
|
||
const baseline = Number(this._o1igSizedHeight);
|
||
this._o1igDragAnchor = {
|
||
height: Number.isFinite(baseline) && baseline > 0 ? baseline : height,
|
||
extra: generatorExtraHeight(this),
|
||
pointerY: canvasPointerStartY,
|
||
};
|
||
}
|
||
const anchor = this._o1igDragAnchor;
|
||
const heightDelta = height - anchor.height;
|
||
const nextExtra = nextGeneratorExtra(anchor, canvasPointerY, heightDelta, nodeDomScale(this));
|
||
if (nextExtra === null) {
|
||
// A width drag keeps LiteGraph's height; just re-fit once it settles.
|
||
this.scheduleGeneratorRefit();
|
||
return;
|
||
}
|
||
setGeneratorExtraHeight(this, nextExtra);
|
||
// Live feedback while dragging: the panel grows and the textarea follows.
|
||
syncPanelExtraDomHeight(this);
|
||
this.scheduleGeneratorRefit();
|
||
};
|
||
|
||
nodeType.prototype.scheduleGeneratorRefit = function () {
|
||
clearTimeout(this._o1igResizeFitTimer);
|
||
this._o1igResizeFitTimer = setTimeout(() => {
|
||
// Never fight the pointer: re-flow once the drag is over.
|
||
if (canvasPointerDown) {
|
||
this._o1igResizeFitTimer = setTimeout(() => fitNode(this), 200);
|
||
return;
|
||
}
|
||
fitNode(this);
|
||
}, 140);
|
||
};
|
||
|
||
const originalExecutionStart = nodeType.prototype.onExecutionStart;
|
||
nodeType.prototype.onExecutionStart = function () {
|
||
originalExecutionStart?.apply(this, arguments);
|
||
buildPanel(this);
|
||
const standardSaveNode = startNextStandardExecution(this);
|
||
if (standardSaveNode) {
|
||
this._o1igRunning = false;
|
||
setStatus(this, "", "");
|
||
return;
|
||
}
|
||
if (pendingBatchIds(this).size) updateGeneratorActivity(this);
|
||
else {
|
||
this._o1igRunning = false;
|
||
setStatus(this, "", "");
|
||
}
|
||
};
|
||
|
||
const originalExecuted = nodeType.prototype.onExecuted;
|
||
nodeType.prototype.onExecuted = function (message) {
|
||
originalExecuted?.apply(this, arguments);
|
||
buildPanel(this);
|
||
clearNativePreview(this);
|
||
if (this._o1igsActiveStandardSaveNodeId != null) {
|
||
this._o1igRunning = false;
|
||
setStatus(this, "", "");
|
||
} else if (pendingBatchIds(this).size) updateGeneratorActivity(this);
|
||
else {
|
||
this._o1igRunning = false;
|
||
setStatus(this, "", "");
|
||
}
|
||
this.setDirtyCanvas?.(true, true);
|
||
};
|
||
|
||
const originalRemoved = nodeType.prototype.onRemoved;
|
||
nodeType.prototype.onRemoved = function () {
|
||
if (this._o1igOutsideHandler) document.removeEventListener("pointerdown", this._o1igOutsideHandler);
|
||
clearTimeout(this._o1igStatusTimer);
|
||
clearTimeout(this._o1igPromptOptimizeStatusTimer);
|
||
detachParallelBatchNode(this);
|
||
originalRemoved?.apply(this, arguments);
|
||
};
|
||
},
|
||
|
||
loadedGraphNode(node) {
|
||
if (node?.comfyClass === NODE_TYPE) {
|
||
buildPanel(node);
|
||
fitNode(node);
|
||
} else if (node?.comfyClass === SAVE_NODE_TYPE) {
|
||
buildSavePanel(node);
|
||
restoreNativeSavePreview(node);
|
||
}
|
||
},
|
||
|
||
async afterConfigureGraph() {
|
||
requestAnimationFrame(() => {
|
||
for (const node of app.graph?._nodes || []) {
|
||
if (node?.comfyClass === NODE_TYPE) {
|
||
node._o1igOutputsReady = true;
|
||
syncGeneratorOutputVisibility(node);
|
||
fitNode(node);
|
||
if (!findLegacyAutoSaveNodes(node).length) continue;
|
||
try {
|
||
ensureSaveNode(node);
|
||
} catch {
|
||
// Keep the legacy node intact until the new backend node is available.
|
||
}
|
||
} else if (node?.comfyClass === SAVE_NODE_TYPE) {
|
||
restoreNativeSavePreview(node);
|
||
recoverParallelBatch(node);
|
||
}
|
||
}
|
||
});
|
||
},
|
||
|
||
setup() {
|
||
installNativeTaskQueueBridge();
|
||
installStandardQueueRouting();
|
||
installNativePreviewActionSync();
|
||
api.addEventListener("o1key.image_job", ({ detail }) => {
|
||
handleParallelImageJob(detail);
|
||
});
|
||
api.addEventListener("execution_error", ({ detail }) => {
|
||
const rawId = detail?.node_id ?? detail?.node;
|
||
const nodeId = typeof rawId === "string" ? Number(rawId) : rawId;
|
||
const node = app.graph?.getNodeById?.(nodeId);
|
||
const rawMessage = detail?.exception_message || detail?.error;
|
||
const message = formatImageGenerationError(rawMessage);
|
||
if (node?.comfyClass === NODE_TYPE) {
|
||
failOldestGenerationBatch(node, message);
|
||
replaceExecutionErrorOverlay(message);
|
||
} else if (node?.comfyClass === SAVE_NODE_TYPE) {
|
||
finishGenerationBatch(node, message);
|
||
replaceExecutionErrorOverlay(message);
|
||
} else if (SEEDANCE_ERROR_NODE_TYPES.has(node?.comfyClass)) {
|
||
replaceExecutionErrorOverlay(formatSeedanceGenerationError(rawMessage));
|
||
}
|
||
});
|
||
api.addEventListener("execution_interrupted", () => {
|
||
for (const node of app.graph?._nodes || []) {
|
||
if (
|
||
node?.comfyClass === NODE_TYPE
|
||
&& (node._o1igRunning || pendingBatchIds(node).size || activeStandardSaveNode(node))
|
||
) {
|
||
failOldestGenerationBatch(node, "生成已取消");
|
||
}
|
||
}
|
||
});
|
||
},
|
||
});
|