Compare commits

...
15 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 5 74eb8b779f Merge branch 'feature/video-edit-tab': Video Edit tab (v0.7.0)
Video タブに簡易動画編集機能(Editサブタブ)を新規実装。クリップの
タイムライン配置、トリム(Clipchamp風ビジュアルスクラバー)、複数
クリップの結合書き出し、静止画/アニメーション画像クリップ対応。
あわせてAssetサブタブをPlan/Editと並ぶ中央下部へ移設し検索・グリッド
/テーブル表示切替を追加、プレビュー枠の高さ固定、Frame保存のVideo
Assets登録とAsset→PlanのFirst/Last Image連携も実装した。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 13:32:40 +09:00
ketle-manandClaude Sonnet 5 baed398fe8 chore(release): v0.7.0 - Video Edit tab初回リリース + Asset移設・トリムスクラバー等
pyproject.tomlのバージョンを0.7.0に更新し、DEVLOG.mdとREADME.mdを
今回のリリース内容(Edit subtab全体の初回公開、Assetサブタブの中央下部
移設、トリムパネルのClipchamp風スクラバー、Frame保存のVideo Assets
登録、Asset→PlanのFirst/Last Image連携)に合わせて更新した。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 13:31:47 +09:00
ketle-manandClaude Sonnet 5 77cfedb243 docs(video-tab): Video Tabヘルプを現行UIとEdit/Asset機能に合わせて更新
Asset subtabが左サイドバーから中央下部(Plan/Editと並ぶ)に移設された
ことを反映し、Project subtabの説明からも「Assetの隣」という古い記述を
削除。Editサブタブ(クリップタイムライン・トリムスクラバー・書き出し)
とAssetサブタブ(検索・グリッド/テーブル切替・First/Last Image連携)の
説明を新規項目として追加し、Frameタブの説明にVideo Assets登録
チェックボックスを追記。index.html・i18n.js(en/ja/zh)・app.jsの
helpIdMapの3点セットで更新。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 13:28:28 +09:00
ketle-manandClaude Sonnet 5 ad70622942 feat(video-tab): FrameのVideo Assets登録チェックボックスとAsset→Plan画像連携を追加
Frameタブの「Outputに保存」にオプションのチェックボックスを追加し、
チェック時は保存したフレームをGalleryの__Video Assets__グループに
自動登録できるようにした。

またAssetタブの画像アセット詳細に「First Imageに設定」「Last Imageに
設定」ボタンを追加し、Planタブの選択中ブロックのFirst/Last Imageへ
直接送れるようにした(動画クリップでは非表示、画像のみ対象)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 13:19:51 +09:00
ketle-manandClaude Sonnet 5 f726418aeb feat(video-edit-tab): トリムパネルにClipchamp風のビジュアルスクラバーを追加
動画クリップのトリム編集を、テキスト入力のみだったUIから、時間目盛り・
再生位置(playhead)・ドラッグ可能なトリムハンドルを備えたビジュアルな
スクラバーに拡張。プレビュー動画のcurrentTimeとplayheadが同期し、
トラックのクリック/ドラッグでシークも可能。既存のStart/End数値入力・
「現在位置を使用」ボタンとは同じcommit経路で連動する。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:55:30 +09:00
ketle-manandClaude Sonnet 5 a917e82ad7 feat(video-tab): AssetをPlan/Editと並ぶ中央下部の第3サブタブに移設
左サイドバーにあったAsset一覧・詳細パネルを中央ペイン下部に移設し、
左=素材一覧(サムネイル/テーブル切替可)・右=選択ファイルの詳細という
2カラムレイアウトに再構成。一覧上部にグループ切替・ファイル名検索・
表示切替ボタンを追加した。左サイドバーはProjectのみのシンプルな
パネルになった。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:32:54 +09:00
ketle-manandClaude Sonnet 5 2fc2365461 fix(video-tab): プレビュー枠の高さを固定してPlan/Editの位置ずれを解消
動画ソースのネイティブサイズによってプレビュー枠(min-height)が伸縮し、
中央ペイン下部のPlan/Editサブタブの表示位置が動画ごとに動いてしまう問題を修正。
枠の高さを固定し、動画/画像は縮小表示のみ(拡大はしない)に変更した。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:18:58 +09:00
ketle-manandClaude Sonnet 5 337fd6ecb8 docs: log Video Edit tab work-in-progress in DEVLOG
Records this session's feature/video-edit-tab branch work (unreleased,
no version bump) — Edit subtab MVP, Phase 0 node-behavior findings,
image-clip support, and the audio-mismatch fix — under a new
Unreleased section, per existing DEVLOG convention where every
version heading corresponds to an actual tagged release.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 20:13:07 +09:00
ketle-manandClaude Sonnet 5 831ba1bd43 Support still/animated image clips in the Edit timeline
Asset's Video Assets/Video Temp groups already list any image tagged
into them (no video-only filter), but selecting one always fed a
<video> element, which can't render image formats — the preview
stayed blank and "Send to Edit" produced a broken clip.

Adds an <img> companion to both preview panes (video-preview.js gains
a mediaType param on setSourcePreview/setResultPreview) so images
preview correctly, and gives Edit-tab clips a kind: "video" | "image".
Image clips get a single editable hold duration instead of in/out trim
points, and export turns them into a real video segment via
LoadImage -> (ImageScale center-crop, only if resolution needs to
match another clip) -> RepeatImageBatch -> CreateVideo — verified on a
live instance to produce an exact-duration, concatenation-compatible
clip. The resolution-mismatch guard now only compares video clips
against each other, since images are auto-fit instead of blocked.

Also fixes a bug this surfaced: ConcatenateVideo hard-errors mixing a
clip with real audio (e.g. stereo/32kHz) next to a silent
image-derived clip. Multi-clip exports now strip audio from every
video clip too (via GetVideoComponents -> CreateVideo) so the whole
timeline is uniformly silent when concatenating; a lone clip keeps its
original audio since no concatenation occurs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 20:10:07 +09:00
ketle-manandClaude Sonnet 5 899feb1bb5 Add sequential timeline preview sharing the Result pane with Export
Adds a Play/Stop toggle on the timeline toolbar that plays every ready
clip back-to-back (each trimmed to its in/out point) in the same
"Result" preview pane Export writes its finished output into — not a
new <video> element — so what's shown there is always exactly what
Export would currently produce. Clip-boundary advancement is driven by
timeupdate/ended listeners comparing against each clip's trimEnd.

video-preview.js gains getResultPreviewVideoElement() since driving
playback (seeking, listening for the trim-out point, swapping sources)
needs direct element access that setResultPreview()'s simple
src-and-visibility API doesn't provide.

Verified end-to-end on a live instance: 2-clip preview with automatic
mid-playback advancement at the first clip's trim-out, then export
producing the same combined duration the preview showed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 17:55:12 +09:00
ketle-manandClaude Sonnet 5 075e2a8c62 Fix trim panel overflow and add timeline total duration display
The Start/End (seconds) inputs and their "use current position"
buttons were laid out side by side, letting the button label overflow
past the container edge and making the button hard to distinguish
from a text field. Stacks the button below the input instead, shrinks
it, and narrows the input column so both fit cleanly.

Also adds a running total-duration readout next to the Clear button,
summing every clip's trimmed length — updated automatically whenever
the timeline re-renders.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 17:46:46 +09:00
ketle-manandClaude Sonnet 5 77163de202 Fix Edit tab layout collapsing to center; drop its own dropzone
Root cause: a leftover CSS rule from the pre-implementation
"Editing tools coming soon" placeholder era (display:flex;
align-items:center; justify-content:center; dashed border) still
targeted .wfm-video-edit-panel and, coming later in the cascade,
silently overrode the real layout — shrinking the timeline, trim
panel, and export panel to their content width and centering them
instead of stretching full-width like the Plan subtab. Removed the
stale rule and gave the timeline track explicit width:100%/flex:none
so it stays a fixed full-width bar (matching Plan's track) regardless
of clip count.

Also removes the Edit subtab's own drop zone now that clips can only
be added via Asset's "Editへ送る" and the Video Source panel's
"Add to Edit" button — one fewer entry point to keep in sync, and the
now-unused videoEditDropLabel i18n key goes with it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 17:38:22 +09:00
ketle-manandClaude Sonnet 5 7f0ecc2ba3 Redesign Video Edit timeline to match the Plan subtab's UI pattern
Replaces the vertical clip list (per-row ▲▼⧉✕ buttons) with a
horizontal timeline track whose blocks are left-aligned at their real
duration (px/sec scale) rather than stretched to fill the track like
Plan's blocks. Reordering moves to a shared toolbar below the track
(◀/▶/Duplicate/Delete/Clear acting on the selected clip), matching
Plan's "+ Split/+ Block/Delete" pattern, plus native HTML5
drag-and-drop reordering directly on the blocks.

Adds a new "Add to Edit" button on the Video Source panel so whatever
is loaded there (a plain drop, an Asset selection, a Frame/GIF source)
can be added to the Edit timeline explicitly — deliberately not
automatic on every Source drop, since Frame/GIF is a single-video tool
used far more often than multi-clip editing and auto-adding would
clutter the timeline.

Verified end-to-end on a live ComfyUI 0.36.0 instance: left-aligned
block widths, Asset -> Add to Edit handoff, move/duplicate/delete/
clear (with i18n'd confirm dialog), and export after a clear.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 17:24:51 +09:00
ketle-manandClaude Sonnet 5 ac733db81e Add Video Edit tab MVP: clip timeline, trim, and concatenate export
Implements the Edit subtab (previously a placeholder) with a minimal
clip timeline: add clips from Asset/local files, reorder/duplicate/
delete, trim per clip, and export by dynamically assembling a ComfyUI
API-format prompt ("Video Slice" per clip -> ConcatenateVideo when
multiple clips -> SaveVideo) run through the existing execution
infrastructure. Exported videos are tagged into the __Video Temp__
gallery group like Plan-tab runs.

Verified end-to-end against a live ComfyUI 0.36.0 instance, including
two bugs only caught by inspecting actual output (not just
execution_success): a missing WebSocket connect before trackProgress,
and VideoTrim silently no-opping on a flat trim value (switched to the
simpler, non-experimental "Video Slice" node instead). See
VIDEO_EDIT_TAB_PLAN.md for the full design and findings.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 17:05:31 +09:00
ketle-manandClaude Sonnet 5 7f2720ff8f release: v0.6.3 — Send CCボタンでMP4動画をComic Creatorの動画ツールへ送れるように対応
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-14 22:24:58 +09:00
18 changed files with 2158 additions and 99 deletions
+2
View File
@@ -2,6 +2,8 @@
Condensed version-by-version index of DEVLOG.md (each line: version + one-line summary of what changed and why). Full rationale, code details, and "How to apply" lessons live in the excluded DEVLOG.md itself; this index exists so graphify can extract a queryable semantic node per release without feeding the full log to the local Ollama model. Regenerate with `python tools/generate_doc_index.py devlog` whenever DEVLOG.md changes.
- **v0.7.0(2026-09-17)** — プレビュー枠の高さ固定・AssetサブタブをPlan/Editと並ぶ中央下部へ移設・トリムパネルにClipchamp風スクラバー追加・Frame保存のVideo Assets登録とAsset→Plan画像連携
- **v0.6.3** — Send CCボタンでMP4動画をComic Creatorの新設「動画ツール」へ送れるように対応
- **v0.6.2** — Image Editタブにペンタブレット筆圧対応とFillツール(バケツ塗りつぶし)を追加
- **v0.6.1** — Galleryタブの検索が「読み込み中」のまま止まりクリアでも中断できない不具合、および50枚程度のフォルダでも数秒〜十数秒かかる不具合を修正
- **v0.6.0** — Gallery/Image Edit両タブにPSD(Photoshop)対応を追加 — 複数画像の一括PSD書き出し、レイヤー保存/読み込み、Gallery表示、Image Editのレイヤーパネル改善
+59
View File
@@ -2,6 +2,64 @@
---
## v0.7.0(2026-09-17)
### プレビュー枠の高さ固定・AssetサブタブをPlan/Editと並ぶ中央下部へ移設・トリムパネルにClipchamp風スクラバー追加・Frame保存のVideo Assets登録とAsset→Plan画像連携
Edit サブタブMVP実装後、実際にユーザーが使う中で見つかった調整要望をまとめて対応した。
**プレビュー枠の高さ固定**: 中央ペインのSource/Resultプレビュー枠が`min-height`指定のみだったため、動画ソースのネイティブサイズ(特に縦長)によって枠が伸縮し、下のPlan/Editサブタブの表示位置がソースを選ぶたびに動いてしまっていた。枠を`height:260px`固定にし、動画/画像側は`width/height:auto; max-width/max-height:100%`(ネイティブサイズが枠より大きい場合のみ縮小、小さい場合は拡大しない)に変更して解消。
**AssetサブタブをPlan/Editと並ぶ中央下部の第3サブタブへ移設**: 左サイドバーにあったAsset一覧・詳細パネルを中央ペイン下部(Plan/Editと同じ場所)へ移設し、左=一覧(サムネイル/テーブル切替可)・右=選択ファイルの詳細という2カラムレイアウトに再構成。一覧上部にグループ切替・ファイル名検索・表示切替(▦グリッド/☰テーブル)ボタンを追加した。左サイドバーはProjectのみのシンプルなパネルになった。
**トリムパネルにClipchamp風ビジュアルスクラバーを追加**: 動画クリップのトリム編集がテキスト入力(開始/終了秒)のみだったのを、時間目盛り(ルーラー)・Sourceプレビューの`currentTime`と同期するドラッグ可能な再生ヘッド・時刻バッジ付きのドラッグ可能なイン/アウトハンドルを備えたビジュアルなスクラバーに拡張した。全位置を`clip.duration`基準の%指定にすることでpx/秒換算の管理を持たずに済ませている。既存のStart/End数値入力・「現在位置を使用」ボタンとは同じ`commit`関数を通して連動する。ハンドルドラッグ中は`_renderTimeline()`の再描画を避け、pointerup時のみ確定してパフォーマンスに配慮。playheadとトリムハンドルが同じ位置に重なってもハンドル操作を優先できるようz-indexを調整した。
**Frame保存のVideo Assets登録とAsset→Plan画像連携**: 右ペインFrameタブの「Save to Output」に「Add to Video Assets group」チェックボックスを追加し、チェック時は保存したフレームをGalleryの`__Video Assets__`グループへ自動登録できるようにした。またAssetタブの画像アセット詳細に「Set as First Image」「Set as Last Image」ボタンを追加し、PlanタブのFirst/Last Imageへ直接画像をアップロードできるようにした(動画クリップでは非表示、選択中のPlanブロックへ反映後Planサブタブへ自動切り替え)。
**検証**: いずれもKaptureで実機ComfyUI_5(ポート8189)に接続し、正方形/縦長動画でのプレビュー枠固定確認、Asset新レイアウトでのグリッド/テーブル切替・検索・選択、トリムスクラバーのplayhead同期・トラッククリックシーク・ハンドルドラッグ(playhead重なり時含む)・複数クリップ切替時のリスナー管理、Frame保存後のGalleryグループ登録をAPI経由で確認、Asset画像からFirst/Last Imageへの反映まで一通り実機確認済み。
**How to apply**: プレビュー枠のようにコンテンツ依存でサイズが変わる要素が、隣接するUIの表示位置に影響する場合は、コンテンツ側ではなく枠側を固定サイズにしてコンテンツを内側で縮小表示する方が安全([[project_video_edit_tab_feature_branch]])。ドラッグ可能なUI要素同士が同じ座標に重なる可能性がある場合は、操作頻度の高い方(今回はトリムハンドル)のz-indexを優先し、もう一方の当たり判定に埋もれないようにする。
関連: [[project_video_edit_tab_feature_branch]]
### Video タブ Edit サブタブ: 簡易動画編集機能(クリップタイムライン・トリム・結合・書き出し)を新規実装
これまで「Editing tools coming soon」のプレースホルダーのみだったVideoタブのEditサブタブに、Adobe Premiereライクな簡易動画編集機能を実装した。詳細設計・調査結果は[VIDEO_EDIT_TAB_PLAN.md](VIDEO_EDIT_TAB_PLAN.md)にまとめてある。
**MVP機能**: クリップのタイムライン配置(左詰め、実秒数×固定px/秒スケール)、トリム(開始/終了秒)、複数クリップの結合書き出し、タイムライン全体の疑似連続プレビュー、静止画/アニメーション画像クリップ(表示時間指定)、Clear/複製/削除/並べ替え(◀▶ボタンおよびネイティブドラッグ&ドロップ)。新規ファイル`static/js/video-edit-tab.js`が中心実装。
**Phase 0実機検証での重要な発見(当初の設計を訂正)**:
- ComfyUI Core 0.35〜0.36には`VideoSlice`という名前のノードは存在せず、正しいclass_typeは`"Video Slice"`(スペース込み)。`VideoTrim`(experimental)の`trim`入力はフラット値`{"start_time":..}`を渡すと**エラーにならず黙って何もトリムしない**(`.get("trim")`で一段余計にネストを剥がす実装のため)。実際に出力duration をprobeして初めて発覚し、「`execution_success`だけでは検証不十分」という教訓を得た。
- `ConcatenateVideo`のAutogrow入力`videos`は、ネストしたJSONオブジェクトではなく`"videos.video0"`のようなドット結合フラットキーがinputsのトップレベルに必要(ComfyUI Core `Autogrow.TemplatePrefix`のドット結合ロジックに由来)。
- `ConcatenateVideo`は解像度不一致で実行時ハードエラーになるため、クライアント側で事前チェックし、動画クリップ同士の不一致は書き出しをブロック、画像クリップは`ImageScale`(crop=center)で自動フィットして回避。
- 動画クリップ(音声あり)と画像由来クリップ(無音)を結合すると`ConcatenateVideo`が音声レイアウト不一致でエラーになる。複数クリップ結合時のみ、全クリップを`GetVideoComponents`→`CreateVideo`で無音統一する対策を実装(単一クリップ書き出しは音声を保持。**複数クリップ結合時は音声が失われるのが既知の限界**)。
**静止画/アニメーション画像クリップ対応**: 既存のAsset一覧(`__Video Assets__`/`__Video Temp__`グループ)には元々ビデオ専用フィルタが無く画像も一覧されていたが、プレビューが常に`<video>`要素前提で画像では何も表示されなかった。`video-preview.js`のSource/Resultプレビュー枠に`<img>`コンパニオン要素を追加し、`mediaType`引数で切り替えるよう拡張。画像クリップは`LoadImage`→(必要時)`ImageScale`→`RepeatImageBatch(amount=表示秒数×24fps)`→`CreateVideo`で正確な長さの動画セグメントに変換して書き出しグラフに組み込む。
**UI設計はPlanサブタブに合わせて再設計**: 当初は縦リスト+各行ボタンだったが、ユーザー指示によりPlanタブの横トラック+共有ツールバー方式(◀▶/複製/削除/クリアが選択中クリップに対して働く)に変更。タイムライン自体はPlanのブロックのようにflex-growで幅一杯に引き伸ばさず、実秒数の固定幅で左詰め(空きトラックはそのまま空く)。この過程で、Edit実装以前の「Editing tools coming soon」プレースホルダー時代の重複CSSルール(`align-items:center`等)が残存しており、実装後もタイムライン全体が中央に縮んで表示される不具合を発見・修正した。
**タイムライン連続プレビュー**: 新規`<video>`要素を追加せず、Export結果が最終的に書き出される「生成された動画」(Result)プレビュー枠を共有し、全クリップ(トリム区間反映)を順番に連続再生する機能を追加(「▶ プレビュー / ■ 停止」トグル)。ユーザー要望「このプレビューの動画=書き出しされる動画」に対応。
**検証**: 全JS/Pythonファイルを`node --check`/構文チェックで確認。開発元リポジトリと実行時`custom_nodes`は別実体のため、変更のたびに両フォルダへ同期しmd5ハッシュ比較で完全一致を確認。Kapture(ブラウザDevTools連携)で実機ComfyUI_5(ポート8189)に接続し、クリップ追加・トリム・並べ替え(ドラッグ含む)・複製・削除・クリア・連続プレビュー・単一/複数クリップ書き出し・静止画クリップの書き出し・動画+画像混在結合を一通り実機確認済み。
**How to apply**: ComfyUI Coreの新しいノード(特にexperimental扱いのもの)をAPIプロンプト形式で直接呼び出す際は、`/object_info`のクラス名・入力スキーマを鵜呑みにせず、実際に`/prompt`で実行して**出力を実測**するまで検証を終えたとみなさない——`execution_success`は型検証を通っただけで、パラメータが意図通り効いたかは別問題(今回`VideoTrim`のトリムが黙って無視される形で顕在化)。Autogrow(`COMFY_AUTOGROW_V3`)型の動的入力は、フラットなドット結合キー(`"prefix{name}"`を`.`区切りでinputsトップレベルに並べる)で渡す。
関連: [[project_dev_deploy_sync]]
## v0.6.3
### Send CCボタンでMP4動画をComic Creatorの新設「動画ツール」へ送れるように対応
Comic Creator(`eagle_comic_creator_spa/comfyui-comic-creator`、別リポジトリ)側にレイアウトタブの新機能「動画ツール」(MP4をコマに配置して再生・停止・音量/ミュート調整・指定フレームでの静止画キャプチャができる実験的機能)が追加されたのに伴い、Galleryタブの「Send CC」ボタンをこれに対応させた。
**問題**: 既存の`sendCcBtn`クリックハンドラ(`gallery-tab.js`)は、選択中ファイルのURLを`window.parent.insertImageFromUrl()`(レイアウトタブ宛て)または`window.parent._ccImageTab.loadFromUrl()`(Imageタブ宛て)へ渡すだけで、`.mp4`を判別する分岐が無かった。Comic Creator側の受け口は画像専用ロジックしか持たないため、動画を選んでSend CCを押しても正しく処理されなかった。
**対応**: `gallery-tab.js`に既にあった`isVideoFile()`ヘルパー(拡張子判定、Video Assetsグループのバッジ表示等で使用中)で選択中ファイルが動画かどうかを判定し、レイアウトタブ宛て(デフォルト経路)で動画の場合はComic Creator側が今回新設した受け口`window.parent.insertVideoFromUrl(url, filename)`を呼ぶよう分岐した。Imageタブ宛て(`_ccI2ITargetMode === 'image'`)で動画を選んだ場合は、Comic Creator側が今回Imageタブの動画編集には対応していないため、トースト(新規i18nキー`galleryVideoNotSupportedInImageTab`、英/日/中3言語)で案内して送信を中断するようにした。
**検証**: 双方の変更点を構文チェック(`node --check`)のみで確認。ComfyUI実機でのSend CC往復動作(Gallery側でmp4選択→送信→Comic Creator側でのオーバーレイ表示・再生確認)はユーザー側での実機確認待ち。
**How to apply**: Comic Creator側とWorkflow Studio側は別リポジトリだが、Send CC・Send to LI nodeのような`window.parent`/`window.opener`経由のクロスウィンドウ連携APIは、どちらか一方だけを変更すると壊れる。片方(今回はComic Creator側)に新しい受け口(`insertVideoFromUrl`)を追加したら、呼び出し元であるこちらのGalleryタブ側も同時に更新する必要がある。
## v0.6.2
### Image Editタブにペンタブレット筆圧対応とFillツール(バケツ塗りつぶし)を追加
@@ -57,6 +115,7 @@
**Gallery: PSDファイルの一覧・サムネイル・プレビュー表示** — `.psd`を`IMAGE_EXTENSIONS`に追加し、Galleryのフォルダ一覧・検索・グループ機能に自動的に乗るようにした。ブラウザは`<img>`でPSDを直接レンダリングできないため、`serve_image`/`serve_thumb`ルートで`.psd`の場合は`psd_tools`で全レイヤーを合成(非表示レイヤーは除外)した上でPNG/JPEGに変換し、mtimeベースのキャッシュキーでディスクキャッシュして配信する方式にした。情報パネルの幅・高さもPSDヘッダーから取得するようにした。
**実機テストで発覚した2件のバグとその修正**:
1. **サムネイル表示が遅く、他の無関係なPNGサムネイルまで真っ黒になる**——原因は`serve_image`/`serve_thumb`ルートがPSD合成という重いCPU処理を`async def`ハンドラ内で直接同期実行しており、aiohttpの単一スレッドイベントループ全体をブロックしていたこと。PSD1枚の合成中は他の並行リクエスト(別画像のサムネイル配信など)も完全に止まり、結果的に無関係な画像まで表示が固まって見えた。`serve_image`・`serve_thumb`・`import_psd_layers`・新設`get_psd_layers`の4ルートを`loop.run_in_executor(None, ...)`でデフォルトのThreadPoolExecutorに逃がすことで解消した。この教訓は今後の重い処理全般に適用すべき一般原則として別途メモリに記録した。
2. **単一画像「Image Edit」送信ボタンでPSDを開くと1レイヤーしかない**(「Open PSD」ボタンでは正しく全レイヤー開ける)——原因はこのボタンが常に`loadFromUrl()`(1枚のフラット画像として読み込む経路)を使っており、PSD専用のレイヤー分解経路を通っていなかったこと。サーバー上のファイルを再アップロードせず直接レイヤー分解できる新規`GET /wfm/gallery/image/psd-layers`(`GalleryService.get_psd_layers_from_path()`)を追加し、既存の`import_psd_layers()`とロジックを`_extract_psd_layers()`に共通化した上で、PSDファイルの場合はこの新エンドポイントを使うよう分岐させた。
+2 -2
View File
@@ -75,8 +75,8 @@ Model Browser, Thumbnail / Table views, Table column sort, Search & Filter, User
### Image Edit Tab (v0.3.65)
Layer-based image editor, Loading images, Open PSD button, Close button, New button, Tools, Layer panel, Duplicate layer (⧉), Layer lock, Text quality, Export, Canvas navigation, Undo / Redo
### Video Tab (v0.5.0 – v0.5.7)
Dedicated video generation UI, independent of GenerateUI, Plan / Edit subtabs, Base settings row, Asset / Project subtabs, Two center previews, First Frame / Last Frame are both optional, Semantic node lookup, not hardcoded IDs, Field highlight color, Load in Video, Frame tab, GIF tab, Playback volume
### Video Tab (v0.5.0 – v0.7.0)
Dedicated video generation UI, independent of GenerateUI, Plan subtab, Base settings row, Edit subtab, Asset subtab, Project subtab, Two center previews, First Frame / Last Frame are both optional, Semantic node lookup, not hardcoded IDs, Field highlight color, Load in Video, Frame tab, GIF tab, Playback volume
### AI TOOL Tab (v0.3.14)
4-pane layout, Translation pane, Chat pane, Chat pane — image generation via Tool Calling, Chat pane — generate_image extra parameters, TOOLS pane (VLM), TOOLS pane — shared Chat attachment, TOOLS pane (Wildcards), Chat pane — image-to-image (I2I), Chat pane — SVG generation, no ComfyUI workflow involved, Chat pane — Skills, Settings pane, Unsloth backend, Settings pane — Chat Image Generation, Settings pane — Chat I2I Generation, Settings pane — Generation, Model unload, Settings shared, Backend support, URL security, Lemonade's other endpoints (not integrated)
+8 -6
View File
@@ -268,7 +268,7 @@ An experimental batch generator: runs the workflow currently loaded in GenerateU
- **Image Edit button** — toolbar button; sends the selected image directly to the Image Edit tab as the base layer; PSD files (v0.6.0) are fully decomposed into their original layers instead of being flattened into one image
- **Send GenUI Image button** — toolbar button (next to Image Edit); uploads the selected image to ComfyUI and sets it as the input for the first LoadImage node in the GenerateUI tab; automatically switches to GenerateUI → Input → Image; requires a workflow with at least one LoadImage node to be loaded
- **Send to LI node button** (v0.5.2) — toolbar button (next to Send GenUI Image); uploads the selected image and writes its filename into the `image` widget of the node currently selected on the ComfyUI canvas (falling back to the first LoadImage-type node found) — same destination and cross-window bridge as the Image Edit tab's **Send to LI node** button (renamed from "Send to Workflow" in this same release), so both entry points now share one consistent name; requires Workflow Studio to have been opened from ComfyUI's top menu button
- **Send CC button** (v0.3.69) — toolbar button, shown only when this Gallery tab is embedded as an iframe inside ComfyUI Comic Creator (a separate custom node); sends the selected image directly into Comic Creator's currently selected panel/overlay
- **Send CC button** (v0.3.69) — toolbar button, shown only when this Gallery tab is embedded as an iframe inside ComfyUI Comic Creator (a separate custom node); sends the selected image directly into Comic Creator's currently selected panel/overlay; when the selected file is an MP4 video (v0.6.3), it is routed to Comic Creator's Layout-tab Video tool instead — inserted as a new video object in the selected panel (playable, capturable to a still frame) rather than as a flattened image; sending a video while the Image tab is the intended destination is not yet supported and shows an info toast instead
- **Search clear (✕)** — inline ✕ button appears inside the search box whenever text is entered; click to clear immediately
- **Clear all filters (✕ Clear)** — toolbar button next to the view-mode (Thumbnail/Table) switch (v0.5.2, moved from the toolbar's rightmost position so it sits with the other display-affecting controls); resets search text, tag filter, group filter, and favorites filter in one click (sort order is preserved)
- **Workflow auto-save** — images generated from the Generate UI tab have their workflow automatically saved to gallery metadata
@@ -409,18 +409,20 @@ An experimental batch generator: runs the workflow currently loaded in GenerateU
</details>
<details>
<summary><h3>Video Tab (v0.5.0 – v0.5.7)</h3></summary>
<summary><h3>Video Tab (v0.5.0 – v0.7.0)</h3></summary>
- **Dedicated video generation UI, independent of GenerateUI** — a purpose-built tab for MiniMax H3 (Image to Video), LTX-2.5 (Text / Image / First & Last Frame to Video), and Wan2.2 (Text to Video) workflows (LTX-2.5/Wan2.2: v0.5.4); does not share state with the GenerateUI tab, and model selection (UNet/CLIP/VAE/Audio VAE) is fixed to the loaded workflow's own defaults rather than editable here
- **Plan / Edit subtabs** (center panel, batch redesign in v0.5.5) — a **plan** is a sequence of timeline blocks, each a fully self-contained generation job with its own Prompt, Duration, and First/Last Image; split the timeline with **+ Split** / **+ Block** / **Delete**, then **Run** to generate every block in order (Pause/Cancel work mid-run) — a plan with a single block behaves exactly like the old one-shot form. First Image can be None, an explicit image, or "use previous block's last frame" (chaining — an explicit Last Image on the previous block always wins over extracting one from its generated output). Save / Save As / Clear a plan (`ws_videoplan_*.json`, with a PNG contact-sheet thumbnail that embeds the full plan data so dropping the image back on works too); Edit is reserved for future video-editing tools
- **Plan subtab** (center panel, batch redesign in v0.5.5) — a **plan** is a sequence of timeline blocks, each a fully self-contained generation job with its own Prompt, Duration, and First/Last Image; split the timeline with **+ Split** / **+ Block** / **Delete**, then **Run** to generate every block in order (Pause/Cancel work mid-run) — a plan with a single block behaves exactly like the old one-shot form. First Image can be None, an explicit image, or "use previous block's last frame" (chaining — an explicit Last Image on the previous block always wins over extracting one from its generated output). Save / Save As / Clear a plan (`ws_videoplan_*.json`, with a PNG contact-sheet thumbnail that embeds the full plan data so dropping the image back on works too)
- **Base settings row** (topbar, v0.5.7) — Aspect Ratio / Megapixels / Multiple / Duration (seconds) / Noise Seed on one row — Duration always reflects the currently selected block (each block keeps its own value), the rest are plan-wide — plus a second row of model-specific fields: Width / Height (become directly editable for workflows with no Resolution Selector node, e.g. Wan2.2 and LTX-2.5's First & Last Frame to Video), Turbo Mode / Strength / Steps (MiniMax H3's turbo LoRA — Turbo Mode doubles as Wan2.2's own turbo toggle, sharing one field), and Prompt Enhance (LTX-2.5 only). Every field in both rows is enabled only when the loaded workflow actually has it — see Field highlight color below (one exception: Wan2.2's Text-to-Video variant doesn't expose Noise Seed at all, so it alone leaves that field disabled)
- **Asset / Project subtabs** (sidebar, v0.5.5) — **Asset** browses generated videos through three groups: **Video Assets** (a manually-curated keeper group you organize yourself, on your own schedule), **Video Temp** (every plan run's output lands here automatically regardless of whether the plan itself was saved — a **Clear Video Temp** button in the Gallery tab's detail panel empties it in one click), and **All Video Assets** (the union of both); selecting a video shows it in the center panel's left preview and lets you tag/memo it or jump straight to the full Gallery tab. **Project** lists every saved plan file (thumbnail, block count, last updated) — click one to load it into the Plan editor, or delete it with the × button; either sidebar panel collapses back down when its own tab is clicked again
- **Two center previews** (v0.5.5) — the left preview shows either the video currently selected in the Asset subtab or whatever's dropped/picked in the **Video Source** panel to its left (**Clear** resets it to empty); the right preview always shows the most recently generated clip. The Frame/GIF tools act on whichever preview was touched most recently
- **Edit subtab** (v0.7.0) — a lightweight clip timeline for trimming and concatenating video/image clips outside of generation: add clips via the Video Source panel's **Add to Edit** button or the Asset subtab's **Send to Edit** button, drag blocks to reorder (or use the ◀/▶ toolbar buttons), Duplicate/Delete the selected clip, Clear to empty the timeline. The trim panel for a selected video clip shows a Clipchamp-style scrubber — a time ruler, a draggable playhead synced to the Source preview, and draggable in/out handles with time badges (image clips get a simple hold-duration field instead). **▶ Preview** plays every ready clip back-to-back (trimmed to its in/out points) in the result preview, and **Export** builds and runs the actual ComfyUI graph (trim → concatenate if more than one clip → save), tagging the result into Video Temp automatically — exporting more than one clip currently drops audio, since ComfyUI's concatenation node requires uniform audio across all inputs
- **Asset subtab** (center panel, next to Plan/Edit — moved here from the sidebar in v0.7.0) — browses generated videos/images through three groups: **Video Assets** (a manually-curated keeper group you organize yourself, on your own schedule), **Video Temp** (every plan run's output lands here automatically regardless of whether the plan itself was saved — a **Clear Video Temp** button in the Gallery tab's detail panel empties it in one click), and **All Video Assets** (the union of both); a filename search box and a thumbnail-grid/table (▦/☰) view toggle sit above the list (v0.7.0). Selecting an item shows it in the center preview and lets you tag/memo it, **Send to Edit** (queues it as a clip in the Edit subtab), jump straight to the full Gallery tab, or — for images only — **Set as First Image** / **Set as Last Image** (v0.7.0, uploads it straight into the currently-selected Plan block and switches to the Plan subtab)
- **Project subtab** (sidebar) — lists every saved plan file (thumbnail, block count, last updated) — click one to load it into the Plan editor, or delete it with the × button; the panel collapses back down when its own tab is clicked again
- **Two center previews** (v0.5.5) — the left preview shows either the video currently selected in the Asset subtab or whatever's dropped/picked in the **Video Source** panel to its left (**Clear** resets it to empty); the right preview always shows the most recently generated clip; both preview frames are a fixed height (v0.7.0) so switching sources never shifts the Plan/Edit/Asset panel below them. The Frame/GIF tools act on whichever preview was touched most recently
- **First Frame / Last Frame are both optional** — leaving First Image empty runs the workflow text-only (the node is simply left unconnected — a "bypass"); workflows that don't even include a LoadImage node for First Frame are supported out of the box (Wan2.2's Text-to-Video graph has neither slot at all), and a LoadImage node is only injected into the graph on the fly if an image is actually supplied
- **Semantic node lookup, not hardcoded IDs** (generalized in v0.5.4) — detects which of the three families is loaded from its subgraph's internal node types (or, for Wan2.2, the subgraph's own name — it has no distinctive internal node type), then locates its Resolution Selector and LoadImage node(s) by the subgraph's *public input label* (`prompt`, `duration`, `width`, `first_frame`, `last_frame`) rather than a fixed slot index — so it keeps working even though the three families expose those inputs under different internal names; a workflow no longer needs to match any bundled reference file's exact node IDs, and no fallback test workflow is auto-loaded on tab open
- **Field highlight color** — Prompt / Duration / First Image / Last Image / Aspect Ratio / Megapixels / Multiple / Noise Seed / Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance labels turn the same highlight color as the GenerateUI Model tab (shared setting, customizable in the Settings tab — see below) when the loaded workflow actually exposes that field; e.g. a Wan2.2 workflow (no Resolution Selector node) leaves Aspect Ratio / Megapixels / Multiple unhighlighted while Width / Height light up instead
- **Load in Video** (Workflow tab) — load any workflow containing a MiniMax H3 Image-to-Video node, an LTX-2.5 Text/Image/First&Last-Frame-to-Video node, or a Wan2.2 Text-to-Video node straight into this tab from the Workflow tab's side-panel toolbar (next to Load in GenerateUI) — starts a fresh single-block plan seeded from the workflow's own current values; unsupported workflows show an error toast instead of loading
- **Frame tab** (right panel) — captures the active preview's current playback position as a still frame: play/seek to the position you want, click **Capture Frame** (client-side canvas, no server round-trip), then **Save to Output** to write it as a PNG into ComfyUI's own Output folder (auto-numbered, same pattern as other generated images)
- **Frame tab** (right panel) — captures the active preview's current playback position as a still frame: play/seek to the position you want, click **Capture Frame** (client-side canvas, no server round-trip), then **Save to Output** to write it as a PNG into ComfyUI's own Output folder (auto-numbered, same pattern as other generated images); an optional **Add to Video Assets group** checkbox (v0.7.0) also tags the saved frame into Gallery's Video Assets group
- **GIF tab** (right panel) — converts the active preview to an animated GIF; set Start/End (seconds), FPS, and an optional Max Width, then **Convert to GIF** — the server decodes the video (PyAV) and encodes an animated GIF (Pillow), both dependencies ComfyUI itself already requires, so no ffmpeg binary or extra install is needed; the result is saved into ComfyUI's Output folder and previewed inline
- **Playback volume** — the preview player's volume is saved to the Settings tab and shared across every video player in the plugin (Video tab, Gallery tab), so it no longer resets to maximum each time a different video is opened
+291
View File
@@ -0,0 +1,291 @@
# Video Editサブタブ「簡易動画編集機能」実装計画
## Context
Video タブは Plan(バッチ動画生成)/ Asset・Project(生成済み動画の一覧)まで実装済みだが、Edit サブタブは `templates/index.html:2895` の空div `#wfm-video-subtab-edit`(「Editing tools coming soon」のプレースホルダーテキストのみ)で、JSロジックは一切無い。ユーザーからは「Adobe Premiereのような簡易動画編集機能」を追加したいという要望があり、調査の結果ComfyUI Core 0.35.0〜0.36.0(2026年9月時点の最新)で `VideoSlice`/`VideoTrim`/`VideoCrop`/`ConcatenateVideo` 等のネイティブ動画編集プリミティブが追加されたばかりであることが判明した。これらを活用しつつ、wf-manager独自のタイムラインUIを被せることで、フルスクラッチでの動画処理実装を避けつつ「複数クリップの配置・トリム・結合」という編集の核となる機能を提供する。
**方針確認済み(ユーザー承認):**
- MVPスコープは最小限(タイムライン配置・トリム・結合書き出しのみ)とし、クロップ・テキストオーバーレイ・BGM合成は明確にPhase 2以降の拡張として切り離す。
- グラフ組立(トリム/クロップ/結合)はComfyUIワークフローに丸投げする方式(Plan tabの`video-workflow.js`と同じ`/prompt`実行基盤を再利用)で進める。`VideoTrim`/`VideoCrop`がexperimental扱いであることのAPI変更リスクは、Phase 0での`/object_info`検証とクラス名参照で軽減する。
実装は下記のPlanエージェント設計をベースに、MVPスコープをPhase 1(タイムライン+トリム+結合)のみに絞り込んで進める。
---
## 1. スコープ定義
### 設計原則(切り分けの判断基準)
| 種別 | 判断基準 | 実装場所 |
|---|---|---|
| **プレビュー/操作UI**(scrub再生、タイムライン上でのドラッグ、トリムハンドル、テキスト位置決めなど、ユーザーが「見ながら触る」もの) | ブラウザの`<video>`/`<canvas>`だけで完結し、即座にフィードバックが必要 | wf-manager独自JS(video-edit-tab.js) |
| **実際の書き出し処理**(トリム確定、複数クリップ結合、クロップ確定、テキスト焼き込み) | 重い処理・GPU不要・単純なメディア操作で、ComfyUI Coreの新ノード(VideoSlice/VideoTrim/VideoCrop/ConcatenateVideo)がほぼそのままカバーする | ComfyUIワークフローを動的組立して`/prompt`に投げる(Plan tabのvideo-workflow.jsパターンを踏襲) |
| **既存方針(PyAV+Pillowのみ、ffmpeg非依存)で完結できないもの**(テキスト/字幕の焼き込み、BGM音量ミックス、簡単なフェード) | ComfyUI Coreノードにも無く、かつ静止画向けtext-overlay系カスタムノードのロジックを流用できる規模 | wf-manager独自Python(video_service.py拡張、PyAV decode + Pillow ImageDraw合成 + PyAV encode) |
| **サムネイル/ファイル一覧/タグ管理** | 既存Galleryインフラで完結 | 既存流用(新規実装なし) |
### MVP(初回リリース、承認済み: 最小限スコープ)
以下の1〜4のみを初回リリース対象とする。クロップ/テキストオーバーレイ/BGM合成/プレビュー高度化は明確にPhase 2以降へ切り出す。
1. **タイムラインへのクリップ配置・並べ替え**
- Asset タブ / Gallery からドラッグ or 「Editへ送る」ボタンで動画をタイムラインに追加。
- 水平方向に複数クリップを並べたシンプルな1トラック構成(Adobe Premiereの「V1」トラック1本のみ、複数トラック無し)。
- ドラッグで順序入れ替え、削除、複製。
2. **クリップ単位のトリム(開始/終了)**
- 各クリップサムネイル上でハンドルをドラッグしてin/outを指定 → プレビューは`<video>`要素のcurrentTimeシークのみ(デコード不要、軽量)。
- 書き出し時にComfy Core `VideoSlice`("Trim Video")ノードで実処理。
3. **複数クリップの結合書き出し**
- タイムライン順に`ConcatenateVideo`ノードをAutogrowで連結し1本のVIDEO出力に。
4. **プレビューと書き出し**
- プレビューはMVPでは「各クリップを順番に`<video>`要素で連続再生する疑似プレビュー」(トリム区間のみ再生してクリップ切り替え)に留める。真の合成プレビューは行わない。
- 「書き出し」ボタン押下でComfyUIワークフロー(`VideoSlice`×N → `ConcatenateVideo`(Autogrow) → `SaveVideo`)を動的組立し`/prompt`に投げ、進捗はWebSocketで表示、完了後Galleryの`VIDEO_GROUP`に自動登録。
### Phase 2以降(MVP対象外、将来拡張として明記)
- **クリップ単位の空間クロップ**: 矩形選択UI(Image Edit Tabのキャンバス選択パターンを流用)→ 書き出し時に`VideoCrop`ノードへ座標を渡す。
- **簡易テキストオーバーレイ(クリップ単位、固定位置・フェード無し)**: テキスト内容・フォントサイズ・色・位置(9グリッドアンカー)・表示区間(開始秒-終了秒)を指定。書き出しはPyAVでフレームデコード→対象区間のフレームだけPillow ImageDraw.textで焼き込み→再エンコード(wf-manager独自Python実装。ComfyUI Coreに動画テキストオーバーレイノードは無いため)。
- **BGM/音声トラック1本の合成**: 元動画の音声をmute/keep選択 + 1本のBGM音声ファイルを全体に重ねる(音量スライダーのみ、ミキシングはPyAVのAudioResampler+単純加算 or `CreateVideo`のcomplete_audio差し替え機能で代替)。複雑なマルチトラックオーディオミキシングは対象外。
- 複数トラック(V1/V2でのピクチャーインピクチャー、オーバーレイ合成)
- クリップ間トランジション(クロスフェード等) — フレーム単位のアルファブレンドはPyAVで可能だが計算コストが高く、CPUのみだと低速。GPU処理が要るなら別途ComfyUIノード化を検討。
- 波形表示付きオーディオトラック編集
- キーフレームアニメーション(テキストの移動/フェードイン等)
- Undo/Redo履歴、複数プロジェクトの保存/読込(Video Planの`video_plan_service.py`と同様の永続化)
- リアルタイム合成プレビュー(WebCodecs APIによるブラウザ内デコード合成、または低解像度プロキシファイルを都度サーバー生成してプレビュー用に配信)
---
## 2. アーキテクチャ
> **補足(実際のサブタブ構造)**: Videoタブは単純な「Plan/Asset/Edit」3分割ではなく、中央ペインが Plan/Edit の2-way切替(`_initCenterSubtabToggle()`, `static/js/video-tab.js:37`)、サイドバーが Asset/Project の独立ペア(`_initSidebarSubtabToggle()`, 同ファイル55行目)という構成。エントリポイントは `static/js/video-tab.js:317` の `export function initVideoTab()` で、ここに `initVideoEditTab()` の呼び出しを追加する。
### フロントエンド(JS)
新規ファイル: `static/js/video-edit-tab.js`
- `class VideoEditTab`(Image Edit Tabの`class ImageEditTab`パターンを踏襲。単一グローバルインスタンスをexportする形も選択可)
- `constructor()`: タイムライン状態(`this.clips = []`、各要素は`{ sourceRef, inPoint, outPoint, cropRect, textOverlay, id }`)、選択中クリップID、DOM参照を初期化。
- `init()`: DOM生成・イベント配線のエントリポイント。`video-tab.js`の`initVideoTab()`から`initVideoEditTab()`として呼ばれる形にする。
- `_setupActionBar()`: Image Edit Tab 1385行目のアクションバー実装を参考に「クリップ追加」「書き出し」「プレビュー再生/停止」ボタン群を構築。
- `_setupTimelinePanel()`: レイヤーパネル(`_setupLayerPanel()` 2194行目)のリスト+サムネ+ドラッグ並べ替えパターンを、縦のレイヤーリストではなく横のタイムラインクリップ列に転用。
- `_setupTrimHandles()`: pointerdown/move/upベースのドラッグ操作(1130-1249行目のポインタイベント処理パターン)をトリムハンドルのドラッグに転用。
- `_setupCropOverlay()`: 同じくpointerイベントパターンをクロップ矩形選択に転用(レイヤーごとに独立canvasを持つ構造は流用しないが、矩形描画のオーバーレイcanvas1枚で足りる)。
- `_setupTextOverlayPanel()`: テキスト内容/フォント/色/アンカー/表示区間の入力フォーム。プレビューは選択中クリップの`<video>`上にCSS絶対配置したdiv要素でオーバーレイ表示(実際の焼き込みはサーバー側、プレビューは近似でよい)。
- `_buildExportWorkflow()`: タイムライン状態からComfyUIワークフローJSON(内部APIフォーマット)を動的組立。`video-workflow.js`の`injectFrameNode()`のノード注入パターン(last_node_id/last_link_id採番、links[]整合性維持)を流用し、`LoadVideo → VideoSlice → (VideoCrop) → ConcatenateVideo(Autogrow) → SaveVideo`のグラフを構築。
- `_exportTimeline()`: `comfyUI.queuePrompt()`/`comfyUI.trackProgress()`(comfyui-client.js既存メソッド、Plan tabと同じ呼び出し方)でグラフを実行し、進捗表示・完了後にGallery登録。
- `_applyTextOverlayJob()`: テキストオーバーレイがある場合のみ、結合済み動画に対して追加で`/api/wfm/video/edit/overlay-text`(新設)を呼ぶ後処理ステップ(ComfyUIグラフでは焼き込めないため、書き出しフローの最終段に独立したPython後処理を挟む二段構成)。
- 既存ファイルへの変更:
- `static/js/video-tab.js`: `initVideoEditTab()`のimportと`initVideoTab()`内呼び出しを追加。`_applyVideoI18n()`にEdit用キーを追加。
- `templates/index.html`: `#wfm-video-subtab-edit`内にタイムライン/アクションバー/クロップオーバーレイ/テキストパネル用のDOM骨格を追加(Plan/Assetサブタブの既存マークアップ構造に合わせる)。
- `static/js/i18n.js`: `videoEditPlaceholder`を削除し、新規i18nキー群(`videoEditTimeline`, `videoEditTrim`, `videoEditCrop`, `videoEditTextOverlay`, `videoEditBgm`, `videoEditExport`等、英/日/中3言語)を追加。
- `static/css/video-tab.css`(存在すれば。無ければ新規`video-edit-tab.css`): タイムラインのクリップブロック、トリムハンドル、クロップオーバーレイのスタイル。
- Asset→Edit連携用の変更:
- `static/js/video-asset-tab.js`: 詳細パネル(`_renderDetail()`)に「Editへ送る」ボタンを追加。クリック時、選択中動画の`{filename, subfolder, type}`または`{kind:"local", file}`参照を`video-edit-tab.js`のエクスポート関数(例: `addClipFromAsset(ref)`)に渡し、Editサブタブに切り替えてタイムライン末尾に追加。
### バックエンド(Python)
判断基準: **ComfyUIワークフローに丸投げできる処理(VIDEO型を保つ、GPU不要でもCPUノードとしてグラフ内で完結できる処理)は`/prompt`実行に任せ、グラフ側に存在しない処理(テキスト焼き込み、音声ミックス、詳細メタ取得)だけを独自Pythonで実装する。** 理由: ワークフロー実行に丸投げすることで実行キュー管理・WebSocket進捗通知・キャンセル(`interrupt`)・履歴(`/history`)を無料で使い回せる一方、独自Python実装は同期/非同期の進捗通知を自前で作る必要があるため、既存インフラで代替できるものは極力グラフに寄せる。
- `py/routes/video_routes.py` 追加エンドポイント:
- `POST /api/wfm/video/edit/probe`: アップロード済み/output上の動画の基本メタ(duration, fps, width, height, has_audio)をPyAVで取得。タイムラインUIがクリップ追加時に必要な長さ・解像度をComfyUIの`/prompt`実行なしで即座に得るため(`GetVideoComponents`ノードを都度実行するのは重く実行キューも消費するため避ける)。
- `POST /api/wfm/video/edit/overlay-text`: 結合済み動画1本 + テキストオーバーレイ指定リスト(区間・アンカー・文字列・色・フォントサイズ)を受け取り、PyAVでデコード→対象区間のみPillow ImageDraw合成→PyAV(av.open(mode="w"))で再エンコードしoutputへ保存。`video_service.convert_to_gif()`のデコード/エンコードパターンを流用。
- `POST /api/wfm/video/edit/mix-audio`(BGM合成が`CreateVideo`ノードのcomplete_audio差し替えだけでは足りない場合の予備、例えば音量調整付き重ね合わせが必要な時): PyAVのAudioResamplerで元音声とBGMをリサンプル→単純加算ミックス→動画に再アタッチ。
- Phase 1では上記のうち`probe`のみ必須、`overlay-text`はテキストオーバーレイ機能実装時に追加、`mix-audio`は`CreateVideo`の`complete_audio`で足りるなら不要(後述リスク参照)。
- `py/services/video_service.py` 追加メソッド:
- `probe_video(path) -> dict`: `av.open()`でstreams[0]の`duration`, `average_rate`, `width`, `height`、`streams.audio`の有無を返す。
- `overlay_text_on_video(src_path, overlays, fps=None) -> dict`: 既存`convert_to_gif`と同じ`_resolve_media_path`を使った安全なパス解決 → フレームループでtがoverlayの区間に該当する時だけPillowで文字を描画 → `av.open(dst, mode="w")`で同じcodec/fpsで書き出し。既存クラスの`_resolve_media_path()`を再利用。
- `mix_audio(...)`: 必要になった場合のみ追加。
- ワークフロー動的組立は**フロントエンドJS側**(`_buildExportWorkflow()`)で行い、バックエンドは実行そのものに関与しない(Plan tabと同じ役割分担: `video-workflow.js`はJSでグラフJSONを操作し、`comfyUI.queuePrompt()`で`/prompt`に投げるのみ)。バックエンドに「ワークフロー組立API」を新設する必要は無い。
### 判断基準まとめ(再掲)
- VIDEO型のまま完結する操作(トリム/クロップ/結合/保存) → ComfyUIグラフ(フロントJSで組立、`/prompt`実行)
- VIDEO型を抜けてピクセル単位の追加合成が要る操作(文字焼き込み、音声ミックス) → wf-manager独自Python(PyAV+Pillow)
- 操作中のインタラクティブ操作(scrub、トリムハンドルのドラッグ、矩形選択) → ブラウザJSのみ、サーバー往復なし
---
## 3. 既存資産の再利用ポイント(具体的な参照箇所)
| 転用元 | 参照箇所 | 転用先 |
|---|---|---|
| Image Edit Tab アクションバー | `static/js/image-edit-tab.js:1385` `_setupActionBar()` | video-edit-tab.jsのツールバー(クリップ追加/書き出し/再生ボタン) |
| Image Edit Tab レイヤーパネル | `static/js/image-edit-tab.js:2194` `_setupLayerPanel()`(リスト/サムネ/透明度スライダー) | タイムラインのクリップリストUI(サムネ表示・並べ替え・削除) |
| Image Edit Tab pointerイベント | `static/js/image-edit-tab.js:1130-1249` | トリムハンドルドラッグ、クロップ矩形選択のドラッグ操作 |
| Image Edit Tab レイヤー合成構造 | `static/js/image-edit-tab.js:2035,2067,2081` | (参考程度)テキストオーバーレイのプレビュー用オーバーレイdiv重畳の考え方 |
| Gallery mp4サムネ/プレビュー | `static/js/gallery-tab.js:63` `isVideoFile()`、`972-985,1750-1766` `<video controls>` | クリップサムネイル生成、プレビューエリアの`<video>`要素の扱い |
| Gallery mp4サーバー側サムネ | `py/services/gallery_metadata.py:1349-1364` `serve_thumbnail`(PyAVで先頭フレームJPEG化) | クリップ追加時のサムネイル取得APIとして直接再利用可能(新規実装不要、`/wfm/gallery/image/thumb`をそのまま叩く) |
| Gallery mp4メタ | `py/services/gallery_metadata.py:766` `_read_mp4_metadata()` | `probe_video()`実装の参考(既存関数を直接呼ぶかロジック共有できないか要確認) |
| video-workflow.js ノード検出/注入パターン | `static/js/video-workflow.js` `locateVideoModelNodes()`, `injectFrameNode()`(last_node_id/last_link_id採番、links[]整合性) | `_buildExportWorkflow()`でVideoSlice/VideoCrop/ConcatenateVideoノードを動的追加する際のID採番・リンク整合性ロジックをそのまま流用 |
| comfyui-client.js 実行基盤 | `static/js/comfyui-client.js:196` `queuePrompt()`, `217` `trackProgress()`, `312` `generate()` | 書き出し実行・進捗表示(新規実装不要) |
| Video Asset Galleryグループ | `static/js/video-asset-tab.js` の`VIDEO_GROUP`/`VTEMP_GROUP`活用パターン | 書き出し完了後の動画を`VIDEO_GROUP`へ自動登録する処理の参考 |
| video_service.py デコード/エンコードパターン | `py/services/video_service.py:60` `convert_to_gif()`(PyAV decode→Pillow処理→再エンコード、`_resolve_media_path`によるパストラバーサル対策) | `overlay_text_on_video()`実装のテンプレートとしてほぼそのまま流用 |
---
## 3.5. 外部カスタムノードの参考実装(追加調査、ユーザー指定4件)
Video Edit実装の設計判断を補強するため、既に「フルスクリーンタイムラインエディタ」を実装している既存カスタムノードを調査した。**これらをそのまま依存として組み込むのではなく、UI/UX設計とノード分割方針の参考にする**(wf-managerはComfyUI Coreの`VideoSlice`/`ConcatenateVideo`丸投げ方針を維持するため、方式は異なる)。
| リポジトリ | 関連度 | 参考にすべき点 |
|---|---|---|
| [SonderSaid/ComfyUI-Sonder-Editor](https://github.com/SonderSaid/ComfyUI-Sonder-Editor) | **高** | マルチレーン(Video/Audio/Prompt/Guide/Driverレーン)タイムラインUI、クリップのドラッグ/トリム/分割/ミュート、レーンのロック/非表示など、Premiereライクな編集UIの完成度が高い実装例。ただし**FFmpeg 7.0以上を必須依存**としており、wf-managerの「ffmpeg非依存(PyAV+Pillowのみ)」方針とは真逆。UIレイアウト(左サイドバー=ギャラリー、中央=ビューポート+トランスポート、下部=マルチレーンタイムライン)は`video-edit-tab.js`のDOM構成の参考にする価値が高いが、実装(FFmpeg CLI呼び出し)はそのまま流用しない。 |
| [shootthesound/ComfyUI-H3Studio](https://github.com/shootthesound/ComfyUI-H3Studio) | **高** | MiniMax H3特化の統合編集ツール。単一ノードから「⤢ open timeline editor」ボタンでフルスクリーンタイムラインを起動する導線、クリップのトリム/クロスフェード/音声ミックスをまとめた「リール」書き出し機能、フィルムストリップ表示・波形表示が参考になる。**「追加のPythonライブラリ不要」と明記**されており、wf-managerの依存最小化方針と親和性が高い(実装詳細は非公開のため、"ノードのカスタムウィジェットからフルスクリーンモーダルを開く"というUIパターンのみ参考にする)。 |
| [domg73/ComfyUI-LoadVideoCrop](https://github.com/domg73/ComfyUI-LoadVideoCrop) | **中(Phase 2クロップ機能に直結)** | 公式`LoadVideo`を拡張し、動画プレビュー上でWYSIWYGにクロップ矩形を描画できる`Load Video Crop`ノード。アスペクト比ロック(1:1/2:3/3:2/3:4/4:3/9:16/16:9/21:9/Free)、`start_time`/`duration`/`strict_duration`によるロード時トリムも兼備。**「追加依存ライブラリ不要」**と明記。Phase 2の`_setupCropOverlay()`実装時、このノードの隠し入力設計(`crop_x/crop_y/crop_w/crop_h`を0..1正規化値で渡す)をComfyUI Core `VideoCrop`ノードとのパラメータ形式比較の参考にする。ノード自体を依存に追加するかはPhase 0で`VideoCrop`(Core)とどちらが安定・高機能か比較検討する。 |
| [astropuzzo/ComfyUI-MiniMax-H3-Image-Studio](https://github.com/astropuzzo/ComfyUI-MiniMax-H3-Image-Studio) | **低** | MiniMax H3モデルを使った**静止画**のT2I/I2I/参照編集ツールで、動画のタイムライン編集や結合とは無関係(対象読者はH3の画像生成ワークフロー利用者)。Video Edit実装への直接的な参考価値は無いため、調査対象から除外し将来のGenerateUI/画像生成系機能検討時の参考候補としてのみ記録する。 |
**設計への反映:**
- `_setupTimelinePanel()`(video-edit-tab.js)のDOM構成は、Sonder Editor/H3Studioのレイアウト(サイドバー=クリップ一覧、中央=プレビュー+トランスポート、下部=タイムライン)を踏襲する。ただし将来のマルチレーン拡張(Phase 2以降のBGMトラック等)を見越し、MVPの単一トラックでも「レーン」という概念でデータ構造を設計しておく(`this.clips`を`this.lanes = [{type:"video", clips:[...]}]`のような形にしておくと将来拡張が容易)。
- Phase 2のクロップUIは、LoadVideoCropの「正規化座標(0..1)でのクロップ矩形」という設計をそのまま踏襲し、ComfyUI Core `VideoCrop`ノードの実際のINPUT_TYPES(Phase 0で`/object_info`確認)と突き合わせて座標系を合わせる。
- H3Studioの「ノードのカスタムウィジェットからフルスクリーンモーダルを開く」という導線は、wf-managerでは既にVideo Editが独立サブタブとして存在するため直接は不要だが、将来「ワークフローグラフ上のノードからEditタブへジャンプする」ショートカットを追加する際の参考にする。
---
## 4. 段階的な実装ステップ(Phase分け)
### Phase 0: 下調査・技術検証(実装前必須)— **完了(2026-09-16、ComfyUI_5実機・ポート8189で検証済み)**
**確定事項(`_buildExportWorkflow()`実装時はこの仕様に厳密に従うこと):**
1. **【2026-09-16 訂正】`VideoSlice`は「クラス名にスペースが入る」ため`/object_info/VideoSlice`が空に見えていただけで、実際には`"Video Slice"`(スペース込み)という正式なclass_typeで存在する。** ソース(`comfy_extras/nodes_video.py:448`)の`node_id="Video Slice"`を確認して判明。**トリムはこちらを使う** — `video`/`start_time`(FLOAT)/`duration`(FLOAT, 0で無制限)/`strict_duration`(BOOLEAN)というフラットな入力のみで、`VIDEO_EDIT`型のネスト構造が一切無く、`experimental`でもない。実機で`start_time=2.0, duration=3.0`を指定し、出力が実際に3.0秒になることをPyAV probeで確認済み(**当初の`VideoTrim`検証は`execution_success`だけを見て「動いた」と誤判定していた——後述の訂正参照**)。
2. **【訂正の経緯・重要な教訓】`VideoTrim`の`trim`入力(`VIDEO_EDIT`型)に一見素直なフラット値`{"start_time":.., "duration":..}`を渡すと、`node_errors`無しで`execution_success`するが、実際には一切トリムされず元動画がそのまま出力される(サイレント無視)。** 原因はソース(`comfy_extras/nodes_video.py:524`)の`execute()`が`(trim or {}).get("trim")`と一段余計にネストを剥がしてから`apply_video_trim()`に渡す実装になっており、`apply_video_trim()`は`trim=None`のとき`start_time=0.0, duration=0.0`とみなして**無条件に元動画をそのまま返す**(`comfy_extras/nodes_video.py:417-424`)ため。正しく`VideoTrim`を使うならフラットではなく**二重に入れ子**にした`{"trim": {"start_time": 0.0, "duration": 1.5}}`が必要。ただし本実装ではより単純な`Video Slice`を採用したため、`VideoTrim`は不使用。**教訓: `execution_success`は「グラフの型検証を通った」ことしか意味せず、パラメータが実際に意図通り効いたかは出力を実際にprobeして確認しない限り分からない。** 以後の実機検証では必ず出力の実測値まで確認すること。
3. **`VideoCrop`の`crop`入力も`VideoTrim`と同じ二重ネスト`.get("crop")`パターン(`comfy_extras/nodes_video.py:555`)。** Phase 2で採用する場合は`{"crop": {"x":0,"y":0,"width":W,"height":H}}`のように二重に入れ子にする必要がある(`VideoCrop`はスペース無しの`"VideoCrop"`のままで、`Video Slice`のような別名は無い)。Phase 2着手時に必ず出力を実測して再確認する。
4. **`ConcatenateVideo`の`videos`(`COMFY_AUTOGROW_V3`)は、ネストしたJSONオブジェクトではなく、ドット区切りの単一文字列キーをinputsのトップレベルに並べる。** これが最大のハマりどころで、`{"videos": {"video0": [...]}}` 等の直感的なネスト表現は**すべて`required_input_missing`で弾かれる**。正しい形式:
```json
"inputs": {
"videos.video0": ["<node_id>", 0],
"videos.video1": ["<node_id>", 0],
"codec": "auto"
}
```
(0始まり、`prefix + index`を単純結合した文字列がそのままキー名。ComfyUI Core `comfy_api/latest/_io.py`の`Autogrow.TemplatePrefix`/`finalize_prefix()`のドット結合ロジックに由来)。実機で2クリップ結合の`execution_success`を確認済み。
5. **`ConcatenateVideo`は解像度不一致で実行時ハードエラーになる。** 実機で960x540と1024x576の2クリップを結合させたところ`ValueError: Accumulated videos have incompatible frame dimensions`で失敗(`comfy_extras/nodes_video.py:178`)。事前チェック無しでの結合は失敗するため、**Phase 1のタイムラインUI側で解像度不一致クリップの警告表示・結合前チェックを必須実装**とする(リスク節で「推奨」としていたものを「必須」に格上げ)。
6. 動画アップロードは標準の`/upload/image`エンドポイント(`OPTIONS`で200確認済み)をそのまま使う想定(`LoadVideo`の`file`ウィジェットが`video_upload: true`を持ち、Core LoadVideo/VHS双方がこのエンドポイントを動画にも流用する既知の挙動)。Phase 1実装時に実際のアップロード→`LoadVideo`参照までを通しで確認する。
7. `LoadVideo`の`file`はCOMBO(inputフォルダ内動画ファイル名の列挙)。Asset/GalleryからEditタブへ渡す動画がComfyUI input配下に無い場合(Gallery出力やVTEMP_GROUP由来)は、書き出し前に`/upload/image`でinputへコピーしてからファイル名を`LoadVideo.file`に渡す必要がある。
### Phase 1: MVP基盤(タイムライン表示・単純トリム結合書き出しのみ)
- 新規: `static/js/video-edit-tab.js`(クラス骨格、タイムラインリスト、クリップ追加/削除/並べ替え)
- 変更: `templates/index.html`(Edit subtab DOM骨格)
- 変更: `static/js/video-tab.js`(init呼び出し追加)
- 変更: `static/js/i18n.js`(新規キー)
- 新規API: `py/routes/video_routes.py`に`/api/wfm/video/edit/probe`追加
- 変更: `py/services/video_service.py`に`probe_video()`追加
- 変更: `static/js/video-asset-tab.js`(「Editへ送る」ボタン)
- 実装内容: クリップ追加→トリムハンドルUI→書き出し(VideoSlice+ConcatenateVideo+SaveVideoのグラフ組立て`/prompt`実行)まで通す。
### Phase 2: クロップ機能
- video-edit-tab.jsに`_setupCropOverlay()`追加
- `_buildExportWorkflow()`を拡張し`VideoCrop`ノードを挿入
### Phase 3: テキストオーバーレイ
- video-edit-tab.jsに`_setupTextOverlayPanel()`追加
- 新規API: `/api/wfm/video/edit/overlay-text`
- `video_service.py`に`overlay_text_on_video()`追加
- 書き出しフローを「グラフ実行→結合済みファイル取得→overlay-text後処理呼び出し」の2段構成に変更
### Phase 4: BGM/音声合成
- `CreateVideo`ノードのcomplete_audio機能で足りるか検証した上で、足りなければ`mix-audio` API追加
- video-edit-tab.jsにBGMアップロード/音量UI追加
### Phase 5: 仕上げ・永続化(任意)
- タイムライン状態の保存/読込(`video_plan_service.py`と同様のJSON永続化を検討、`VideoEditProjectService`として新設するか判断)
- Undo/Redo(将来拡張スコープだが、Phase 5で簡易版のみ着手する場合はここ)
---
## 5. リスク・技術的懸念点
1. **VideoTrim/VideoCropのexperimental扱いリスク**
- ComfyUI Core側で今後のマイナーバージョンでノード名・入出力仕様が変更される可能性がある。`io.VideoEdit`ウィジェット型はフロントエンドのインタラクティブUI前提の設計であり、wf-managerは独自UIから直接パラメータをJSON投入する形になるため、公式フロントエンドUIの挙動と乖離があっても気づきにくい。
- 対策: 表示名ではなくノードのクラス名で参照する。最終的にトリムは`experimental`でも`VIDEO_EDIT`ネストでもない`"Video Slice"`(スペース込みのclass_type、`node_id="Video Slice"`)を採用したため、この項目のリスクは実質解消した。Phase 2で`VideoCrop`(こちらは`experimental`かつ`VIDEO_EDIT`の二重ネスト、代替ノード無し)を使う際は本リスクが残るため、必ず出力を実測確認する。
- CLAUDE.mdの「ワークフローJSON整合性ルール」(last_node_id/last_link_id、links[]の3箇所整合)を`_buildExportWorkflow()`実装時に厳守する。
2. **ffmpeg非依存方針の機能的限界**
- トランジション(クロスフェード等)やアルファブレンド合成はComfyUI Coreノードに無く、PyAVで自前実装するとフレーム単位のデコード→NumPy/Pillow合成→再エンコードとなり、CPU処理でかなり低速になる(特に長尺・高解像度動画)。MVPではトランジション無しとし、将来拡張でも「対応するなら低解像度プレビュー限定」等のスコープ限定を検討すべき。
- コーデック非互換なクリップ同士の結合は`ConcatenateVideo`が自動的に一度デコードしてから再結合するため、異なる解像度/フレームレートのクリップを混在させると処理コストが跳ね上がる可能性がある。タイムラインUI側で「解像度/fps不一致クリップ」を警告表示する簡易チェックをPhase 1に含めることを推奨。
- テキストオーバーレイの再エンコード(Phase 3)は全フレームを一度デコード・Pillow処理・再エンコードするため、長尺動画では書き出しに時間がかかる。プログレス表示(Frame N/Total等)をAPIレスポンスではなくポーリング or 簡易WebSocket通知で出す設計を検討(現状の`convert_to_gif`は同期一括処理でプログレス無し、これをそのまま踏襲すると長尺でUIが固まって見える点に注意)。
3. **既存Video Plan/Assetタブとのデータ連携**
- AssetタブからEditタブへの動画受け渡しは、Asset側が持つ参照形式(Galleryの絶対パス`img.path`)とEdit側のタイムラインが必要とする形式(ComfyUIの`{filename, subfolder, type}`、またはローカルFileオブジェクト)の変換が必要。`video-asset-tab.js`の`_loadIntoSourcePreview()`が既にこの変換(Blob取得→File化→`kind:"local"`)を行っているので、同じパターンをEditタブのクリップ追加処理でも使う。ただし書き出しグラフの`LoadVideo`ノードはComfyUI input/output/temp配下のファイルを期待するため、ローカルFileの場合は動画アップロードAPIを経由してから`LoadVideo`に渡す必要がある(Phase 0の技術検証項目)。
- Video Planタブが生成した動画は`VTEMP_GROUP`に入るため、Editタブの「クリップ追加」ソースとして「Video Plan実行結果」も選択できるようにする導線(Assetタブ経由で十分か、Editタブ内に直接「最近の生成結果」ショートカットを設けるか)はUX判断が必要。
- タイムライン編集結果を保存/読込する永続化機能(Phase 5想定)を作る場合、`video_plan_service.py`のディレクトリ構成・ファイル命名規則を踏襲し、別サービスクラス(`VideoEditProjectService`)として分離するか、既存`VideoPlanService`を拡張するかの設計判断が必要(データモデルが「バッチ生成の入力」と「編集後のタイムライン状態」で意味的に異なるため、別クラス推奨)。
4. **並行実行時のリソース競合**
- Edit書き出しはPlan tabのバッチ生成と同じ`/prompt`キューを使うため、Plan実行中にEdit書き出しを投げると同じキューに並ぶ。ユーザーへの「実行中」表示や二重実行防止のUI制御をPlan tab側の既存パターン(生成中はボタンdisable等)に倣って実装する。
5. **開発・デプロイ運用(CLAUDE.md既存ルール)**
- 開発元リポジトリ(`c:\Users\statsu-11\Desktop\now_work\comfyUI-wf-maneger\ComfyUI-Workflow-Studio`)と実行時`custom_nodes`(`...\ComfyUI_5\custom_nodes\comfyui-workflow-studio`)は別実体。実機確認のたびに同期スクリプトでの全体反映が必要(部分同期は原因不明のエラーの元)。
- `_buildExportWorkflow()`実装時はワークフローJSON整合性ルール(`last_node_id`/`last_link_id`が最大値以上、`links[]`とノード両端の`links`/`link`の3箇所整合)を厳守する。
- Python側変更(`video_service.py`, `video_routes.py`)反映にはComfyUI完全再起動が必須(`py_compile`キャッシュではなくインポート自体が起動時一度きりのため)。
---
## 6. UI再設計(2026-09-16、ユーザー指示によりPlanタブ寄りに変更)
初回MVP実装(縦リスト+各行ボタン方式)を、以下のとおりPlan subtabのUIパターンに揃える形で再設計・実機確認済み。
- **タイムライン**: 縦リスト(`wfm-video-edit-clip-list`)から、Planタブと同じ横トラック構造(`wfm-video-edit-timeline-track`)へ変更。ただしPlanのブロックは`flex-grow`でトラック幅いっぱいに引き伸ばされるのに対し、Editのブロックは実秒数×固定px/秒(20px/秒、最小56px)の幅を持ち**左詰め**で並ぶ(空きトラックはそのまま空く)。
- **並べ替えの共有化**: 各クリップ行が持っていた▲▼⧉✕ボタンを廃止し、タイムライン直下の共有ツールバー(◀ 左へ移動 / ▶ 右へ移動 / 複製 / 削除 / クリア)に統合。Planタブの「+ Split / + Block / Delete」ツールバーと同じ「選択中の対象に対して働く共通ボタン」方式。
- **ドラッグ並べ替え**: ネイティブHTML5 D&Dでブロック同士のドラッグ&ドロップによる並べ替えにも対応(ボタンと併用可)。`_reorderByDrop()`は「削除→対象の新インデックスを探索→挿入」の順で行い、素朴な二段splice実装にありがちなオフバイワンを回避している。
- **Clearボタン新設**: タイムライン全体をクリアする専用ボタン(`videoEditConfirmClear`で確認ダイアログ表示)。
- **上部「動画ソース」パネルとの連携**: 自動連携ではなく、Video Sourceパネルに明示的な「Editに追加」ボタン(`#wfm-video-source-add-to-edit`)を新設。Frame/GIF目的の単発動画ドロップでEditタイムラインが意図せず汚れないよう、ユーザーが選択・確認済み。ローカルFile/サーバー参照(`kind:"local"`/`"input"`/`"output"`)の両方に対応し、クリックでEditサブタブへ自動切替。
- Frame抽出・GIF化(右ペイン、単独動画操作)とEdit(タイムライン編集・結合、複数クリップ操作)の役割分担は従来通り変更なし——ユーザーからの確認事項としてこの分離を維持している。
実機(ComfyUI_5・ポート8189、Kapture)で以下を確認済み: 左詰めタイムライン描画、Asset選択→「Editに追加」経路、2クリップの◀移動での順序入れ替え、複製、削除、クリア(確認ダイアログのi18n適用含む)、クリア後の単一クリップ書き出し(22.13秒で正常出力)。
## 7. レイアウト修正(2026-09-16、追加指示)
UI再設計直後、実機で「空のタイムライン/書き出しパネルが中央に縮んで表示され、Planタブのように横幅いっぱい・右端固定にならない」という不具合をユーザーが発見。原因はCSSのバグで、修正内容は以下の3点。
1. **Editタブ自身のドロップゾーンを削除**: `#wfm-video-edit-drop-zone`をtemplates/index.htmlから削除し、`video-edit-tab.js`の`_wireAddClipDropZone()`も削除。クリップ追加は Asset タブの「Editへ送る」ボタンと、Video Sourceパネルの「Editに追加」ボタン(第4節参照)の2経路に一本化。
2. **【根本原因】`static/css/video-tab.css`に旧プレースホルダー時代の重複`.wfm-video-edit-panel`ルールが残存していた。** Edit サブタブが「Editing tools coming soon」という1行プレースホルダーだった頃の`display:flex; align-items:center; justify-content:center; border:1px dashed ...`というルール(中央に1行だけ表示するための定義)が、実装を追加した後も削除されておらず、CSSカスケード順(後勝ち)で新しい`.wfm-video-edit-panel { padding: 0 16px 16px; }`の直後に来て`align-items:center`等を上書きし続けていた。これによりタイムライン・トリムパネル・書き出しパネルの全てが横方向に縮んで中央寄せされていた。該当ルールを完全に削除して解消。
3. `.wfm-video-edit-timeline-track`に`width:100%; box-sizing:border-box; flex:none;`を明示し、クリップの有無に関わらずトラック自体がPlanの`.wfm-video-timeline-track`と同様に横幅いっぱい・高さ固定のバーであり続けるようにした(今回のバグの根本原因はCSSの重複ルールだったが、将来の再発防止として明示指定を追加)。
修正後、実機で「空のタイムラインが横幅いっぱいに固定表示される」「クリップ追加後もトラックがフル幅を保ち、クリップは左詰め」「書き出しパネルがPlanのRun/Planパネルと同じ右端固定位置に表示される」ことをスクリーンショットで確認済み。
## 8. トリムパネル・ツールバーの細部調整(2026-09-16、追加指示)
- **開始/終了(秒)入力欄+「現在位置を使用」ボタン**: 従来は横並び(`display:flex`)で、ボタンのテキストが枠からはみ出しコンテナ幅を超えていた。入力欄とボタンを縦積み(`.wfm-video-edit-trim-field { flex-direction:column }`)にし、`.wfm-video-edit-trim-row`のグリッド列幅を`minmax(0,160px)`に縮小。ボタンは`.wfm-video-edit-playhead-btn`(font-size:10px、padding:2px 6px)で一回り小さくし、入力欄との見分けを明確化。
- **タイムライン総合時間の表示**: ツールバーのClearボタン左隣に、全クリップのトリム後長さ合計を表示する`#wfm-video-edit-total-duration`(`合計: 22.1s`のような表示)を追加。`_updateTotalDuration()`が`_updateToolbarState()`(タイムライン再描画のたびに呼ばれる)から自動更新される。
## 9. タイムライン連続プレビュー(2026-09-16、追加指示)
「タイムラインの動画を上部の『生成された動画』プレビューで表示したい。このプレビューの動画=書き出しされる動画としたい」という要望に対応。新規に`<video>`要素を追加するのではなく、Exportの結果が最終的に書き出される**同じ「Result」プレビュー枠**(`#wfm-video-preview-video`、`video-preview.js`の`setResultPreview()`が使う枠)を共有し、タイムライン上の全クリップ(トリム区間反映済み)を順番に連続再生する「疑似合成プレビュー」を実装した。当初計画のMVP項目4「各クリップを順番に`<video>`要素で連続再生する疑似プレビュー」を正式に実装したものにあたる。
- **UI**: タイムラインツールバーに「▶ プレビュー / ■ 停止」トグルボタンを追加(Delete と 合計時間表示の間)。クリップが0件のときは無効化。
- **実装**(`video-edit-tab.js`): `_startPreview()`が`serverRef`ありかつエラー無しのクリップを`_previewClips`として捕捉し先頭から`setResultPreview()`で読み込み・`trimStart`へシーク・再生。`timeupdate`イベントで`currentTime >= trimEnd`を検知した時点、または`ended`イベントで次クリップへ自動遷移(`_advancePreview()`)。全クリップ終了で自動停止。
- `video-preview.js`に`getResultPreviewVideoElement()`を新規export(Resultペインの`<video>`要素へ直接アクセスし、`timeupdate`/`ended`購読や`currentTime`制御を行うため。`setResultPreview()`自体はsrc差し替えのみで再生制御はできないため)。
- クリップ削除・クリア・書き出し開始時には`_stopPreview()`を呼び、再生中の疑似プレビューを確実に停止する(書き出し完了後は同じ枠に実際の書き出し結果が上書き表示される——「プレビューの動画=書き出しされる動画」という要望通り、同一枠が編集中プレビューと最終結果の両方を担う)。
実機で2クリップ(22.1s+19.1s)の連続プレビュー再生→クリップ境界での自動切替→停止→書き出し(結合後41.2s)→Resultペインへの結果反映、という一連の流れを確認済み。
## 10. 静止画/アニメーション画像クリップ対応(2026-09-16、追加指示)
「Assetの画像(静止画)を動画ソースでプレビュー、Editに追加可能にしたい。静止画、アニメーション画像をタイムラインに追加時間を設定できるようにしたい」という要望に対応。既存のAsset一覧(`__Video Assets__`/`__Video Temp__`グループ、ユーザー選択によりこの2グループのみを対象、Gallery全体には拡張しない)には元々ビデオ専用フィルタが無く、手動でタグ付けされた画像もそのまま一覧に出ていたが、プレビューが常に`<video>`要素前提だったため画像では何も表示されず、Editに追加しても動画として扱われ破綻していた。
**設計判断(ユーザー承認事項):**
- 静止画/アニメーション画像は区別せず、どちらも「表示時間(秒)」を指定するhold型クリップとして統一的に扱う。
- 画像クリップの解像度が他の動画クリップと不一致の場合は、`ImageScale`ノード(`crop="center"`)で自動的に動画側の解像度へフィット(ブロックしない)。
**実装:**
- `video-preview.js`: Source/Resultの両プレビュー枠に`<img>`コンパニオン要素を追加し、`setSourcePreview()`/`setResultPreview()`に`mediaType`("video"|"image")引数を追加。`getActivePreviewVideoElement()`は画像表示中は`null`を返す(Frame/GIFツールの誤動作防止)。
- `gallery-tab.js`: `isVideoFile()`をexport。
- `video-asset-tab.js`/`video-tab.js`: プレビュー読み込み・「Editへ送る」/「Editに追加」の各経路で`isVideoFile()`により`mediaType`を判定して渡すよう修正。Video Sourceドロップゾーンも`image/*`を受け付けるよう拡張。
- `video-edit-tab.js`: クリップに`kind:"video"|"image"`を追加。画像クリップは`file.type`から自動判定(`addClipFromFile()`)、サーバーへアップロード後、寸法はPyAV probeではなくブラウザの`Image()`で読み取り(`_readImageDimensions()`、PyAVは任意の静止画形式を安定して開けないため)。トリムパネルはStart/Endペアの代わりに単一の「表示時間(秒)」入力に分岐。タイムラインブロックには🖼/🎬の種別アイコンを付与。解像度不一致ガード(`_findResolutionMismatch`)は`kind==="video"`同士のみ比較するよう変更(画像は自動フィットで解決するため対象外)。
- **書き出しグラフ(画像クリップ)**: `LoadImage` → (解像度不一致時のみ)`ImageScale(crop=center)` → `RepeatImageBatch(amount = 表示秒数 × 24fps)` → `CreateVideo(fps=24, codec="auto")`。実機で48フレーム/24fps→1.998秒の正確な動画生成を確認済み。
- **【追加発見・修正】音声トラック不整合によるConcatenateVideo失敗**: 動画クリップ(音声あり、例: 32kHz stereo)と画像由来クリップ(音声なし)を結合すると`ConcatenateVideo`が`audio layout: expected None, got 'stereo'`で失敗することを実機で発見。対策として、**2クリップ以上を結合する場合のみ**、動画クリップも`GetVideoComponents`→`CreateVideo`(audio未指定)で無音再構成してから結合するよう統一。単一クリップの書き出し(結合が発生しない)は従来通り音声を保持する。**この結果、複数クリップを結合した書き出しは音声を持たないという制約がMVPの既知の限界として残る**(Phase 2以降で音声トラックの取り扱いを検討する余地あり)。
実機で以下を確認済み: 静止画の`<img>`プレビュー表示、Editへの追加(🖼アイコン・表示時間入力)、単独画像クリップの書き出し(2.998秒の正確な動画化)、動画クリップ+画像クリップ混在時の自動解像度フィット・音声除去による結合成功(5.996秒)。
---
### Critical Files for Implementation
- static/js/video-edit-tab.js(新規、中心となるクラス実装)
- templates/index.html(Edit subtab DOM骨格、2895行目付近を拡張)
- static/js/video-workflow.js(ノード注入・ID採番パターンの流用元)
- py/services/video_service.py(probe_video/overlay_text_on_video追加)
- py/routes/video_routes.py(新規APIエンドポイント追加)
- static/js/image-edit-tab.js(アクションバー・レイヤーパネル・pointerイベントパターンの流用元、1385行目・2194行目・1130-1249行目)
- static/js/video-asset-tab.js(Asset→Edit連携ボタン追加)
+19
View File
@@ -19,6 +19,7 @@ _plan_service = VideoPlanService(VIDEO_PLAN_DIR)
def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/video/frame/save-to-output", handle_save_frame)
app.router.add_post("/api/wfm/video/to-gif", handle_to_gif)
app.router.add_get("/api/wfm/video/edit/probe", handle_probe_video)
app.router.add_get("/api/wfm/video/plans", handle_list_plans)
app.router.add_get("/api/wfm/video/plans/content", handle_get_plan_content)
@@ -69,6 +70,24 @@ async def handle_to_gif(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
async def handle_probe_video(request: web.Request) -> web.Response:
filename = request.rel_url.query.get("filename", "")
subfolder = request.rel_url.query.get("subfolder", "")
type_ = request.rel_url.query.get("type", "input")
if not filename:
return web.json_response({"error": "filename required"}, status=400)
try:
result = await asyncio.to_thread(_service.probe_video, filename, subfolder, type_)
return web.json_response(result)
except FileNotFoundError as e:
return web.json_response({"error": str(e)}, status=404)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error probing video: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_list_plans(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_plan_service.list_plans)
+32
View File
@@ -57,6 +57,38 @@ class VideoService:
save_path.write_bytes(image_bytes)
return {"filename": save_name, "subfolder": subfolder}
def probe_video(self, filename: str, subfolder: str, type_: str) -> dict:
"""Reads duration/dimensions/fps/audio presence via PyAV only (no ffmpeg
subprocess) — used by the Video Edit tab right after a clip is added, so
the timeline UI can show its length and the export-time resolution-match
check has real numbers to compare against."""
import av # type: ignore
src_path = self._resolve_media_path(filename, subfolder, type_)
container = av.open(str(src_path))
try:
stream = container.streams.video[0]
fps = float(stream.average_rate) if stream.average_rate else 0.0
if stream.duration is not None and stream.time_base is not None:
duration = float(stream.duration * stream.time_base)
elif container.duration is not None:
duration = float(container.duration) / 1_000_000
else:
duration = 0.0
width = stream.codec_context.width
height = stream.codec_context.height
has_audio = len(container.streams.audio) > 0
finally:
container.close()
return {
"duration": duration,
"width": width,
"height": height,
"fps": fps,
"has_audio": has_audio,
}
def convert_to_gif(
self,
filename: str,
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-workflow-studio"
description = "A comprehensive workflow, asset management, and generation UI plugin for ComfyUI. Manage workflows, models, images, and prompts; batch generation and Image Feeder in the GenerateUI tab; library side panel with canvas drag & drop and AI tools."
version = "0.6.2"
version = "0.7.0"
license = { file = "LICENSE" }
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+285 -19
View File
@@ -275,15 +275,85 @@
flex-direction: column;
}
/* ── Asset: 素材グリッド・詳細パネル ── */
/* ── Asset: 中央下部サブタブ。左=一覧(サムネイル/テーブル切替) / 右=詳細 ── */
.wfm-video-asset-content { padding: 0 16px 16px; }
.wfm-video-asset-layout {
display: flex;
gap: 16px;
align-items: flex-start;
}
.wfm-video-asset-list-col {
flex: 2;
min-width: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.wfm-video-asset-detail-col {
flex: 1;
min-width: 220px;
max-width: 320px;
border-left: 1px solid var(--wfm-border);
padding-left: 16px;
}
.wfm-video-asset-toolbar {
display: flex;
gap: 6px;
align-items: center;
flex-wrap: wrap;
}
.wfm-video-asset-view-btn.active {
background: var(--wfm-primary);
color: #fff;
}
.wfm-video-asset-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
gap: 8px;
max-height: 320px;
max-height: 420px;
overflow-y: auto;
}
.wfm-video-asset-table-wrap {
max-height: 420px;
overflow-y: auto;
border: 1px solid var(--wfm-border);
border-radius: 4px;
}
.wfm-video-asset-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.wfm-video-asset-table th,
.wfm-video-asset-table td {
padding: 6px 8px;
text-align: left;
border-bottom: 1px solid var(--wfm-border);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 240px;
}
.wfm-video-asset-table thead th {
position: sticky;
top: 0;
background: var(--wfm-bg-secondary);
}
.wfm-video-asset-row { cursor: pointer; }
.wfm-video-asset-row:hover { background: var(--wfm-bg-hover); }
.wfm-video-asset-row.selected { outline: 2px solid var(--wfm-primary); outline-offset: -2px; }
.wfm-video-asset-card {
cursor: pointer;
border: 1px solid var(--wfm-border);
@@ -315,8 +385,211 @@
display: flex;
flex-direction: column;
gap: 6px;
border-top: 1px solid var(--wfm-border);
padding-top: 10px;
}
/* ── Edit: クリップタイムライン(Planタブと同じ横トラック+共有ツールバー方式)・
トリムパネル・書き出しパネル ──
Planの.wfm-video-timeline-trackはブロックをflex-grow(duration比率)で幅一杯に
引き伸ばすのに対し、Editのブロックは実秒数×px/秒の固定幅で「左詰め」に並べる
(空きトラックはそのまま空く)ため、専用クラスに分けている。 */
.wfm-video-edit-panel { padding: 0 16px 16px; }
.wfm-video-edit-timeline-track {
display: flex;
align-items: stretch;
gap: 4px;
width: 100%;
box-sizing: border-box;
height: 48px;
padding: 4px;
border-radius: 4px;
border: 1px solid var(--wfm-border);
overflow-x: auto;
position: relative;
flex: none; /* stay a fixed-height full-width bar; never shrink/stretch with clip content */
}
.wfm-video-edit-timeline-placeholder {
display: flex;
align-items: center;
}
.wfm-video-edit-timeline-block {
flex: none;
display: flex;
flex-direction: column;
justify-content: center;
padding: 2px 6px;
border: 1px solid var(--wfm-border);
border-radius: 3px;
background: var(--wfm-bg-hover, rgba(255, 255, 255, 0.04));
cursor: grab;
overflow: hidden;
transition: outline 0.1s;
}
.wfm-video-edit-timeline-block:active { cursor: grabbing; }
.wfm-video-edit-timeline-block.selected { outline: 2px solid var(--wfm-primary); outline-offset: -2px; }
.wfm-video-edit-timeline-block-name {
font-size: 11px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-video-edit-timeline-block-meta {
font-size: 10px;
color: var(--wfm-text-secondary);
}
.wfm-video-edit-main-row {
display: flex;
gap: 16px;
align-items: flex-start;
margin-top: 10px;
}
.wfm-video-edit-trim-panel {
flex: 1;
min-width: 0;
}
.wfm-video-edit-trim-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 160px));
gap: 10px;
}
.wfm-video-edit-trim-row label {
display: block;
font-size: 12px;
color: var(--wfm-text-secondary);
margin-bottom: 4px;
}
/* 開始/終了の入力欄+「現在位置を使用」ボタンを縦積みにする。以前は横並びで
ボタンのラベルがはみ出し、かつ入力欄とボタンの見分けがつきにくかった。 */
.wfm-video-edit-trim-field {
display: flex;
flex-direction: column;
gap: 4px;
}
.wfm-video-edit-trim-field input { width: 100%; box-sizing: border-box; }
.wfm-video-edit-playhead-btn {
align-self: flex-start;
font-size: 10px;
padding: 2px 6px;
}
.wfm-video-edit-total-duration {
font-size: 12px;
color: var(--wfm-text-secondary);
white-space: nowrap;
}
/* ── トリムスクラバー: clipchamp風の時間目盛り+シークバー+トリムハンドル。
すべて%位置指定(clip.duration基準)にすることでpx/秒換算を持たずに済ませている。 */
.wfm-video-trim-scrubber {
margin-top: 10px;
user-select: none;
}
.wfm-video-trim-ruler {
position: relative;
height: 16px;
font-size: 10px;
color: var(--wfm-text-secondary);
}
.wfm-video-trim-ruler-tick {
position: absolute;
top: 0;
transform: translateX(-50%);
white-space: nowrap;
}
.wfm-video-trim-track {
position: relative;
height: 36px;
margin-top: 4px;
background: var(--wfm-bg-hover, #111);
border: 1px solid var(--wfm-border);
border-radius: 4px;
cursor: pointer;
}
.wfm-video-trim-range {
position: absolute;
top: 0;
bottom: 0;
background: rgba(70, 130, 230, 0.3);
border-top: 2px solid var(--wfm-primary);
border-bottom: 2px solid var(--wfm-primary);
pointer-events: none;
}
.wfm-video-trim-handle {
position: absolute;
top: 0;
bottom: 0;
width: 10px;
margin-left: -5px;
background: var(--wfm-primary);
border-radius: 2px;
cursor: ew-resize;
z-index: 3;
}
.wfm-video-trim-playhead {
position: absolute;
top: -4px;
bottom: -4px;
width: 2px;
margin-left: -1px;
background: #fff;
/* Below the trim handles (z-index:3) so a handle sitting at the same
position (e.g. right after "Set from playhead") stays grabbable instead
of the playhead's hit area stealing the pointer. */
z-index: 2;
cursor: ew-resize;
}
.wfm-video-trim-playhead::before {
content: "";
position: absolute;
top: -4px;
left: 50%;
transform: translateX(-50%);
width: 10px;
height: 10px;
border-radius: 50%;
background: #fff;
}
.wfm-video-trim-badge {
position: absolute;
top: -22px;
left: 50%;
transform: translateX(-50%);
background: #111;
color: #fff;
font-size: 10px;
padding: 1px 5px;
border-radius: 3px;
white-space: nowrap;
pointer-events: none;
}
.wfm-video-trim-badge-playhead {
background: #000;
}
.wfm-video-edit-export-panel {
width: 220px;
flex: none;
}
.wfm-video-asset-detail label {
@@ -383,7 +656,7 @@
.wfm-video-preview-frame {
flex: 1;
min-width: 0;
min-height: 260px;
height: 260px;
display: flex;
align-items: center;
justify-content: center;
@@ -391,11 +664,16 @@
border-radius: 6px;
background: var(--wfm-bg-hover, #111);
text-align: center;
overflow: hidden;
}
/* ソース動画/画像のネイティブサイズがフレームより大きい場合のみ縮小し、
小さい場合は拡大しない(枠のheightを固定にしてPlan/Editの位置がずれないようにするため) */
.wfm-video-preview-el {
max-width: 100%;
max-height: 60vh;
max-height: 100%;
width: auto;
height: auto;
border-radius: 6px;
}
@@ -417,18 +695,6 @@
margin: 0 0 8px 0;
}
/* 将来の動画編集機能(トリミング等)用のプレースホルダー領域 */
.wfm-video-edit-panel {
flex: 1;
min-height: 160px;
display: flex;
align-items: center;
justify-content: center;
border: 1px dashed var(--wfm-border);
border-radius: 6px;
color: var(--wfm-text-secondary);
font-size: 13px;
}
/* ── 右ペイン: プロパティ (Frame抽出 / GIF変換タブ) ── */
.wfm-video-properties-panel {
+1
View File
@@ -745,6 +745,7 @@ function applyI18nToHtml() {
"wfm-help-video-5": "helpVideo5", "wfm-help-video-6": "helpVideo6",
"wfm-help-video-7": "helpVideo7", "wfm-help-video-8": "helpVideo8",
"wfm-help-video-9": "helpVideo9", "wfm-help-video-10": "helpVideo10",
"wfm-help-video-11": "helpVideo11", "wfm-help-video-12": "helpVideo12",
};
for (const [id, key] of Object.entries(helpIdMap)) {
const el = document.getElementById(id);
+27 -1
View File
@@ -60,7 +60,7 @@ function _isReservedGroup(name) {
// 拡張子から動画ファイル(mp4)かどうかを判定する。
// 一覧アイテムは path/filename、詳細メタ(get_image_metadata)は ext フィールドを持つため両対応。
function isVideoFile(img) {
export function isVideoFile(img) {
const source = img?.ext || img?.filename || img?.path || "";
return source.toLowerCase().endsWith(".mp4");
}
@@ -1986,6 +1986,7 @@ function bindEvents() {
return;
}
const url = API.serveImage(state.selectedImage.path);
const isVideo = isVideoFile(state.selectedImage);
// I2I送信元がImageタブだった場合はそちらへ画像を読み込ませる(_ccI2ITargetModeはComic Creater側が
// 「I2Iへ送る」ボタン押下時にセットするフラグ。undefined/'layout'なら従来通りコマ/オーバーレイへ挿入)
@@ -1996,6 +1997,11 @@ function bindEvents() {
targetMode = null;
}
if (targetMode === "image") {
// Imageタブは動画未対応(Comic Creator側の動画ツールはレイアウトタブのみ対応)
if (isVideo) {
showToast(t("galleryVideoNotSupportedInImageTab"), "info");
return;
}
let imageTab = null;
try {
if (window.parent && window.parent !== window && typeof window.parent._ccImageTab?.loadFromUrl === "function") {
@@ -2013,6 +2019,26 @@ function bindEvents() {
return;
}
// レイアウトタブのコマ/オーバーレイへ(デフォルト経路)。動画(.mp4)はComic Creator側の
// 動画ツール専用の受け口(insertVideoFromUrl)へ、それ以外は従来通り画像として送る
if (isVideo) {
let insertVideoFn = null;
try {
if (window.parent && window.parent !== window && typeof window.parent.insertVideoFromUrl === "function") {
insertVideoFn = window.parent.insertVideoFromUrl;
}
} catch (e) {
insertVideoFn = null;
}
if (!insertVideoFn) {
showToast(t("galleryCCNotAvailable"), "info");
return;
}
insertVideoFn(url, state.selectedImage.filename || "video.mp4");
showToast(t("gallerySentCC"), "success");
return;
}
let insertFn = null;
try {
if (window.parent && window.parent !== window && typeof window.parent.insertImageFromUrl === "function") {
+111 -12
View File
@@ -586,6 +586,7 @@ const LANGUAGES = {
sendToLiNodeSuccess: (filename) => `Sent "${filename}" to LI node`,
galleryCCNotAvailable: "Open this Gallery from ComfyUI Comic Creator to use Send CC",
gallerySentCC: "Sent to ComfyUI Comic Creator",
galleryVideoNotSupportedInImageTab: "Sending a video to the Image tab is not supported yet",
galleryNoEmbeddedWorkflow: "No ComfyUI workflow embedded in this image.",
galleryTabOutput: "Output",
galleryTabImagePrompt: "ImagePrompt",
@@ -1344,7 +1345,37 @@ const LANGUAGES = {
// -- Video Tab (MiniMax H3 / LTX-2.5 / Wan2.2, independent of GenerateUI) --
tabVideo: "Video",
loadInVideo: "Load in Video",
videoEditPlaceholder: "Editing tools coming soon",
videoEditNoClipsHint: "No clips yet — select an Asset or drop a video into Video Source above, then \"Add to Edit\"",
videoEditNoClips: "Add at least one clip first",
videoEditStillProbing: "Please wait for clip analysis to finish",
videoEditResolutionMismatch: (a, b) => `Clip resolutions don't match (${a} vs ${b}). Trim/crop to the same size before exporting.`,
videoEditProbing: "Analyzing...",
videoEditSelectClipHint: "Select a clip to trim",
videoEditImageDuration: "Duration (s)",
videoEditTrimStart: "Start (s)",
videoEditTrimEnd: "End (s)",
videoEditSetFromPlayhead: "Use current position",
videoEditMoveLeft: "Move left",
videoEditMoveRight: "Move right",
videoEditClearBtn: "Clear",
videoEditTotalDuration: (time) => `Total: ${time}`,
videoEditPreviewPlay: "▶ Preview",
videoEditPreviewStop: "■ Stop",
videoEditConfirmClear: "Clear the entire edit timeline?",
videoSourceAddToEdit: "Add to Edit",
videoEditDuplicate: "Duplicate",
videoEditDelete: "Delete",
videoEditExportBtn: "Export",
videoEditExporting: "Exporting...",
videoEditExportDone: (name) => `Exported: ${name}`,
videoEditSendToEdit: "Send to Edit",
videoEditClipSent: (name) => `Added "${name}" to Edit timeline`,
videoAssetSetAsFirst: "Set as First Image",
videoAssetSetAsLast: "Set as Last Image",
videoAssetSetAsFirstDone: (name) => `Set "${name}" as First Image`,
videoAssetSetAsLastDone: (name) => `Set "${name}" as Last Image`,
videoNoBlockSelected: "No block selected in Plan",
videoBlockImageUploadFailed: "Failed to upload image to Plan block",
videoNoWorkflowLoaded: "No workflow loaded",
videoUnsupportedWorkflow: "This workflow does not contain a supported video model node (MiniMax H3, LTX-2.5 Text/Image/First&Last-Frame to Video, or Wan2.2 Text to Video)",
videoWorkflowLoadFailed: "Failed to load workflow",
@@ -1389,17 +1420,19 @@ const LANGUAGES = {
videoProjectDeleteFailed: "Failed to delete plan",
videoProjectLoadListFailed: "Failed to load plan list",
helpVideoTitle: "Video Tab",
helpVideoDesc: "A dedicated video generation tab for MiniMax H3 (Image to Video), LTX-2.5 (Text / Image / First & Last Frame to Video), and Wan2.2 (Text to Video) workflows, independent of the GenerateUI tab. The center panel's Plan / Edit subtabs handle batch generation and (future) editing; the sidebar's Asset / Project subtabs handle browsing generated videos and saved plans.",
helpVideoDesc: "A dedicated video generation tab for MiniMax H3 (Image to Video), LTX-2.5 (Text / Image / First & Last Frame to Video), and Wan2.2 (Text to Video) workflows, independent of the GenerateUI tab. The center panel's Plan / Edit / Asset subtabs handle batch generation, clip editing, and browsing generated videos; the sidebar's Project subtab handles saved plans.",
helpVideo1: "Plan subtab: the topbar's settings row holds Aspect Ratio / Megapixels / Multiple / Duration (seconds) / Noise Seed as this plan's base settings — Duration always reflects the currently selected block (each block keeps its own value), the rest are plan-wide. A second row below adds Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance, each enabled only for workflows that actually support it (see helpVideo2). Split the timeline into blocks with the + Split / + Block / Delete buttons — each block has its own Prompt, Duration, and First/Last Image — First Image can be None, an explicit image, or \"use previous block's last frame\" (an explicit Last Image on the previous block always wins over extracting one from its generated video). Click Run to generate every block in order; Pause/Cancel work mid-run.",
helpVideo2: "A plan with a single block behaves exactly like the old one-shot form. Model selection (UNet / CLIP / VAE / Audio VAE) is fixed to the loaded workflow's defaults. For workflows with no ResolutionSelector node (e.g. Wan2.2, LTX-2.5 First & Last Frame to Video), the Aspect Ratio / Megapixels / Multiple fields are disabled and the workflow's own Width / Height become directly editable instead. Turbo Mode / Strength / Steps only apply to MiniMax H3's turbo LoRA, and Prompt Enhance only to LTX-2.5 — both stay disabled for other model families. Noise Seed is disabled for the one workflow that doesn't expose it: Wan2.2 Text-to-Video.",
helpVideo3: "Use the \"Load in Video\" button in the Workflow tab's detail modal to load a workflow containing a MiniMax H3 Image-to-Video node, an LTX-2.5 Text/Image/First&Last-Frame-to-Video node, or a Wan2.2 Text-to-Video node — this starts a fresh single-block plan seeded from the workflow's own current values. Unsupported workflows show an error instead.",
helpVideo4: "Generated videos (mp4) automatically appear in the Asset subtab's Video Temp group, and can also be browsed and played back in the Gallery tab. Organizing keepers into Video Assets is entirely up to you, on your own schedule.",
helpVideo5: "The center panel shows two previews: the left one shows either the video you select in the Asset subtab or whatever you drop/pick in the Video Source panel on its left (Clear resets it to empty), letting you use the Frame/GIF tools without running the loaded video workflow first; the right one always shows the most recently generated clip.",
helpVideo6: "Frame tab (right panel): play/seek the preview video to the position you want, click Capture Frame to grab that frame client-side, then Save to Output to write it as a PNG into ComfyUI's output folder.",
helpVideo6: "Frame tab (right panel): play/seek the preview video to the position you want, click Capture Frame to grab that frame client-side, then Save to Output to write it as a PNG into ComfyUI's output folder — check \"Add to Video Assets group\" first to also tag the saved frame into Gallery's Video Assets group.",
helpVideo7: "GIF tab (right panel): set Start/End (seconds), FPS, and an optional Max Width, then Convert to GIF — the server decodes the video and encodes an animated GIF into ComfyUI's output folder.",
helpVideo8: "Chaining: setting a block's First Image to \"use previous block's last frame\" continues smoothly from the previous clip — if that previous block has its own explicit Last Image, that image is used directly; otherwise the actual last frame of its generated video is extracted automatically.",
helpVideo9: "Project tab (sidebar, next to Asset): browse every saved plan file (thumbnail, block count, last updated), click one to load it into the Plan editor, or delete it with the × button; clicking the same tab again collapses the panel.",
helpVideo9: "Project tab (sidebar): browse every saved plan file (thumbnail, block count, last updated), click one to load it into the Plan editor, or delete it with the × button; clicking the same tab again collapses the panel.",
helpVideo10: "Highlight color: the Prompt / Duration / First Image / Last Image / Aspect Ratio / Megapixels / Multiple / Noise Seed / Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance labels turn the same highlight color as the GenerateUI Model tab (customizable in the Settings tab) when the loaded workflow actually supports that field — e.g. for a Wan2.2 workflow (no ResolutionSelector node), the Aspect Ratio / Megapixels / Multiple labels stay unhighlighted while Width / Height light up instead.",
helpVideo11: "Edit subtab: a lightweight clip timeline for trimming and concatenating video/image clips outside of generation. Add clips via the Video Source panel's \"Add to Edit\" button or the Asset subtab's \"Send to Edit\" button, then drag blocks to reorder (or use the ◀/▶ toolbar buttons), Duplicate/Delete the selected clip, and Clear to empty the timeline. The trim panel for the selected video clip shows a time ruler, a draggable playhead synced to the Source preview, and draggable in/out handles with time badges — image clips instead get a simple hold-duration field. ▶ Preview plays every ready clip back-to-back (trimmed to its in/out points) in the right-hand result preview; Export builds and runs the actual ComfyUI graph (trim → concatenate if more than one clip → save), tagging the result into the Video Temp group automatically. Exporting more than one clip currently drops audio, since ComfyUI's concatenation node requires uniform audio across all inputs.",
helpVideo12: "Asset subtab (center panel, next to Plan/Edit): browses every video/image tagged into Video Assets or Video Temp (via the group dropdown, or \"All Video Assets\" for both). Search filters by filename; the ▦/☰ buttons switch between a thumbnail grid and a table (filename/updated/tags). Selecting an item shows its tags/memo, loads it into the center preview, and offers \"Send to Edit\" (queues it as a clip in the Edit subtab) plus, for images only, \"Set as First Image\"/\"Set as Last Image\" (uploads it straight into the currently-selected Plan block, switching to the Plan subtab).",
},
ja: {
@@ -1982,6 +2015,7 @@ const LANGUAGES = {
sendToLiNodeSuccess: (filename) => `"${filename}" をLIノードへ送信しました`,
galleryCCNotAvailable: "Send CCはComfyUI Comic Creator内のギャラリーから開いた場合のみ使用できます",
gallerySentCC: "ComfyUI Comic Creatorへ送信しました",
galleryVideoNotSupportedInImageTab: "動画のImageタブへの送信は未対応です",
galleryNoEmbeddedWorkflow: "この画像にはComfyUIワークフローが埋め込まれていません。",
galleryTabOutput: "Output",
galleryTabImagePrompt: "ImagePrompt",
@@ -2740,7 +2774,37 @@ const LANGUAGES = {
// -- Video タブ(MiniMax H3 / LTX-2.5 / Wan2.2対応、GenerateUIタブとは独立) --
tabVideo: "Video",
loadInVideo: "Videoに読み込み",
videoEditPlaceholder: "編集機能は今後追加予定",
videoEditNoClipsHint: "クリップがありません — 上の動画ソースでAssetを選択/動画をドロップし「Editに追加」してください",
videoEditNoClips: "まずクリップを1つ以上追加してください",
videoEditStillProbing: "クリップの解析が完了するまでお待ちください",
videoEditResolutionMismatch: (a, b) => `クリップの解像度が一致しません(${a} と ${b})。書き出し前に同じサイズにトリム/クロップしてください。`,
videoEditProbing: "解析中...",
videoEditSelectClipHint: "トリムするクリップを選択してください",
videoEditImageDuration: "表示時間(秒)",
videoEditTrimStart: "開始(秒)",
videoEditTrimEnd: "終了(秒)",
videoEditSetFromPlayhead: "現在位置を使用",
videoEditMoveLeft: "左へ移動",
videoEditMoveRight: "右へ移動",
videoEditClearBtn: "クリア",
videoEditTotalDuration: (time) => `合計: ${time}`,
videoEditPreviewPlay: "▶ プレビュー",
videoEditPreviewStop: "■ 停止",
videoEditConfirmClear: "編集タイムラインを全てクリアしますか?",
videoSourceAddToEdit: "Editに追加",
videoEditDuplicate: "複製",
videoEditDelete: "削除",
videoEditExportBtn: "書き出し",
videoEditExporting: "書き出し中...",
videoEditExportDone: (name) => `書き出し完了: ${name}`,
videoEditSendToEdit: "Editへ送る",
videoEditClipSent: (name) => `"${name}" をEditタイムラインに追加しました`,
videoAssetSetAsFirst: "First Imageに設定",
videoAssetSetAsLast: "Last Imageに設定",
videoAssetSetAsFirstDone: (name) => `"${name}" をFirst Imageに設定しました`,
videoAssetSetAsLastDone: (name) => `"${name}" をLast Imageに設定しました`,
videoNoBlockSelected: "Planでブロックが選択されていません",
videoBlockImageUploadFailed: "Planブロックへの画像アップロードに失敗しました",
videoNoWorkflowLoaded: "ワークフローが読み込まれていません",
videoUnsupportedWorkflow: "このワークフローには対応する動画モデルノード(MiniMax H3、LTX-2.5のText/Image/First&Last-Frame to Video、またはWan2.2のText to Video)が含まれていません",
videoWorkflowLoadFailed: "ワークフローの読み込みに失敗しました",
@@ -2785,17 +2849,19 @@ const LANGUAGES = {
videoProjectDeleteFailed: "Planの削除に失敗しました",
videoProjectLoadListFailed: "Plan一覧の読み込みに失敗しました",
helpVideoTitle: "Video タブ",
helpVideoDesc: "MiniMax H3 (Image to Video)、LTX-2.5 (Text / Image / First & Last Frame to Video)、Wan2.2 (Text to Video) ワークフロー対応の動画生成タブ。GenerateUIタブとは独立して動作します。中央パネルのPlan/Editサブタブがバッチ生成と(将来の)編集を、左サイドバーのAsset/Projectサブタブが生成済み動画の閲覧と保存済みPlanの一覧を扱います。",
helpVideoDesc: "MiniMax H3 (Image to Video)、LTX-2.5 (Text / Image / First & Last Frame to Video)、Wan2.2 (Text to Video) ワークフロー対応の動画生成タブ。GenerateUIタブとは独立して動作します。中央パネルのPlan/Edit/Assetサブタブがバッチ生成・クリップ編集・生成済み動画の閲覧を、左サイドバーのProjectサブタブが保存済みPlanの一覧を扱います。",
helpVideo1: "Planサブタブ: 上部の設定行にAspect Ratio/Megapixels/Multiple/Duration(秒)/Noise SeedがこのPlanの基本設定として並びます——Durationは常に現在選択中のブロックの値を表示・編集します(各ブロックが独自の値を持つ)が、それ以外はPlan全体で共通の値です。その下の2行目にはWidth/Height/Turbo Mode/Strength/Steps/Prompt Enhanceが並び、読み込んだワークフローが実際に対応する項目だけ入力可能になります(詳細はhelpVideo2)。「+ Split」「+ Block」「Delete」ボタンでタイムラインをブロックに分割すると、各ブロックは独自のPrompt・Duration・First/Last Imageを持ちます(First Imageは「なし」「画像を指定」「前ブロックの最終フレームを使用」から選択可能。前ブロックに明示的なLast Imageが設定されていれば、フレーム抽出よりそちらが優先されます)。Runを押すと全ブロックを順番に生成します。実行中もPause/Cancelが使えます。",
helpVideo2: "ブロックが1個だけのPlanは、以前の単発生成フォームと同じ動作になります。モデル選択(UNet/CLIP/VAE/Audio VAE)は読み込んだワークフローの既定値に固定されます。ResolutionSelectorノードを持たないワークフロー(Wan2.2、LTX-2.5のFirst & Last Frame to Videoなど)はAspect Ratio/Megapixels/Multiple欄が無効化される代わりに、ワークフロー自体のWidth/Heightを直接編集できるようになります。Turbo Mode/Strength/StepsはMiniMax H3のturbo LoRA専用、Prompt EnhanceはLTX-2.5専用で、他のモデルファミリーでは無効のままです。Noise SeedはWan2.2のText to Videoのみ公開入力を持たないため無効化されます。",
helpVideo3: "Workflowタブの詳細モーダルにある「Videoに読み込み」ボタンから、MiniMax H3のImage to Videoノード、LTX-2.5のText/Image/First&Last-Frame to Videoノード、またはWan2.2のText to Videoノードを含むワークフローを読み込めます。この操作でワークフローの現在値を反映したブロック1個の新規Planが作成されます。対応していないワークフローはエラー表示になります。",
helpVideo4: "生成した動画(mp4)はAssetサブタブのVideo Tempグループに自動的に反映されるほか、Galleryタブでも閲覧・再生できます。残したい動画をVideo Assetsへ整理するタイミングはユーザー任意です。",
helpVideo5: "中央パネルには2つのプレビューがあります。左側はAssetサブタブで選択した動画、または左隣の「Video Source」パネルにドロップ/選択した任意のローカル動画を表示し(Clearでリセット)、読み込んだワークフローを実行せずにFrame/GIF機能を使えます。右側は常に直近で生成されたクリップを表示します。",
helpVideo6: "Frameタブ(右パネル): プレビュー動画を再生・シークして止めたい位置で「Capture Frame」を押すとその場でフレームをキャプチャし、「Save to Output」でPNGとしてComfyUIのOutputフォルダに保存します。",
helpVideo6: "Frameタブ(右パネル): プレビュー動画を再生・シークして止めたい位置で「Capture Frame」を押すとその場でフレームをキャプチャし、「Save to Output」でPNGとしてComfyUIのOutputフォルダに保存します。保存前に「Add to Video Assets group」にチェックを入れると、保存したフレームをGalleryのVideo Assetsグループにも自動登録できます。",
helpVideo7: "GIFタブ(右パネル): Start/End(秒)・FPS・Max Width(任意)を指定して「Convert to GIF」を押すと、サーバー側で動画をデコードしアニメーションGIFとしてComfyUIのOutputフォルダに保存します。",
helpVideo8: "チェイン機能: ブロックのFirst Imageを「前ブロックの最終フレームを使用」に設定すると、前のクリップから連続した映像になります。前ブロックに明示的なLast Imageが設定されていればそれがそのまま使われ、無ければ生成された動画から実際の最終フレームが自動抽出されます。",
helpVideo9: "Projectタブ(左サイドバー、Assetの隣): 保存済みの全Planファイル(サムネイル・ブロック数・更新日時)を一覧表示し、クリックでPlanエディタへ読み込み、×ボタンで削除できます。同じタブをもう一度押すとパネルを閉じます。",
helpVideo9: "Projectタブ(左サイドバー): 保存済みの全Planファイル(サムネイル・ブロック数・更新日時)を一覧表示し、クリックでPlanエディタへ読み込み、×ボタンで削除できます。同じタブをもう一度押すとパネルを閉じます。",
helpVideo10: "ハイライト表示: 読み込んだワークフローが実際にサポートしているフィールドに応じて、Prompt/Duration/First Image/Last Image/Aspect Ratio/Megapixels/Multiple/Noise Seed/Width/Height/Turbo Mode/Strength/Steps/Prompt Enhanceのラベルが、GenerateUI ModelタブのハイライトとSettingsタブで共通設定できる色に変わります。例えばWan2.2ワークフロー(ResolutionSelectorノードが無い)ではAspect Ratio/Megapixels/Multipleはハイライトされない代わりに、Width/Heightがハイライトされます。",
helpVideo11: "Editサブタブ: 生成とは独立して動画/画像クリップをトリム・結合できる簡易タイムラインです。Video Sourceパネルの「Editに追加」ボタン、またはAssetサブタブの「Editへ送る」ボタンでクリップを追加し、ブロックをドラッグ(または◀/▶ツールバーボタン)で並べ替え、選択中クリップをDuplicate/Delete、Clearでタイムラインを空にできます。選択中の動画クリップのトリムパネルには時間目盛り・Sourceプレビューと同期するドラッグ可能な再生ヘッド・時刻バッジ付きのドラッグ可能なイン/アウトハンドルが表示されます(画像クリップは代わりにシンプルな保持時間の入力欄)。「▶ プレビュー」は準備済みの全クリップをイン/アウト点でトリムして右側の結果プレビューで連続再生し、「書き出し」は実際のComfyUIグラフ(トリム→2クリップ以上ならConcatenate→保存)を構築・実行して、結果をVideo Tempグループへ自動登録します。複数クリップの書き出しは現状音声が失われます(ComfyUIの結合ノードが全入力で音声形式の統一を要求するため)。",
helpVideo12: "Assetサブタブ(中央パネル、Plan/Editの隣): グループ切替(または「All Video Assets」で両方まとめて)でVideo AssetsまたはVideo Tempに登録された動画/画像を一覧表示します。検索欄はファイル名でフィルタし、▦/☰ボタンでサムネイルグリッドとテーブル表示(ファイル名・更新日時・タグ)を切り替えられます。項目を選択するとタグ・メモが表示され中央プレビューに読み込まれ、「Editへ送る」(Editサブタブのクリップとして追加)に加え、画像の場合のみ「First Imageに設定」「Last Imageに設定」(選択中のPlanブロックへ直接アップロードし、Planサブタブへ切り替え)が使えます。",
},
zh: {
@@ -3378,6 +3444,7 @@ const LANGUAGES = {
sendToLiNodeSuccess: (filename) => `已将"${filename}"发送到LI节点`,
galleryCCNotAvailable: "仅当从ComfyUI Comic Creator内的图库打开时才能使用Send CC",
gallerySentCC: "已发送至ComfyUI Comic Creator",
galleryVideoNotSupportedInImageTab: "暂不支持将视频发送到Image标签",
galleryNoEmbeddedWorkflow: "此图像中未嵌入ComfyUI工作流。",
galleryTabOutput: "Output",
galleryTabImagePrompt: "ImagePrompt",
@@ -4136,7 +4203,37 @@ const LANGUAGES = {
// -- Video 标签页(支持 MiniMax H3 / LTX-2.5 / Wan2.2,独立于 GenerateUI) --
tabVideo: "Video",
loadInVideo: "加载到Video",
videoEditPlaceholder: "编辑功能即将推出",
videoEditNoClipsHint: "暂无片段 — 请在上方选择素材或拖放视频后点击“添加到Edit”",
videoEditNoClips: "请先添加至少一个片段",
videoEditStillProbing: "请等待片段分析完成",
videoEditResolutionMismatch: (a, b) => `片段分辨率不一致(${a} 与 ${b})。导出前请裁剪为相同尺寸。`,
videoEditProbing: "分析中...",
videoEditSelectClipHint: "选择一个片段进行裁剪",
videoEditImageDuration: "显示时长(秒)",
videoEditTrimStart: "开始(秒)",
videoEditTrimEnd: "结束(秒)",
videoEditSetFromPlayhead: "使用当前位置",
videoEditMoveLeft: "左移",
videoEditMoveRight: "右移",
videoEditClearBtn: "清空",
videoEditTotalDuration: (time) => `总计: ${time}`,
videoEditPreviewPlay: "▶ 预览",
videoEditPreviewStop: "■ 停止",
videoEditConfirmClear: "确定清空整个编辑时间线吗?",
videoSourceAddToEdit: "添加到Edit",
videoEditDuplicate: "复制",
videoEditDelete: "删除",
videoEditExportBtn: "导出",
videoEditExporting: "导出中...",
videoEditExportDone: (name) => `已导出: ${name}`,
videoEditSendToEdit: "发送到Edit",
videoEditClipSent: (name) => `已将 "${name}" 添加到Edit时间线`,
videoAssetSetAsFirst: "设为First Image",
videoAssetSetAsLast: "设为Last Image",
videoAssetSetAsFirstDone: (name) => `已将 "${name}" 设为First Image`,
videoAssetSetAsLastDone: (name) => `已将 "${name}" 设为Last Image`,
videoNoBlockSelected: "Plan中未选择区块",
videoBlockImageUploadFailed: "上传图片到Plan区块失败",
videoNoWorkflowLoaded: "尚未加载工作流",
videoUnsupportedWorkflow: "该工作流不包含受支持的视频模型节点(MiniMax H3、LTX-2.5 的 Text/Image/First&Last-Frame to Video,或 Wan2.2 的 Text to Video)",
videoWorkflowLoadFailed: "工作流加载失败",
@@ -4181,17 +4278,19 @@ const LANGUAGES = {
videoProjectDeleteFailed: "Plan 删除失败",
videoProjectLoadListFailed: "Plan 列表加载失败",
helpVideoTitle: "Video 标签页",
helpVideoDesc: "支持 MiniMax H3(Image to Video)、LTX-2.5(Text / Image / First & Last Frame to Video)、Wan2.2(Text to Video)工作流的视频生成标签页,独立于 GenerateUI 标签页运行。中央面板的 Plan/Edit 子标签负责批量生成和(未来的)编辑;侧边栏的 Asset/Project 子标签负责浏览已生成的视频和已保存的 Plan。",
helpVideoDesc: "支持 MiniMax H3(Image to Video)、LTX-2.5(Text / Image / First & Last Frame to Video)、Wan2.2(Text to Video)工作流的视频生成标签页,独立于 GenerateUI 标签页运行。中央面板的 Plan/Edit/Asset 子标签负责批量生成、片段剪辑和浏览已生成的视频;侧边栏的 Project 子标签负责已保存的 Plan。",
helpVideo1: "Plan 子标签:顶部设置行包含 Aspect Ratio/Megapixels/Multiple/Duration(秒)/Noise Seed,作为该 Plan 的基础设置——Duration 始终显示并可编辑当前选中区块的值(每个区块保留自己的值),其余字段则是整个 Plan 共用的。下方第二行是 Width/Height/Turbo Mode/Strength/Steps/Prompt Enhance,仅当所加载的工作流实际支持该项时才可输入(详见 helpVideo2)。用「+ Split」「+ Block」「Delete」按钮把时间线分割成多个区块后,每个区块都有自己的 Prompt、Duration 以及 First/Last Image(First Image 可选择“无”、“指定图片”或“使用前一个区块的最后一帧”——若前一个区块已明确设置了 Last Image,则优先使用该图片而非提取帧)。点击 Run 会按顺序生成所有区块,运行中也可以 Pause/Cancel。",
helpVideo2: "只有一个区块的 Plan 与旧版单次生成表单效果完全相同。模型选择(UNet/CLIP/VAE/Audio VAE)固定为所加载工作流的默认值。没有 ResolutionSelector 节点的工作流(如 Wan2.2、LTX-2.5 的 First & Last Frame to Video)会禁用 Aspect Ratio/Megapixels/Multiple 字段,改为可以直接编辑工作流自身的 Width/Height。Turbo Mode/Strength/Steps 仅适用于 MiniMax H3 的 turbo LoRA,Prompt Enhance 仅适用于 LTX-2.5——其他模型系列中这些字段保持禁用。Noise Seed 仅在 Wan2.2 的 Text to Video 中会被禁用,因为该变体未公开此输入。",
helpVideo3: "在 Workflow 标签页的详情弹窗中使用「加载到Video」按钮,可以加载包含 MiniMax H3 的 Image to Video 节点、LTX-2.5 的 Text/Image/First&Last-Frame to Video 节点、或 Wan2.2 的 Text to Video 节点的工作流——此操作会创建一个仅含一个区块、并以该工作流当前值为初始值的新 Plan。不受支持的工作流会显示错误提示。",
helpVideo4: "生成的视频(mp4)会自动出现在 Asset 子标签的 Video Temp 组中,也可以在 Gallery 标签页中浏览和播放。是否整理到 Video Assets,由您自行决定时机。",
helpVideo5: "中间面板有两个预览区:左侧显示您在 Asset 子标签中选择的视频,或拖放/选择到左边「Video Source」面板中的任意本地视频(点击 Clear 可重置),无需先运行已加载的视频工作流即可使用 Frame/GIF 工具;右侧始终显示最近一次生成的片段。",
helpVideo6: "Frame标签页(右侧面板):播放/拖动预览视频到想要的位置,点击「Capture Frame」在客户端截取该帧,再点击「Save to Output」将其保存为PNG到ComfyUI的输出文件夹。",
helpVideo6: "Frame标签页(右侧面板):播放/拖动预览视频到想要的位置,点击「Capture Frame」在客户端截取该帧,再点击「Save to Output」将其保存为PNG到ComfyUI的输出文件夹——保存前勾选「Add to Video Assets group」还可以把保存的帧同时标记进 Gallery 的 Video Assets 分组。",
helpVideo7: "GIF标签页(右侧面板):设置Start/End(秒)、FPS和可选的Max Width,点击「Convert to GIF」后,服务器会解码视频并将动画GIF保存到ComfyUI的输出文件夹。",
helpVideo8: "链接功能:将某个区块的 First Image 设置为“使用前一个区块的最后一帧”,即可与上一个片段流畅衔接——如果前一个区块已明确设置了 Last Image,将直接使用该图片;否则会自动从其生成的视频中提取实际的最后一帧。",
helpVideo9: "Project标签页(左侧边栏,与Asset并列):浏览所有已保存的 Plan 文件(缩略图、区块数、最后更新时间),点击即可加载到 Plan 编辑器,或用 × 按钮删除;再次点击同一标签会收起面板。",
helpVideo9: "Project标签页(左侧边栏):浏览所有已保存的 Plan 文件(缩略图、区块数、最后更新时间),点击即可加载到 Plan 编辑器,或用 × 按钮删除;再次点击同一标签会收起面板。",
helpVideo10: "高亮颜色:当所加载的工作流实际支持该字段时,Prompt / Duration / First Image / Last Image / Aspect Ratio / Megapixels / Multiple / Noise Seed / Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance 标签会变为与 GenerateUI Model 标签页相同的高亮颜色(可在 Settings 标签页自定义)——例如 Wan2.2 工作流(没有 ResolutionSelector 节点)中,Aspect Ratio / Megapixels / Multiple 不会高亮,取而代之的是 Width / Height 会高亮。",
helpVideo11: "Edit 子标签:独立于生成流程的轻量剪辑时间线,用于裁剪和拼接视频/图片片段。通过 Video Source 面板的「Add to Edit」按钮,或 Asset 子标签的「Send to Edit」按钮添加片段,拖动区块(或使用 ◀/▶ 工具栏按钮)重新排序,对选中片段执行 Duplicate/Delete,Clear 可清空时间线。选中视频片段的裁剪面板会显示时间刻度尺、与 Source 预览同步的可拖动播放头,以及带时间标签的可拖动入/出点手柄(图片片段则只有一个简单的保持时长输入框)。「▶ Preview」会按入/出点依次裁剪并在右侧结果预览区连续播放所有就绪片段;「Export」会构建并运行实际的 ComfyUI 图(裁剪→若多于一个片段则拼接→保存),并自动把结果标记进 Video Temp 分组。目前导出多个片段会丢失音频,因为 ComfyUI 的拼接节点要求所有输入的音频格式一致。",
helpVideo12: "Asset 子标签(中央面板,位于 Plan/Edit 旁):浏览标记到 Video Assets 或 Video Temp 分组的所有视频/图片(通过分组下拉框选择,或选择「All Video Assets」同时浏览两者)。搜索框按文件名过滤,▦/☰ 按钮可在缩略图网格和表格视图(文件名/更新时间/标签)之间切换。选中一项会显示其标签/备注并加载到中央预览,此外还提供「Send to Edit」(作为片段加入 Edit 子标签);仅图片还额外提供「Set as First Image」「Set as Last Image」(直接上传到当前选中的 Plan 区块,并切换到 Plan 子标签)。",
},
};
+121 -10
View File
@@ -8,8 +8,12 @@
* to the real Gallery tab via the "Open in Gallery" button.
*/
import { VIDEO_GROUP, VTEMP_GROUP, ensureVideoGroup } from "./gallery-tab.js";
import { VIDEO_GROUP, VTEMP_GROUP, ensureVideoGroup, isVideoFile } from "./gallery-tab.js";
import { setSourcePreview } from "./video-preview.js";
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { addClipFromFile } from "./video-edit-tab.js";
import { setBlockImageFromFile } from "./video-plan-tab.js";
// Sentinel for the "All Video Assets" option — not a real backend group, since
// Gallery's group filter only ever matches one group at a time. Selecting it
@@ -27,8 +31,20 @@ const _s = {
images: [],
selectedPath: null,
loaded: false, // becomes true once the Asset subtab has been shown at least once
searchQuery: "",
viewMode: "grid", // "grid" | "table"
};
function _formatDate(mtime) {
return new Date(mtime * 1000).toLocaleString();
}
function _filteredImages() {
const q = _s.searchQuery.trim().toLowerCase();
if (!q) return _s.images;
return _s.images.filter((img) => img.filename.toLowerCase().includes(q));
}
async function _fetchOutputDir() {
if (_s.outputDir) return;
try {
@@ -92,7 +108,7 @@ async function _loadImages() {
images = await _fetchGroupImages(_s.group);
}
_s.images = images;
_renderGrid();
_renderList();
if (statusEl) statusEl.textContent = `${_s.images.length} video(s)`;
} catch (err) {
_s.images = [];
@@ -101,15 +117,55 @@ async function _loadImages() {
}
}
// Renders whichever of grid/table is active for the current viewMode — called
// on load, on search input, and after switching view modes.
function _renderList() {
if (_s.viewMode === "table") _renderTable();
else _renderGrid();
}
function _renderGrid() {
const grid = document.getElementById("wfm-video-asset-grid");
if (!grid) return;
if (_s.images.length === 0) {
const images = _filteredImages();
if (images.length === 0) {
grid.innerHTML = `<div class="wfm-placeholder">No videos yet</div>`;
return;
}
grid.innerHTML = "";
for (const img of _s.images) grid.appendChild(_makeCard(img));
for (const img of images) grid.appendChild(_makeCard(img));
}
function _renderTable() {
const body = document.getElementById("wfm-video-asset-table-body");
if (!body) return;
const images = _filteredImages();
if (images.length === 0) {
body.innerHTML = `<tr><td colspan="3" class="wfm-placeholder">No videos yet</td></tr>`;
return;
}
body.innerHTML = "";
for (const img of images) body.appendChild(_makeRow(img));
}
function _makeRow(img) {
const row = document.createElement("tr");
row.className = "wfm-video-asset-row" + (img.path === _s.selectedPath ? " selected" : "");
row.dataset.path = img.path;
const nameCell = document.createElement("td");
nameCell.textContent = img.filename;
nameCell.title = img.filename;
const dateCell = document.createElement("td");
dateCell.textContent = _formatDate(img.mtime);
const tagsCell = document.createElement("td");
tagsCell.textContent = (img.tags || []).join(", ");
row.append(nameCell, dateCell, tagsCell);
row.addEventListener("click", () => _selectImage(img));
return row;
}
function _makeCard(img) {
@@ -135,27 +191,30 @@ function _makeCard(img) {
function _selectImage(img) {
_s.selectedPath = img.path;
document.querySelectorAll(".wfm-video-asset-card").forEach((c) => {
document.querySelectorAll(".wfm-video-asset-card, .wfm-video-asset-row").forEach((c) => {
c.classList.toggle("selected", c.dataset.path === img.path);
});
_renderDetail(img);
_loadIntoSourcePreview(img);
}
// Feeds the selected asset's video into the center panel's Asset/Source preview
// Feeds the selected asset's media into the center panel's Asset/Source preview
// pane (see video-preview.js) so it's visible without switching tabs, and so the
// Frame/GIF property tools can operate on it just like a Video Source drop.
// Fetched as a Blob and wrapped as a "local" source rather than trying to map
// Gallery's arbitrary absolute path onto ComfyUI's filename/subfolder/type
// triple — that keeps the GIF tool's existing upload-on-first-use path working
// unchanged for both cases.
// unchanged for both cases. Still/animated images (this group isn't exclusively
// videos — anything tagged into it shows up here) preview via the pane's <img>
// companion element instead of trying to play them as a <video>.
async function _loadIntoSourcePreview(img) {
try {
const res = await fetch(`/wfm/gallery/image/serve?path=${encodeURIComponent(img.path)}`);
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
const file = new File([blob], img.filename, { type: blob.type || "video/mp4" });
setSourcePreview(URL.createObjectURL(file), { kind: "local", file });
const isVideo = isVideoFile(img);
const file = new File([blob], img.filename, { type: blob.type || (isVideo ? "video/mp4" : "image/png") });
setSourcePreview(URL.createObjectURL(file), { kind: "local", file }, isVideo ? "video" : "image");
} catch (err) {
console.warn("[VideoAsset] failed to load preview:", err);
}
@@ -178,7 +237,12 @@ function _renderDetail(img) {
<label style="margin-top:10px;">Memo</label>
<textarea id="wfm-video-asset-memo" class="wfm-textarea" rows="3"></textarea>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-memo-save" style="margin-top:6px;">Save Memo</button>
<button type="button" class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-video-asset-open-gallery" style="width:100%;margin-top:12px;">Open in Gallery</button>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-send-to-edit" style="width:100%;margin-top:12px;">${t("videoEditSendToEdit")}</button>
<div id="wfm-video-asset-set-plan-image-row" style="display:${isVideoFile(img) ? "none" : "flex"};gap:6px;margin-top:6px;">
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-set-first" style="flex:1;">${t("videoAssetSetAsFirst")}</button>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-set-last" style="flex:1;">${t("videoAssetSetAsLast")}</button>
</div>
<button type="button" class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-video-asset-open-gallery" style="width:100%;margin-top:6px;">Open in Gallery</button>
`;
const nameEl = document.getElementById("wfm-video-asset-name");
@@ -205,6 +269,36 @@ function _renderDetail(img) {
img.memo = memo;
});
panel.querySelector("#wfm-video-asset-send-to-edit")?.addEventListener("click", async () => {
try {
const res = await fetch(`/wfm/gallery/image/serve?path=${encodeURIComponent(img.path)}`);
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
const file = new File([blob], img.filename, { type: blob.type || (isVideoFile(img) ? "video/mp4" : "image/png") });
addClipFromFile(file, img.filename);
document.querySelector('.wfm-video-center-panel .wfm-video-subtab-btn[data-video-subtab="edit"]')?.click();
showToast(t("videoEditClipSent", img.filename), "success");
} catch (err) {
showToast(t("errorWithMsg", err.message), "error");
}
});
const setAsPlanImage = async (which) => {
try {
const res = await fetch(`/wfm/gallery/image/serve?path=${encodeURIComponent(img.path)}`);
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
const file = new File([blob], img.filename, { type: blob.type || "image/png" });
await setBlockImageFromFile(which, file);
document.querySelector('.wfm-video-center-panel .wfm-video-subtab-btn[data-video-subtab="plan"]')?.click();
showToast(t(which === "first" ? "videoAssetSetAsFirstDone" : "videoAssetSetAsLastDone", img.filename), "success");
} catch (err) {
showToast(t("errorWithMsg", err.message), "error");
}
};
panel.querySelector("#wfm-video-asset-set-first")?.addEventListener("click", () => setAsPlanImage("first"));
panel.querySelector("#wfm-video-asset-set-last")?.addEventListener("click", () => setAsPlanImage("last"));
panel.querySelector("#wfm-video-asset-open-gallery")?.addEventListener("click", () => {
document.querySelector('.wfm-tab[data-tab="gallery"]')?.click();
const filterSel = document.getElementById("wfm-gallery-group-filter");
@@ -275,6 +369,17 @@ export async function refreshVideoAssetTab() {
await _loadImages();
}
function _setViewMode(mode) {
_s.viewMode = mode;
document.getElementById("wfm-video-asset-view-grid")?.classList.toggle("active", mode === "grid");
document.getElementById("wfm-video-asset-view-table")?.classList.toggle("active", mode === "table");
const grid = document.getElementById("wfm-video-asset-grid");
const tableWrap = document.getElementById("wfm-video-asset-table-wrap");
if (grid) grid.style.display = mode === "grid" ? "" : "none";
if (tableWrap) tableWrap.style.display = mode === "table" ? "" : "none";
_renderList();
}
export function initVideoAssetTab() {
document.getElementById("wfm-video-asset-group")?.addEventListener("change", (e) => {
_s.group = e.target.value;
@@ -284,6 +389,12 @@ export function initVideoAssetTab() {
_loadImages();
});
document.getElementById("wfm-video-asset-refresh")?.addEventListener("click", () => _loadImages());
document.getElementById("wfm-video-asset-search")?.addEventListener("input", (e) => {
_s.searchQuery = e.target.value;
_renderList();
});
document.getElementById("wfm-video-asset-view-grid")?.addEventListener("click", () => _setViewMode("grid"));
document.getElementById("wfm-video-asset-view-table")?.addEventListener("click", () => _setViewMode("table"));
// Neither reserved group is ever auto-created by a batch run itself (see
// video-plan-tab.js's _ensureVideoAssetGroups, which only ensures
+958
View File
@@ -0,0 +1,958 @@
/**
* Video Tab - Edit subtab: a minimal non-linear-editor-style clip timeline
* (MVP scope: add clips, reorder, trim, concatenate, export).
*
* Design (see VIDEO_EDIT_TAB_PLAN.md at the repo root for the full writeup):
* - Every clip is uploaded to ComfyUI's `input` area on add (same
* upload-on-first-use pattern as video-tab.js's GIF tool), then probed
* via /api/wfm/video/edit/probe (PyAV, no ffmpeg) for duration/width/height.
* - Export builds a ComfyUI API-format prompt directly (LoadVideo -> VideoTrim
* per clip -> ConcatenateVideo (if >1 clip) -> SaveVideo) and runs it through
* the existing comfyUI.queuePrompt()/trackProgress() infra — no new backend
* "build workflow" endpoint needed.
* - Trim/scrub preview reuses the existing Source preview pane (video-preview.js)
* instead of a second <video> element — selecting a clip loads it there,
* exactly like video-asset-tab.js already does for asset selection.
*
* Confirmed against a live ComfyUI 0.36.0 instance (see plan doc "Phase 0"):
* - The class_type for the simple trim node is `"Video Slice"` (WITH A SPACE —
* `/object_info/VideoSlice` looks empty because that's not its real id; its
* node_id is literally "Video Slice"). It takes plain flat inputs
* (video/start_time/duration/strict_duration), no VIDEO_EDIT nesting, and
* is not experimental — this is what's used here, not `VideoTrim`.
* `VideoTrim`'s `trim` input, if ever needed, must be double-nested —
* `{"trim": {"start_time":.., "duration":..}}` — because its execute()
* does `(trim or {}).get("trim")` before reading start_time/duration; a
* flat `{"start_time":..}` value is silently accepted and silently
* no-ops (verified: it does NOT raise, it just doesn't trim anything).
* - `ConcatenateVideo`'s Autogrow `videos` input is addressed via flat,
* dot-joined keys at the top level of `inputs`: "videos.video0",
* "videos.video1", ... (0-indexed) — NOT a nested object and NOT plain
* "video0"/"video1" without the "videos." prefix.
* - ConcatenateVideo hard-errors at execution time if clip frame dimensions
* differ, so mismatched clips are blocked client-side before export —
* but only between VIDEO clips; an image clip is auto-fit (ImageScale,
* center-crop) to match, since it isn't fixed-resolution source footage.
*
* Image clips: a still or animated image dropped in has no inherent video
* duration, so it gets a user-editable "hold" length instead of in/out trim
* points (clip.trimStart stays 0, clip.trimEnd IS the hold length — this
* keeps it a drop-in replacement everywhere the code already reads
* trimEnd-trimStart as "this clip's length in the timeline", e.g. the block
* width calc and the total-duration readout). Export turns it into a real
* VIDEO segment via LoadImage -> (ImageScale, only if resolution needs to
* match) -> RepeatImageBatch(amount = holdSeconds * fps) -> CreateVideo —
* confirmed on a live instance to produce an exact-duration, correctly
* concatenation-compatible clip (see VIDEO_EDIT_TAB_PLAN.md "Image clips").
*/
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { comfyUI } from "./comfyui-client.js";
import {
setSourcePreview, setResultPreview, getActivePreviewVideoElement, getResultPreviewVideoElement,
} from "./video-preview.js";
import { VTEMP_GROUP, ensureVideoGroup } from "./gallery-tab.js";
const _s = {
clips: [], // { id, name, file, kind:"video"|"image", serverRef:{filename,subfolder,type}|null, duration, width, height, fps, trimStart, trimEnd, probing, error }
selectedId: null,
exporting: false,
nextId: 1,
outputDir: "",
};
// Pixel-per-second scale for the timeline track — clips are laid out at their
// real (trimmed) duration and left-aligned, NOT stretched to fill the track
// width like the Plan tab's blocks (whose widths are relative shares of a
// fixed-length plan) — Edit's timeline represents actual seconds.
const _PX_PER_SEC = 20;
const _MIN_BLOCK_PX = 56;
// Default hold length for a freshly-added image clip; user-adjustable per
// clip afterward in the trim panel.
const _DEFAULT_IMAGE_DURATION = 3.0;
// fps used when turning a held image into a video segment for export/preview
// concatenation — arbitrary but consistent (doesn't need to match other
// clips' native fps; ConcatenateVideo works at the container/frame level).
const _IMAGE_EXPORT_FPS = 24;
let _dragClipId = null; // clip being dragged for timeline reordering
// ============================================
// Output-dir lookup (same small helper video-asset-tab.js / video-plan-tab.js
// each keep their own copy of — needed to build the absolute path Gallery's
// group-tagging API expects).
// ============================================
async function _fetchOutputDir() {
if (_s.outputDir) return;
try {
const res = await fetch("/api/wfm/settings/output-dir");
if (res.ok) {
const data = await res.json();
_s.outputDir = (data.current || "").replace(/\\/g, "/").replace(/\/$/, "");
}
} catch { /* non-critical */ }
}
// ============================================
// Clip list state
// ============================================
function _selectedClip() {
return _s.clips.find((c) => c.id === _s.selectedId) || null;
}
// Exported so video-asset-tab.js's "Send to Edit" button can add an asset
// (already fetched as a Blob/File the same way it feeds the Source preview)
// without either module importing the other's internals.
export function addClipFromFile(file, displayName) {
const kind = file.type.startsWith("video/") ? "video" : "image";
const clip = {
id: _s.nextId++,
name: displayName || file.name,
file,
kind,
serverRef: null,
duration: kind === "image" ? _DEFAULT_IMAGE_DURATION : 0,
width: 0,
height: 0,
fps: 0,
trimStart: 0,
trimEnd: kind === "image" ? _DEFAULT_IMAGE_DURATION : 0,
probing: true,
error: null,
};
_s.clips.push(clip);
_s.selectedId = clip.id;
_renderTimeline();
_renderTrimPanel();
setSourcePreview(URL.createObjectURL(file), { kind: "local", file }, kind);
if (kind === "image") _probeImageClip(clip);
else _probeClip(clip);
}
async function _probeClip(clip) {
try {
const uploaded = await comfyUI.uploadImage(clip.file, clip.file.name);
clip.serverRef = { filename: uploaded.name, subfolder: uploaded.subfolder || "", type: "input" };
const params = new URLSearchParams({
filename: clip.serverRef.filename,
subfolder: clip.serverRef.subfolder,
type: clip.serverRef.type,
});
const res = await fetch(`/api/wfm/video/edit/probe?${params}`);
const json = await res.json();
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
clip.duration = json.duration || 0;
clip.width = json.width || 0;
clip.height = json.height || 0;
clip.fps = json.fps || 0;
clip.trimStart = 0;
clip.trimEnd = clip.duration;
} catch (err) {
clip.error = err.message;
showToast(t("errorWithMsg", err.message), "error");
} finally {
clip.probing = false;
_renderTimeline();
if (_s.selectedId === clip.id) _renderTrimPanel();
}
}
// Image dimensions are read client-side (no server round-trip needed — PyAV
// isn't reliable for opening arbitrary still-image formats as "video" the
// way it is for real video containers) via a throwaway <img>, revoking its
// blob URL once read either way.
function _readImageDimensions(file) {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => { URL.revokeObjectURL(url); resolve({ width: img.naturalWidth, height: img.naturalHeight }); };
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error("Failed to read image dimensions")); };
img.src = url;
});
}
async function _probeImageClip(clip) {
try {
const uploaded = await comfyUI.uploadImage(clip.file, clip.file.name);
clip.serverRef = { filename: uploaded.name, subfolder: uploaded.subfolder || "", type: "input" };
const dims = await _readImageDimensions(clip.file);
clip.width = dims.width;
clip.height = dims.height;
// duration/trimEnd already hold the default (or a previously-edited)
// hold length — probing an image only needs to fill in serverRef/size.
} catch (err) {
clip.error = err.message;
showToast(t("errorWithMsg", err.message), "error");
} finally {
clip.probing = false;
_renderTimeline();
if (_s.selectedId === clip.id) _renderTrimPanel();
}
}
function _moveClip(id, delta) {
const idx = _s.clips.findIndex((c) => c.id === id);
const target = idx + delta;
if (idx < 0 || target < 0 || target >= _s.clips.length) return;
[_s.clips[idx], _s.clips[target]] = [_s.clips[target], _s.clips[idx]];
_renderTimeline();
}
function _duplicateClip(id) {
const idx = _s.clips.findIndex((c) => c.id === id);
if (idx < 0) return;
const clone = { ..._s.clips[idx], id: _s.nextId++ };
_s.clips.splice(idx + 1, 0, clone);
_s.selectedId = clone.id;
_renderTimeline();
_renderTrimPanel();
}
function _deleteClip(id) {
_stopPreview();
_s.clips = _s.clips.filter((c) => c.id !== id);
if (_s.selectedId === id) {
_s.selectedId = _s.clips.length ? _s.clips[0].id : null;
if (_s.selectedId) _selectClip(_s.selectedId);
else setSourcePreview(null, null);
}
_renderTimeline();
_renderTrimPanel();
}
function _clearTimeline() {
if (_s.clips.length === 0) return;
if (!confirm(t("videoEditConfirmClear"))) return;
_stopPreview();
_s.clips = [];
_s.selectedId = null;
setSourcePreview(null, null);
_renderTimeline();
_renderTrimPanel();
}
function _selectClip(id) {
_s.selectedId = id;
const clip = _selectedClip();
_renderTimeline();
_renderTrimPanel();
if (clip) setSourcePreview(URL.createObjectURL(clip.file), { kind: "local", file: clip.file }, clip.kind);
}
// ============================================
// Resolution-mismatch guard — ConcatenateVideo hard-errors at execution time
// on mismatched frame dimensions (confirmed on a live 0.36.0 instance), so
// this is checked client-side before ever building the export graph. Only
// VIDEO clips are compared: an image clip's resolution is auto-fit at export
// time (see _buildExportWorkflow), so it can never be the thing blocking export.
// ============================================
function _findResolutionMismatch(clips) {
const sized = clips.filter((c) => c.kind === "video" && c.width && c.height);
if (sized.length < 2) return null;
const first = sized[0];
const mismatched = sized.find((c) => c.width !== first.width || c.height !== first.height);
if (!mismatched) return null;
return t("videoEditResolutionMismatch", `${first.name} (${first.width}x${first.height})`, `${mismatched.name} (${mismatched.width}x${mismatched.height})`);
}
// ============================================
// Rendering
// ============================================
function _fmtTime(s) {
if (!s && s !== 0) return "--";
return `${s.toFixed(1)}s`;
}
// M:SS.ds timecode for the trim scrubber's ruler ticks and badges (mirrors
// the "0:01.70" style Clipchamp-like editors use) — distinct from _fmtTime's
// coarser "1.7s" used elsewhere (timeline block meta, total-duration readout).
function _fmtTimecode(s) {
const clamped = Math.max(0, s || 0);
const m = Math.floor(clamped / 60);
const sec = clamped - m * 60;
return `${m}:${sec.toFixed(2).padStart(5, "0")}`;
}
// Horizontal timeline track (see VIDEO_EDIT_TAB_PLAN.md's UI redesign note):
// clips are laid out left-to-right at their real (trimmed) duration on a
// fixed px/sec scale and left-aligned — an empty track stays empty on the
// right rather than stretching clips to fill it. Reordering is done either
// by dragging a block onto another (native HTML5 DnD) or via the shared
// toolbar buttons below the track, which act on whichever clip is selected
// (mirrors the Plan subtab's "+Split/+Block/Delete" toolbar pattern instead
// of giving every row its own set of buttons).
function _renderTimeline() {
const track = document.getElementById("wfm-video-edit-timeline-track");
if (!track) return;
track.innerHTML = "";
if (_s.clips.length === 0) {
const placeholder = document.createElement("span");
placeholder.className = "wfm-placeholder wfm-video-edit-timeline-placeholder";
placeholder.textContent = t("videoEditNoClipsHint");
track.appendChild(placeholder);
_updateToolbarState();
return;
}
_s.clips.forEach((clip) => {
const block = document.createElement("div");
block.className = "wfm-video-edit-timeline-block" + (clip.id === _s.selectedId ? " selected" : "");
const seconds = clip.probing || clip.error ? 0 : Math.max(0.1, clip.trimEnd - clip.trimStart);
block.style.width = `${Math.max(_MIN_BLOCK_PX, Math.round(seconds * _PX_PER_SEC))}px`;
block.title = clip.name;
block.draggable = true;
const nameEl = document.createElement("div");
nameEl.className = "wfm-video-edit-timeline-block-name";
nameEl.textContent = `${clip.kind === "image" ? "🖼" : "🎬"} ${clip.name}`;
const metaEl = document.createElement("div");
metaEl.className = "wfm-video-edit-timeline-block-meta";
if (clip.probing) metaEl.textContent = t("videoEditProbing");
else if (clip.error) metaEl.textContent = "✗";
else metaEl.textContent = _fmtTime(clip.trimEnd - clip.trimStart);
block.append(nameEl, metaEl);
block.addEventListener("click", () => _selectClip(clip.id));
block.addEventListener("dragstart", (e) => {
_dragClipId = clip.id;
e.dataTransfer.effectAllowed = "move";
});
block.addEventListener("dragover", (e) => e.preventDefault());
block.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
_reorderByDrop(clip.id);
});
track.appendChild(block);
});
_updateToolbarState();
}
function _reorderByDrop(targetId) {
if (_dragClipId == null || _dragClipId === targetId) { _dragClipId = null; return; }
const fromIdx = _s.clips.findIndex((c) => c.id === _dragClipId);
_dragClipId = null;
if (fromIdx < 0) return;
// Remove first, then look up the target's index in the now-shortened array —
// sidesteps the off-by-one from a naive "look up both indices, then splice
// twice" approach when fromIdx < toIdx. Dropping onto a block inserts the
// dragged clip right before it; dropping past the last block (targetId
// null, from the track's own drop handler) appends to the end.
const [moved] = _s.clips.splice(fromIdx, 1);
if (targetId == null) {
_s.clips.push(moved);
} else {
const toIdx = _s.clips.findIndex((c) => c.id === targetId);
_s.clips.splice(toIdx < 0 ? _s.clips.length : toIdx, 0, moved);
}
_renderTimeline();
}
function _updateToolbarState() {
const idx = _s.clips.findIndex((c) => c.id === _s.selectedId);
const hasSelection = idx >= 0;
const setDisabled = (id, disabled) => {
const el = document.getElementById(id);
if (el) el.disabled = disabled;
};
setDisabled("wfm-video-edit-move-left-btn", !hasSelection || idx === 0);
setDisabled("wfm-video-edit-move-right-btn", !hasSelection || idx === _s.clips.length - 1);
setDisabled("wfm-video-edit-duplicate-btn", !hasSelection);
setDisabled("wfm-video-edit-delete-btn", !hasSelection);
setDisabled("wfm-video-edit-clear-btn", _s.clips.length === 0);
setDisabled("wfm-video-edit-preview-btn", _s.clips.length === 0);
_updateTotalDuration();
}
function _updateTotalDuration() {
const el = document.getElementById("wfm-video-edit-total-duration");
if (!el) return;
const total = _s.clips.reduce((sum, c) => {
if (c.probing || c.error) return sum;
return sum + Math.max(0, c.trimEnd - c.trimStart);
}, 0);
el.textContent = _s.clips.length === 0 ? "" : t("videoEditTotalDuration", _fmtTime(total));
}
// ============================================
// Trim scrubber — Clipchamp-style visual timeline for the selected video
// clip's trim panel: a time ruler, a draggable in/out range, and a playhead
// synced to the Source preview's <video> element. All positions are computed
// as percentages of clip.duration (not px/sec) so no separate zoom/scale
// bookkeeping is needed — the track just fills whatever width the panel gives it.
// ============================================
// Tracks the (element, listener) pair currently wired to a <video>'s
// "timeupdate" so it can be torn down before the next clip selection reuses
// the same persistent preview element (see video-preview.js) — otherwise
// listeners would pile up across every clip switch.
let _scrubVideoEl = null;
let _scrubVideoListener = null;
function _teardownTrimScrubber() {
if (_scrubVideoEl && _scrubVideoListener) {
_scrubVideoEl.removeEventListener("timeupdate", _scrubVideoListener);
}
_scrubVideoEl = null;
_scrubVideoListener = null;
}
// "Nice" tick spacing so the ruler shows roughly 5-8 labeled ticks regardless
// of clip length (a 3s clip gets 0.5s ticks, a 5min clip gets 60s ticks).
function _niceRulerStep(duration) {
const rough = duration / 6;
const candidates = [0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];
return candidates.find((c) => c >= rough) || candidates[candidates.length - 1];
}
function _renderRuler(ruler, duration) {
ruler.innerHTML = "";
if (!duration) return;
const step = _niceRulerStep(duration);
for (let time = 0; time <= duration + 0.001; time += step) {
const tick = document.createElement("span");
tick.className = "wfm-video-trim-ruler-tick";
tick.style.left = `${Math.min(100, (time / duration) * 100)}%`;
tick.textContent = _fmtTimecode(time).replace(/\.\d+$/, "");
ruler.appendChild(tick);
}
}
// Wires the scrubber DOM (already inserted into the trim panel by
// _renderTrimPanel) for one video clip. `commit` is the trim-panel's own
// start/end-input commit function — the scrubber drives it via the same
// inputs rather than writing clip.trimStart/trimEnd directly, so both paths
// (typed numbers, dragged handles) stay in sync through one code path.
function _wireTrimScrubber(clip, startInput, endInput, commit) {
const track = document.getElementById("wfm-video-trim-track");
const ruler = document.getElementById("wfm-video-trim-ruler");
const rangeEl = document.getElementById("wfm-video-trim-range");
const handleStart = document.getElementById("wfm-video-trim-handle-start");
const handleEnd = document.getElementById("wfm-video-trim-handle-end");
const playhead = document.getElementById("wfm-video-trim-playhead");
const badgeStart = document.getElementById("wfm-video-trim-badge-start");
const badgeEnd = document.getElementById("wfm-video-trim-badge-end");
const badgePlayhead = document.getElementById("wfm-video-trim-badge-playhead");
if (!track || !clip.duration) return;
_renderRuler(ruler, clip.duration);
const pct = (t) => `${Math.min(100, Math.max(0, (t / clip.duration) * 100))}%`;
function updateRange() {
rangeEl.style.left = pct(clip.trimStart);
rangeEl.style.width = `${Math.max(0, ((Math.min(clip.trimEnd, clip.duration) - clip.trimStart) / clip.duration) * 100)}%`;
handleStart.style.left = pct(clip.trimStart);
handleEnd.style.left = pct(clip.trimEnd);
badgeStart.textContent = _fmtTimecode(clip.trimStart);
badgeEnd.textContent = _fmtTimecode(clip.trimEnd);
}
updateRange();
function updatePlayhead(t) {
playhead.style.left = pct(t);
badgePlayhead.textContent = _fmtTimecode(t);
}
const video = getActivePreviewVideoElement();
if (video) {
_scrubVideoEl = video;
_scrubVideoListener = () => updatePlayhead(video.currentTime);
video.addEventListener("timeupdate", _scrubVideoListener);
updatePlayhead(video.currentTime);
} else {
updatePlayhead(0);
}
function seekTo(clientX) {
const rect = track.getBoundingClientRect();
const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
const t = ratio * clip.duration;
const v = getActivePreviewVideoElement();
if (v) v.currentTime = t;
updatePlayhead(t);
}
// Drags a trim handle: while pointer is down, only the scrubber's own
// visuals (range/handle position, badge text) update — clip.trimStart/End
// and the timeline block widths commit once on pointerup, so dragging
// doesn't thrash _renderTimeline() on every mousemove.
function wireHandleDrag(handleEl, isStart) {
handleEl.addEventListener("pointerdown", (e) => {
e.preventDefault();
e.stopPropagation();
handleEl.setPointerCapture(e.pointerId);
const onMove = (ev) => {
const rect = track.getBoundingClientRect();
const ratio = Math.min(1, Math.max(0, (ev.clientX - rect.left) / rect.width));
const t = ratio * clip.duration;
if (isStart) startInput.value = Math.min(t, clip.trimEnd - 0.05).toFixed(2);
else endInput.value = Math.max(t, clip.trimStart + 0.05).toFixed(2);
commit({ skipTimelineRerender: true });
updateRange();
};
const onUp = () => {
handleEl.removeEventListener("pointermove", onMove);
handleEl.removeEventListener("pointerup", onUp);
_renderTimeline();
};
handleEl.addEventListener("pointermove", onMove);
handleEl.addEventListener("pointerup", onUp);
});
}
wireHandleDrag(handleStart, true);
wireHandleDrag(handleEnd, false);
track.addEventListener("pointerdown", (e) => {
if (e.target === handleStart || e.target === handleEnd || e.target === playhead) return;
seekTo(e.clientX);
});
playhead.addEventListener("pointerdown", (e) => {
e.preventDefault();
e.stopPropagation();
playhead.setPointerCapture(e.pointerId);
const onMove = (ev) => seekTo(ev.clientX);
const onUp = () => {
playhead.removeEventListener("pointermove", onMove);
playhead.removeEventListener("pointerup", onUp);
};
playhead.addEventListener("pointermove", onMove);
playhead.addEventListener("pointerup", onUp);
});
}
function _renderTrimPanel() {
const panel = document.getElementById("wfm-video-edit-trim-panel");
if (!panel) return;
_teardownTrimScrubber();
const clip = _selectedClip();
if (!clip) {
panel.innerHTML = `<span class="wfm-placeholder">${t("videoEditSelectClipHint")}</span>`;
return;
}
if (clip.probing) {
panel.innerHTML = `<span class="wfm-placeholder">${t("videoEditProbing")}</span>`;
return;
}
if (clip.error) {
panel.innerHTML = `<span class="wfm-placeholder" style="color:var(--wfm-danger)">✗ ${clip.error}</span>`;
return;
}
// clip.name is a user-controlled filename — kept out of the innerHTML string
// and assigned via textContent afterward (same pattern as video-asset-tab.js's
// _renderDetail()), so it can never be interpreted as markup.
if (clip.kind === "image") {
panel.innerHTML = `
<div class="wfm-video-edit-clip-name" id="wfm-video-edit-trim-clip-name" style="margin-bottom:6px;"></div>
<div class="wfm-video-edit-trim-field" style="max-width:160px;">
<label>${t("videoEditImageDuration")}</label>
<input type="number" id="wfm-video-edit-image-duration" class="wfm-input" step="0.1" min="0.1" value="${clip.trimEnd.toFixed(2)}">
</div>
`;
const nameEl = document.getElementById("wfm-video-edit-trim-clip-name");
if (nameEl) { nameEl.textContent = clip.name; nameEl.title = clip.name; }
const durInput = document.getElementById("wfm-video-edit-image-duration");
durInput.addEventListener("change", () => {
const val = Math.max(0.1, Number(durInput.value) || _DEFAULT_IMAGE_DURATION);
clip.trimEnd = val;
clip.duration = val;
durInput.value = val.toFixed(2);
_renderTimeline();
});
return;
}
panel.innerHTML = `
<div class="wfm-video-edit-clip-name" id="wfm-video-edit-trim-clip-name" style="margin-bottom:6px;"></div>
<div class="wfm-video-trim-scrubber" id="wfm-video-trim-scrubber">
<div class="wfm-video-trim-ruler" id="wfm-video-trim-ruler"></div>
<div class="wfm-video-trim-track" id="wfm-video-trim-track">
<div class="wfm-video-trim-range" id="wfm-video-trim-range"></div>
<div class="wfm-video-trim-handle" id="wfm-video-trim-handle-start">
<span class="wfm-video-trim-badge" id="wfm-video-trim-badge-start"></span>
</div>
<div class="wfm-video-trim-handle" id="wfm-video-trim-handle-end">
<span class="wfm-video-trim-badge" id="wfm-video-trim-badge-end"></span>
</div>
<div class="wfm-video-trim-playhead" id="wfm-video-trim-playhead">
<span class="wfm-video-trim-badge wfm-video-trim-badge-playhead" id="wfm-video-trim-badge-playhead"></span>
</div>
</div>
</div>
<div class="wfm-video-edit-trim-row" style="margin-top:10px;">
<div class="wfm-video-edit-trim-field">
<label>${t("videoEditTrimStart")}</label>
<input type="number" id="wfm-video-edit-trim-start" class="wfm-input" step="0.1" min="0" max="${clip.duration}" value="${clip.trimStart.toFixed(2)}">
<button type="button" class="wfm-btn wfm-btn-xs wfm-video-edit-playhead-btn" id="wfm-video-edit-trim-start-set">${t("videoEditSetFromPlayhead")}</button>
</div>
<div class="wfm-video-edit-trim-field">
<label>${t("videoEditTrimEnd")}</label>
<input type="number" id="wfm-video-edit-trim-end" class="wfm-input" step="0.1" min="0" max="${clip.duration}" value="${clip.trimEnd.toFixed(2)}">
<button type="button" class="wfm-btn wfm-btn-xs wfm-video-edit-playhead-btn" id="wfm-video-edit-trim-end-set">${t("videoEditSetFromPlayhead")}</button>
</div>
</div>
`;
const nameEl = document.getElementById("wfm-video-edit-trim-clip-name");
if (nameEl) { nameEl.textContent = clip.name; nameEl.title = clip.name; }
const startInput = document.getElementById("wfm-video-edit-trim-start");
const endInput = document.getElementById("wfm-video-edit-trim-end");
// skipTimelineRerender: the scrubber's handle-drag calls this on every
// pointermove (see _wireTrimScrubber) — re-running _renderTimeline() that
// often would rebuild every timeline block per mousemove for no visible
// benefit, since the scrubber already redraws its own range live.
const commit = ({ skipTimelineRerender } = {}) => {
let start = Math.max(0, Math.min(Number(startInput.value) || 0, clip.duration));
let end = Math.max(0, Math.min(Number(endInput.value) || 0, clip.duration));
if (end <= start) end = Math.min(clip.duration, start + 0.1);
clip.trimStart = start;
clip.trimEnd = end;
startInput.value = start.toFixed(2);
endInput.value = end.toFixed(2);
if (!skipTimelineRerender) _renderTimeline();
};
startInput.addEventListener("change", commit);
endInput.addEventListener("change", commit);
document.getElementById("wfm-video-edit-trim-start-set")?.addEventListener("click", () => {
const video = getActivePreviewVideoElement();
if (video) { startInput.value = video.currentTime.toFixed(2); commit(); }
});
document.getElementById("wfm-video-edit-trim-end-set")?.addEventListener("click", () => {
const video = getActivePreviewVideoElement();
if (video) { endInput.value = video.currentTime.toFixed(2); commit(); }
});
_wireTrimScrubber(clip, startInput, endInput, commit);
}
// ============================================
// Sequential timeline preview — plays every ready clip back-to-back (each
// trimmed to its in/out point) in the shared "Result" pane (the same one
// Export writes its finished output into), so what plays there is always
// exactly what Export would currently produce. Deliberately reuses that pane
// rather than a third <video> element: the user asked for it to be the same
// slot the exported video lands in, not a separate preview area.
// ============================================
let _previewPlaying = false;
let _previewClips = [];
let _previewIndex = 0;
let _previewImageTimer = null; // holds an image clip on screen for its duration (setTimeout, no video events to hook)
function _onPreviewTimeUpdate() {
const video = getResultPreviewVideoElement();
const clip = _previewClips[_previewIndex];
if (!video || !clip || clip.kind !== "video") return;
if (video.currentTime >= clip.trimEnd) _advancePreview();
}
function _advancePreview() {
_previewIndex += 1;
if (_previewIndex >= _previewClips.length) { _stopPreview(); return; }
_playPreviewClip();
}
function _playPreviewClip() {
const clip = _previewClips[_previewIndex];
if (!clip) { _stopPreview(); return; }
if (clip.kind === "image") {
const video = getResultPreviewVideoElement();
video?.pause();
setResultPreview(URL.createObjectURL(clip.file), { kind: "local", file: clip.file }, "image");
const holdMs = Math.max(50, (clip.trimEnd - clip.trimStart) * 1000);
_previewImageTimer = setTimeout(_advancePreview, holdMs);
return;
}
const video = getResultPreviewVideoElement();
if (!video) { _stopPreview(); return; }
setResultPreview(URL.createObjectURL(clip.file), { kind: "local", file: clip.file }, "video");
// currentTime only reliably applies once the new source has metadata —
// setting it immediately after swapping src is flaky across browsers.
const onReady = () => {
video.removeEventListener("loadedmetadata", onReady);
video.currentTime = clip.trimStart;
video.play().catch(() => {});
};
video.addEventListener("loadedmetadata", onReady);
}
function _startPreview() {
_previewClips = _s.clips.filter((c) => !c.probing && !c.error);
if (_previewClips.length === 0) {
showToast(t("videoEditNoClips"), "error");
return;
}
_previewIndex = 0;
_previewPlaying = true;
const video = getResultPreviewVideoElement();
video?.addEventListener("timeupdate", _onPreviewTimeUpdate);
video?.addEventListener("ended", _advancePreview);
_playPreviewClip();
_updatePreviewBtn();
}
function _stopPreview() {
_previewPlaying = false;
if (_previewImageTimer) { clearTimeout(_previewImageTimer); _previewImageTimer = null; }
const video = getResultPreviewVideoElement();
video?.removeEventListener("timeupdate", _onPreviewTimeUpdate);
video?.removeEventListener("ended", _advancePreview);
video?.pause();
_updatePreviewBtn();
}
function _togglePreview() {
if (_previewPlaying) _stopPreview();
else _startPreview();
}
function _updatePreviewBtn() {
const btn = document.getElementById("wfm-video-edit-preview-btn");
if (btn) btn.textContent = _previewPlaying ? t("videoEditPreviewStop") : t("videoEditPreviewPlay");
}
// ============================================
// Export — builds a ComfyUI API-format prompt directly (see module header for
// the confirmed input formats) and runs it through the existing execution
// infrastructure (comfyui-client.js), exactly like video-plan-tab.js does.
// ============================================
function _buildExportWorkflow(clips) {
const prompt = {};
let nextId = 1;
const alloc = () => String(nextId++);
const trimOutputs = [];
// Auto-fit target for image clips: the first VIDEO clip's resolution, so
// a still dropped alongside real footage doesn't need to be pre-sized by
// hand (see _findResolutionMismatch, which only ever compares VIDEO
// clips against each other — images are exempt because of this fit step).
const videoClip = clips.find((c) => c.kind === "video");
const targetW = videoClip ? videoClip.width : clips[0]?.width;
const targetH = videoClip ? videoClip.height : clips[0]?.height;
// Only strip audio when clips will actually be concatenated — a single
// video clip never goes through ConcatenateVideo, so there's no mixed-
// audio compatibility problem to avoid and its audio can be kept intact.
const needsUniformSilence = clips.length > 1;
for (const clip of clips) {
const file = clip.serverRef.subfolder
? `${clip.serverRef.subfolder}/${clip.serverRef.filename}`
: clip.serverRef.filename;
if (clip.kind === "image") {
const loadId = alloc();
prompt[loadId] = { class_type: "LoadImage", inputs: { image: file } };
let imageOut = [loadId, 0];
if (targetW && targetH && (clip.width !== targetW || clip.height !== targetH)) {
const scaleId = alloc();
prompt[scaleId] = {
class_type: "ImageScale",
inputs: { image: imageOut, upscale_method: "lanczos", width: targetW, height: targetH, crop: "center" },
};
imageOut = [scaleId, 0];
}
const repeatId = alloc();
const amount = Math.max(1, Math.round((clip.trimEnd - clip.trimStart) * _IMAGE_EXPORT_FPS));
prompt[repeatId] = { class_type: "RepeatImageBatch", inputs: { image: imageOut, amount } };
const createId = alloc();
prompt[createId] = {
class_type: "CreateVideo",
inputs: { images: [repeatId, 0], fps: _IMAGE_EXPORT_FPS, codec: "auto" },
};
trimOutputs.push(createId);
continue;
}
const loadId = alloc();
prompt[loadId] = { class_type: "LoadVideo", inputs: { file } };
const trimId = alloc();
prompt[trimId] = {
class_type: "Video Slice",
inputs: {
video: [loadId, 0],
start_time: clip.trimStart,
duration: Math.max(0.05, clip.trimEnd - clip.trimStart),
strict_duration: false,
},
};
if (!needsUniformSilence) {
trimOutputs.push(trimId);
continue;
}
// Strip audio by decomposing/recomposing through GetVideoComponents ->
// CreateVideo (audio input left unset). Verified on a live instance:
// ConcatenateVideo hard-errors mixing a clip with stereo/32kHz audio
// next to a silent image-derived clip ("audio layout: expected None,
// got 'stereo'"), so every clip is made silent whenever more than one
// clip is being concatenated. This means a multi-clip export never
// carries audio — a known MVP limitation, not handled per-clip
// because ConcatenateVideo needs uniform audio across all inputs. A
// lone clip (see needsUniformSilence above) keeps its original audio.
const componentsId = alloc();
prompt[componentsId] = { class_type: "GetVideoComponents", inputs: { video: [trimId, 0] } };
const silentId = alloc();
prompt[silentId] = {
class_type: "CreateVideo",
inputs: { images: [componentsId, 0], fps: [componentsId, 2], codec: "auto" },
};
trimOutputs.push(silentId);
}
let finalOutput;
if (trimOutputs.length === 1) {
finalOutput = [trimOutputs[0], 0];
} else {
const concatId = alloc();
const inputs = { codec: "auto" };
// Autogrow's flat "videos.videoN" key format — see module header.
trimOutputs.forEach((tid, i) => { inputs[`videos.video${i}`] = [tid, 0]; });
prompt[concatId] = { class_type: "ConcatenateVideo", inputs };
finalOutput = [concatId, 0];
}
const saveId = alloc();
prompt[saveId] = {
class_type: "SaveVideo",
inputs: { video: finalOutput, filename_prefix: "video/wfm_edit", format: "auto" },
};
return { prompt, saveId };
}
function _setExportUi(running, pct) {
const btn = document.getElementById("wfm-video-edit-export-btn");
const bar = document.getElementById("wfm-video-edit-progress-bar");
const text = document.getElementById("wfm-video-edit-progress-text");
if (btn) btn.disabled = running;
if (bar) bar.style.width = `${Math.round((pct || 0) * 100)}%`;
if (text) text.textContent = running ? t("videoEditExporting") : "Ready";
}
async function _addOutputToVideoTemp(filename, subfolder) {
await _fetchOutputDir();
if (!_s.outputDir) return;
const parts = [_s.outputDir];
if (subfolder) parts.push(subfolder);
parts.push(filename);
const path = parts.join("/");
try {
await ensureVideoGroup();
await fetch(`/wfm/gallery/groups/${encodeURIComponent(VTEMP_GROUP)}/add`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path }),
});
} catch (err) {
console.warn("[VideoEdit] failed to tag export into video group:", err);
}
}
async function _exportTimeline() {
if (_s.exporting) return;
_stopPreview();
const readyClips = _s.clips.filter((c) => c.serverRef && !c.error);
if (readyClips.length === 0) {
showToast(t("videoEditNoClips"), "error");
return;
}
if (_s.clips.some((c) => c.probing)) {
showToast(t("videoEditStillProbing"), "error");
return;
}
const mismatch = _findResolutionMismatch(readyClips);
if (mismatch) {
showToast(mismatch, "error");
return;
}
_s.exporting = true;
_setExportUi(true, 0);
try {
const wsOk = await comfyUI.connectWebSocket();
if (!wsOk) throw new Error("Failed to connect WebSocket");
const { prompt, saveId } = _buildExportWorkflow(readyClips);
const result = await comfyUI.queuePrompt(prompt);
await comfyUI.trackProgress(result.prompt_id, (pct) => _setExportUi(true, pct));
const history = await comfyUI.getHistory(result.prompt_id);
const output = history?.outputs?.[saveId]?.images?.[0];
if (!output) throw new Error("No output produced");
const params = new URLSearchParams({ filename: output.filename, subfolder: output.subfolder || "", type: "output" });
setResultPreview(`${comfyUI.baseUrl}/view?${params}`, { kind: "output", filename: output.filename, subfolder: output.subfolder || "", type: "output" });
showToast(t("videoEditExportDone", output.filename), "success");
await _addOutputToVideoTemp(output.filename, output.subfolder);
} catch (err) {
showToast(t("errorWithMsg", err.message), "error");
} finally {
_s.exporting = false;
_setExportUi(false, 0);
}
}
// ============================================
// Init
// ============================================
function _wireToolbar() {
document.getElementById("wfm-video-edit-move-left-btn")?.addEventListener("click", () => {
if (_s.selectedId != null) _moveClip(_s.selectedId, -1);
});
document.getElementById("wfm-video-edit-move-right-btn")?.addEventListener("click", () => {
if (_s.selectedId != null) _moveClip(_s.selectedId, 1);
});
document.getElementById("wfm-video-edit-duplicate-btn")?.addEventListener("click", () => {
if (_s.selectedId != null) _duplicateClip(_s.selectedId);
});
document.getElementById("wfm-video-edit-delete-btn")?.addEventListener("click", () => {
if (_s.selectedId != null) _deleteClip(_s.selectedId);
});
document.getElementById("wfm-video-edit-preview-btn")?.addEventListener("click", _togglePreview);
document.getElementById("wfm-video-edit-clear-btn")?.addEventListener("click", _clearTimeline);
// Dropping a dragged block past the last one (onto empty track space)
// moves it to the end — block-level drop handlers stopPropagation() so
// this only fires for drops that miss every block.
const track = document.getElementById("wfm-video-edit-timeline-track");
track?.addEventListener("dragover", (e) => e.preventDefault());
track?.addEventListener("drop", (e) => {
e.preventDefault();
_reorderByDrop(null);
});
}
export function initVideoEditTab() {
_wireToolbar();
document.getElementById("wfm-video-edit-export-btn")?.addEventListener("click", _exportTimeline);
_renderTimeline();
_renderTrimPanel();
_updatePreviewBtn();
}
+23 -2
View File
@@ -290,10 +290,13 @@ function _wireBlockImageDropZone(which) {
});
}
// Returns true/false so setBlockImageFromFile (called from outside the Plan
// subtab, where this status text may not even be visible) can tell its own
// caller whether the upload actually succeeded instead of just assuming so.
async function _handleBlockImageUpload(which, file) {
if (!file || !file.type.startsWith("image/")) return;
if (!file || !file.type.startsWith("image/")) return false;
const block = _plan.blocks.find((b) => b.id === _selectedBlockId);
if (!block) return;
if (!block) return false;
const statusEl = document.getElementById(`wfm-video-block-${which}-status`);
const previewImg = document.getElementById(`wfm-video-block-${which}-preview`);
const wrap = document.getElementById(`wfm-video-block-${which}-wrap`);
@@ -309,11 +312,29 @@ async function _handleBlockImageUpload(which, file) {
if (which === "first") { block.first_image_filename = result.name; block.first_image_mode = "explicit"; }
else block.last_image_filename = result.name;
if (statusEl) { statusEl.textContent = `✓ ${result.name}`; statusEl.style.color = "var(--wfm-success)"; }
return true;
} catch (err) {
if (statusEl) { statusEl.textContent = `✗ ${err.message}`; statusEl.style.color = "var(--wfm-danger)"; }
return false;
}
}
// Exported so other modules (video-asset-tab.js's "Set as First/Last Image"
// buttons) can seed the currently-selected Plan block's First/Last Image from
// an already-fetched File — reuses the exact upload + first_image_mode
// bookkeeping the drop-zone UI itself uses, then re-renders the block editor
// so its dropdown/preview reflect the change even if the Plan subtab wasn't
// the one visible when this was called. _plan.blocks always has at least one
// entry (see _emptyBlock's initializer), so this only ever fails to find a
// block if _selectedBlockId itself has gone stale somehow.
export async function setBlockImageFromFile(which, file) {
const block = _plan.blocks.find((b) => b.id === _selectedBlockId);
if (!block) throw new Error(t("videoNoBlockSelected"));
const ok = await _handleBlockImageUpload(which, file);
_renderBlockEditor();
if (!ok) throw new Error(t("videoBlockImageUploadFailed"));
}
function _clearBlockImage(which) {
const block = _plan.blocks.find((b) => b.id === _selectedBlockId);
if (!block) return;
+45 -14
View File
@@ -8,25 +8,34 @@
* lets all three depend on it without needing to import each other —
* video-tab.js already imports both of the others for init/refresh, so a
* reverse import from either back into video-tab.js would create a cycle.
*
* Each pane also has a companion <img> element (wfm-video-*-preview-img) so a
* still/animated image (from Asset or a Video Source drop) can be previewed
* without forcing it through a <video> tag, which can't render image formats
* at all. mediaType controls which element is shown; Frame/GIF's
* getActivePreviewVideoElement() returns null while a pane is showing an
* image, since those tools only make sense against real video.
*/
const _PANES = {
source: { video: "wfm-video-source-preview-video", placeholder: "wfm-video-source-preview-placeholder" },
result: { video: "wfm-video-preview-video", placeholder: "wfm-video-preview-placeholder" },
source: { video: "wfm-video-source-preview-video", img: "wfm-video-source-preview-img", placeholder: "wfm-video-source-preview-placeholder" },
result: { video: "wfm-video-preview-video", img: "wfm-video-preview-img", placeholder: "wfm-video-preview-placeholder" },
};
const _objectUrls = { source: null, result: null };
// Whichever pane most recently received a video is what the Frame/GIF property
// Whichever pane most recently received media is what the Frame/GIF property
// tabs act on (see getActivePreviewSource/getActivePreviewVideoElement below) —
// an Asset selection or Video Source drop activates "source", a batch run
// finishing a block activates "result".
// finishing a block (or the Edit tab's export/preview) activates "result".
let _activePane = null; // "source" | "result" | null
let _activeSource = null;
let _activeMediaType = null; // "video" | "image" | null — mirrors _activePane's current content
function _setPreview(pane, url, source) {
function _setPreview(pane, url, source, mediaType = "video") {
const ids = _PANES[pane];
const video = document.getElementById(ids.video);
const img = document.getElementById(ids.img);
const placeholder = document.getElementById(ids.placeholder);
if (!video || !placeholder) return;
@@ -37,31 +46,44 @@ function _setPreview(pane, url, source) {
if (url && url.startsWith("blob:")) _objectUrls[pane] = url;
if (url) {
video.src = url;
video.style.display = "block";
if (mediaType === "image") {
video.pause();
video.removeAttribute("src");
video.load();
video.style.display = "none";
if (img) { img.src = url; img.style.display = "block"; }
} else {
if (img) { img.removeAttribute("src"); img.style.display = "none"; }
video.src = url;
video.style.display = "block";
}
placeholder.style.display = "none";
_activePane = pane;
_activeSource = source;
_activeMediaType = mediaType;
} else {
video.pause();
video.removeAttribute("src");
video.load();
video.style.display = "none";
if (img) { img.removeAttribute("src"); img.style.display = "none"; }
placeholder.style.display = "";
if (_activePane === pane) { _activePane = null; _activeSource = null; }
if (_activePane === pane) { _activePane = null; _activeSource = null; _activeMediaType = null; }
}
}
// Sets (or clears, with url=null) the Asset-selection/Video-Source-drop pane.
export function setSourcePreview(url, source) { _setPreview("source", url, source); }
// mediaType: "video" (default) or "image".
export function setSourcePreview(url, source, mediaType = "video") { _setPreview("source", url, source, mediaType); }
// Sets (or clears) the generated-result pane — called once per block as a
// batch run's video output comes in.
export function setResultPreview(url, source) { _setPreview("result", url, source); }
// batch run's video output comes in, and by the Edit tab's timeline preview
// (which may show either a video clip or a held still image).
export function setResultPreview(url, source, mediaType = "video") { _setPreview("result", url, source, mediaType); }
// What the Frame/GIF property tabs operate on: { kind: "output"|"input", filename,
// subfolder, type } for anything already on the server, or { kind: "local", file }
// for a picked/dropped file not yet uploaded. null if neither pane has a video.
// for a picked/dropped file not yet uploaded. null if neither pane has media.
export function getActivePreviewSource() { return _activeSource; }
// The GIF tab uploads a still-local source on first use and needs to remember
@@ -70,9 +92,10 @@ export function getActivePreviewSource() { return _activeSource; }
export function updateActivePreviewSourceRef(source) { _activeSource = source; }
// The <video> element the Frame/GIF tools should read/capture from, or null if
// neither pane currently has a video loaded.
// neither pane currently has a video loaded (including when the active pane is
// showing a still image instead).
export function getActivePreviewVideoElement() {
if (!_activePane) return null;
if (!_activePane || _activeMediaType === "image") return null;
return document.getElementById(_PANES[_activePane].video);
}
@@ -80,3 +103,11 @@ export function getActivePreviewVideoElement() {
export function getAllPreviewVideoElements() {
return Object.values(_PANES).map((ids) => document.getElementById(ids.video)).filter(Boolean);
}
// Direct access to the "result" pane's <video> element — used by
// video-edit-tab.js's timeline preview, which needs to drive playback
// (seek to a clip's trim-in, listen for the trim-out point, swap to the
// next clip) rather than just set a src via setResultPreview().
export function getResultPreviewVideoElement() {
return document.getElementById(_PANES.result.video);
}
+95 -12
View File
@@ -17,6 +17,8 @@ import { applyStoredVideoVolume } from "./settings-tab.js";
import { initVideoPlanTab, loadWorkflowIntoVideoEditor } from "./video-plan-tab.js";
import { initVideoAssetTab, refreshVideoAssetTab } from "./video-asset-tab.js";
import { initVideoProjectTab, refreshVideoProjectTab } from "./video-project-tab.js";
import { initVideoEditTab, addClipFromFile } from "./video-edit-tab.js";
import { VIDEO_GROUP, ensureVideoGroup } from "./gallery-tab.js";
import {
setSourcePreview, getActivePreviewSource, updateActivePreviewSourceRef,
getActivePreviewVideoElement, getAllPreviewVideoElements,
@@ -26,10 +28,10 @@ export { loadWorkflowIntoVideoEditor };
// ============================================
// Subtab switching — two INDEPENDENT groups sharing the same .wfm-video-subtab-*
// look, kept deliberately uncoupled: the sidebar's Asset/Project pair collapses
// entirely when re-clicked (nothing needs to always be visible there — Video
// Source covers the "load something to work with" case), while the center
// Plan/Edit pair is a "always exactly one visible" 2-way tab. Querying each
// look, kept deliberately uncoupled: the sidebar's Project button collapses its
// panel entirely when re-clicked (nothing needs to always be visible there —
// Video Source covers the "load something to work with" case), while the center
// Plan/Edit/Asset trio is a "always exactly one visible" tab group. Querying each
// scoped to its own container (rather than one global querySelectorAll) is
// what keeps clicking one from affecting the other.
// ============================================
@@ -45,13 +47,14 @@ function _initCenterSubtabToggle() {
scope.querySelectorAll(".wfm-video-subtab-panel").forEach((p) => {
p.style.display = p.dataset.videoSubtabPanel === target ? "" : "none";
});
if (target === "asset") refreshVideoAssetTab();
});
});
}
// Sidebar Asset/Project pair: clicking a button shows its panel and hides the
// other; clicking the already-active button collapses it (both panels hidden),
// letting the video preview reclaim the sidebar's width when neither is needed.
// Sidebar Project button: clicking it shows its panel; clicking it again while
// active collapses it, letting the video preview reclaim the sidebar's width
// when it isn't needed.
function _initSidebarSubtabToggle() {
const sidebar = document.querySelector(".wfm-video-form-panel");
if (!sidebar) return;
@@ -66,8 +69,7 @@ function _initSidebarSubtabToggle() {
if (willShow) {
btn.classList.add("active");
panel.style.display = "";
if (target === "asset") refreshVideoAssetTab();
else if (target === "project") refreshVideoProjectTab();
if (target === "project") refreshVideoProjectTab();
}
});
});
@@ -103,7 +105,17 @@ function _applyVideoI18n() {
const el = document.getElementById(id);
if (el) el.textContent = t(key);
};
setText("wfm-video-edit-placeholder-label", "videoEditPlaceholder");
const setTitle = (id, key) => {
const el = document.getElementById(id);
if (el) el.title = t(key);
};
setText("wfm-video-edit-export-btn", "videoEditExportBtn");
setTitle("wfm-video-edit-move-left-btn", "videoEditMoveLeft");
setTitle("wfm-video-edit-move-right-btn", "videoEditMoveRight");
setText("wfm-video-edit-duplicate-btn", "videoEditDuplicate");
setText("wfm-video-edit-delete-btn", "videoEditDelete");
setText("wfm-video-edit-clear-btn", "videoEditClearBtn");
setText("wfm-video-source-add-to-edit", "videoSourceAddToEdit");
setText("wfm-video-source-label", "videoSourceLabel");
setText("wfm-video-source-hint", "videoSourceHint");
setText("wfm-video-source-drop-label", "videoSourceDropLabel");
@@ -131,12 +143,40 @@ function _applyVideoI18n() {
function _wireVideoSourcePanel() {
_wireDropZone("wfm-video-source-drop", "wfm-video-source-file", (file) => {
if (!file.type.startsWith("video/")) return;
const isVideo = file.type.startsWith("video/");
const isImage = file.type.startsWith("image/");
if (!isVideo && !isImage) return;
const statusEl = document.getElementById("wfm-video-source-status");
setSourcePreview(URL.createObjectURL(file), { kind: "local", file });
setSourcePreview(URL.createObjectURL(file), { kind: "local", file }, isVideo ? "video" : "image");
if (statusEl) { statusEl.textContent = file.name; statusEl.style.color = ""; }
});
// "Add to Edit" — explicit, user-triggered handoff from whatever is loaded
// in the Source pane (a plain drop, an Asset selection, a Frame/GIF-tool
// source) into the Edit subtab's clip timeline. Deliberately NOT automatic
// on every Source drop — Frame/GIF is a single-video tool the user reaches
// for far more often than multi-clip editing, so auto-adding would clutter
// the Edit timeline with videos the user never meant to combine.
document.getElementById("wfm-video-source-add-to-edit")?.addEventListener("click", async () => {
const ref = getActivePreviewSource();
if (!ref) { showToast(t("videoNoSourceLoaded"), "error"); return; }
try {
let file;
if (ref.kind === "local") {
file = ref.file;
} else {
const blob = await comfyUI.getImageBlob(ref);
const isVideoExt = /\.(mp4|webm|mkv|mov)$/i.test(ref.filename || "");
file = new File([blob], ref.filename, { type: blob.type || (isVideoExt ? "video/mp4" : "image/png") });
}
addClipFromFile(file);
document.querySelector('.wfm-video-center-panel .wfm-video-subtab-btn[data-video-subtab="edit"]')?.click();
showToast(t("videoEditClipSent", file.name), "success");
} catch (err) {
showToast(t("errorWithMsg", err.message), "error");
}
});
document.getElementById("wfm-video-source-clear")?.addEventListener("click", () => {
setSourcePreview(null, null);
const statusEl = document.getElementById("wfm-video-source-status");
@@ -170,6 +210,7 @@ function _initPropTabs() {
// ============================================
let _capturedFrameBlob = null;
let _frameOutputDir = "";
function _blobToDataUrl(blob) {
return new Promise((resolve, reject) => {
@@ -180,6 +221,44 @@ function _blobToDataUrl(blob) {
});
}
// Same small output-dir lookup each of video-asset-tab.js/video-plan-tab.js/
// video-edit-tab.js keeps its own copy of — needed to build the absolute path
// Gallery's group-tagging API expects.
async function _fetchFrameOutputDir() {
if (_frameOutputDir) return;
try {
const res = await fetch("/api/wfm/settings/output-dir");
if (res.ok) {
const data = await res.json();
_frameOutputDir = (data.current || "").replace(/\\/g, "/").replace(/\/$/, "");
}
} catch { /* non-critical */ }
}
// Opt-in tagging of a saved frame into Gallery's curated __Video Assets__
// group (see the "Add to Video Assets group" checkbox) — mirrors
// video-edit-tab.js's _addOutputToVideoTemp, but targets the curated group
// directly since a manually-captured frame is a deliberate keep, not the
// every-run scratch output __Video Temp__ exists for.
async function _addFrameToVideoAssets(filename, subfolder) {
await _fetchFrameOutputDir();
if (!_frameOutputDir) return;
const parts = [_frameOutputDir];
if (subfolder) parts.push(subfolder);
parts.push(filename);
const path = parts.join("/");
try {
await ensureVideoGroup();
await fetch(`/wfm/gallery/groups/${encodeURIComponent(VIDEO_GROUP)}/add`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path }),
});
} catch (err) {
console.warn("[VideoTab] failed to tag frame into video group:", err);
}
}
function _initFrameTab() {
const captureBtn = document.getElementById("wfm-video-frame-capture-btn");
const saveBtn = document.getElementById("wfm-video-frame-save-btn");
@@ -226,6 +305,9 @@ function _initFrameTab() {
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
if (statusEl) { statusEl.textContent = `✓ ${json.filename}`; statusEl.style.color = "var(--wfm-success)"; }
showToast(t("videoFrameSaved", json.filename), "success");
if (document.getElementById("wfm-video-frame-add-to-assets")?.checked) {
await _addFrameToVideoAssets(json.filename, json.subfolder);
}
} catch (err) {
if (statusEl) { statusEl.textContent = `✗ ${err.message}`; statusEl.style.color = "var(--wfm-danger)"; }
showToast(t("errorWithMsg", err.message), "error");
@@ -321,6 +403,7 @@ export function initVideoTab() {
initVideoPlanTab();
initVideoAssetTab();
initVideoProjectTab();
initVideoEditTab();
_wireVideoSourcePanel();
_initPropTabs();
+78 -20
View File
@@ -2099,7 +2099,7 @@
<div class="wfm-help-page" id="wfm-help-page-video">
<h2 id="wfm-help-video-title">Video Tab</h2>
<p id="wfm-help-video-desc">A dedicated video generation tab for MiniMax H3 (Image to Video), LTX-2.5 (Text / Image / First & Last Frame to Video), and Wan2.2 (Text to Video) workflows, independent of the GenerateUI tab. The center panel's Plan / Edit subtabs handle batch generation and (future) editing; the sidebar's Asset / Project subtabs handle browsing generated videos and saved plans.</p>
<p id="wfm-help-video-desc">A dedicated video generation tab for MiniMax H3 (Image to Video), LTX-2.5 (Text / Image / First & Last Frame to Video), and Wan2.2 (Text to Video) workflows, independent of the GenerateUI tab. The center panel's Plan / Edit / Asset subtabs handle batch generation, clip editing, and browsing generated videos; the sidebar's Project subtab handles saved plans.</p>
<div class="wfm-help-card">
<ul>
<li id="wfm-help-video-1">Plan subtab: the topbar's settings row holds Aspect Ratio / Megapixels / Multiple / Duration (seconds) / Noise Seed as this plan's base settings — Duration always reflects the currently selected block (each block keeps its own value), the rest are plan-wide. A second row below adds Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance, each enabled only for workflows that actually support it (see helpVideo2). Split the timeline into blocks with the + Split / + Block / Delete buttons — each block has its own Prompt, Duration, and First/Last Image — First Image can be None, an explicit image, or "use previous block's last frame" (an explicit Last Image on the previous block always wins over extracting one from its generated video). Click Run to generate every block in order; Pause/Cancel work mid-run.</li>
@@ -2107,11 +2107,13 @@
<li id="wfm-help-video-3">Use the "Load in Video" button in the Workflow tab's detail modal to load a workflow containing a MiniMax H3 Image-to-Video node, an LTX-2.5 Text/Image/First&Last-Frame-to-Video node, or a Wan2.2 Text-to-Video node — this starts a fresh single-block plan seeded from the workflow's own current values. Unsupported workflows show an error instead.</li>
<li id="wfm-help-video-4">Generated videos (mp4) automatically appear in the Asset subtab's Video Temp group, and can also be browsed and played back in the Gallery tab. Organizing keepers into Video Assets is entirely up to you, on your own schedule.</li>
<li id="wfm-help-video-5">The center panel shows two previews: the left one shows either the video you select in the Asset subtab or whatever you drop/pick in the Video Source panel on its left (Clear resets it to empty), letting you use the Frame/GIF tools without running the loaded video workflow first; the right one always shows the most recently generated clip.</li>
<li id="wfm-help-video-6">Frame tab (right panel): play/seek the preview video to the position you want, click Capture Frame to grab that frame client-side, then Save to Output to write it as a PNG into ComfyUI's output folder.</li>
<li id="wfm-help-video-6">Frame tab (right panel): play/seek the preview video to the position you want, click Capture Frame to grab that frame client-side, then Save to Output to write it as a PNG into ComfyUI's output folder — check "Add to Video Assets group" first to also tag the saved frame into Gallery's Video Assets group.</li>
<li id="wfm-help-video-7">GIF tab (right panel): set Start/End (seconds), FPS, and an optional Max Width, then Convert to GIF — the server decodes the video and encodes an animated GIF into ComfyUI's output folder.</li>
<li id="wfm-help-video-8">Chaining: setting a block's First Image to "use previous block's last frame" continues smoothly from the previous clip — if that previous block has its own explicit Last Image, that image is used directly; otherwise the actual last frame of its generated video is extracted automatically.</li>
<li id="wfm-help-video-9">Project tab (sidebar, next to Asset): browse every saved plan file (thumbnail, block count, last updated), click one to load it into the Plan editor, or delete it with the × button; clicking the same tab again collapses the panel.</li>
<li id="wfm-help-video-9">Project tab (sidebar): browse every saved plan file (thumbnail, block count, last updated), click one to load it into the Plan editor, or delete it with the × button; clicking the same tab again collapses the panel.</li>
<li id="wfm-help-video-10">Highlight color: the Prompt / Duration / First Image / Last Image / Aspect Ratio / Megapixels / Multiple / Noise Seed / Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance labels turn the same highlight color as the GenerateUI Model tab (customizable in the Settings tab) when the loaded workflow actually supports that field — e.g. for a Wan2.2 workflow (no ResolutionSelector node), the Aspect Ratio / Megapixels / Multiple labels stay unhighlighted while Width / Height light up instead.</li>
<li id="wfm-help-video-11">Edit subtab: a lightweight clip timeline for trimming and concatenating video/image clips outside of generation. Add clips via the Video Source panel's "Add to Edit" button or the Asset subtab's "Send to Edit" button, then drag blocks to reorder (or use the ◀/▶ toolbar buttons), Duplicate/Delete the selected clip, and Clear to empty the timeline. The trim panel for the selected video clip shows a time ruler, a draggable playhead synced to the Source preview, and draggable in/out handles with time badges — image clips instead get a simple hold-duration field. ▶ Preview plays every ready clip back-to-back (trimmed to its in/out points) in the right-hand result preview; Export builds and runs the actual ComfyUI graph (trim → concatenate if more than one clip → save), tagging the result into the Video Temp group automatically. Exporting more than one clip currently drops audio, since ComfyUI's concatenation node requires uniform audio across all inputs.</li>
<li id="wfm-help-video-12">Asset subtab (center panel, next to Plan/Edit): browses every video/image tagged into Video Assets or Video Temp (via the group dropdown, or "All Video Assets" for both). Search filters by filename; the ▦/☰ buttons switch between a thumbnail grid and a table (filename/updated/tags). Selecting an item shows its tags/memo, loads it into the center preview, and offers "Send to Edit" (queues it as a clip in the Edit subtab) plus, for images only, "Set as First Image"/"Set as Last Image" (uploads it straight into the currently-selected Plan block, switching to the Plan subtab).</li>
</ul>
</div>
<button class="wfm-help-jump-btn wfm-btn wfm-btn-sm" data-jump-tab="video">Go to Video Tab</button>
@@ -2717,23 +2719,9 @@
<div class="wfm-video-layout">
<div class="wfm-video-form-panel">
<div class="wfm-video-subtab-nav">
<button type="button" class="wfm-video-subtab-btn" data-video-subtab="asset" id="wfm-video-subtab-btn-asset">Asset</button>
<button type="button" class="wfm-video-subtab-btn" data-video-subtab="project" id="wfm-video-subtab-btn-project">Project</button>
</div>
<!-- Asset: このPlanが生成した動画の素材管理(Galleryのグループ機能を再利用) -->
<div id="wfm-video-subtab-asset" class="wfm-video-subtab-panel" data-video-subtab-panel="asset" style="display:none;">
<div style="display:flex;gap:6px;align-items:center;">
<select id="wfm-video-asset-group" class="wfm-input" style="flex:1;"></select>
<button type="button" id="wfm-video-asset-refresh" class="wfm-btn wfm-btn-sm" title="Refresh">↻</button>
</div>
<span id="wfm-video-asset-status" class="wfm-i2i-status"></span>
<div class="wfm-video-asset-grid" id="wfm-video-asset-grid"></div>
<div class="wfm-video-asset-detail" id="wfm-video-asset-detail">
<span class="wfm-placeholder">Select a video</span>
</div>
</div>
<!-- Project: 保存済みVideo Plan一覧(クリックでPlanエディタへ読み込み) -->
<div id="wfm-video-subtab-project" class="wfm-video-subtab-panel" data-video-subtab-panel="project" style="display:none;">
<div style="display:flex;gap:6px;align-items:center;">
@@ -2753,27 +2741,66 @@
<div class="wfm-i2i-drop-zone" id="wfm-video-source-drop">
<label class="wfm-i2i-drop-label">
<span id="wfm-video-source-drop-label">Drop video or click to select</span>
<input type="file" accept="video/*" id="wfm-video-source-file" style="display:none;">
<input type="file" accept="video/*,image/*" id="wfm-video-source-file" style="display:none;">
</label>
</div>
<div style="display:flex;gap:6px;align-items:center;margin-top:6px;">
<span class="wfm-i2i-status" id="wfm-video-source-status" style="flex:1;"></span>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-source-add-to-edit">Add to Edit</button>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-source-clear">Clear</button>
</div>
</div>
<div class="wfm-video-preview-frame" id="wfm-video-source-preview-frame">
<span class="wfm-placeholder" id="wfm-video-source-preview-placeholder">Asset / Source Preview</span>
<video id="wfm-video-source-preview-video" class="wfm-video-preview-el" controls style="display:none;"></video>
<img id="wfm-video-source-preview-img" class="wfm-video-preview-el" style="display:none;">
</div>
<div class="wfm-video-preview-frame" id="wfm-video-preview-frame">
<span class="wfm-placeholder" id="wfm-video-preview-placeholder">Generated Video Preview</span>
<video id="wfm-video-preview-video" class="wfm-video-preview-el" controls style="display:none;"></video>
<img id="wfm-video-preview-img" class="wfm-video-preview-el" style="display:none;">
</div>
</div>
<div class="wfm-video-subtab-nav wfm-video-center-subtab-nav">
<button type="button" class="wfm-video-subtab-btn active" data-video-subtab="plan">Plan</button>
<button type="button" class="wfm-video-subtab-btn" data-video-subtab="edit">Edit</button>
<button type="button" class="wfm-video-subtab-btn" data-video-subtab="asset" id="wfm-video-subtab-btn-asset">Asset</button>
</div>
<!-- Asset: このPlanが生成した動画の素材管理(Galleryのグループ機能を再利用)。
左=一覧(サムネイル/テーブル切替可) / 右=選択ファイルの詳細(タグ・メモ等) -->
<div id="wfm-video-subtab-asset" class="wfm-video-subtab-panel wfm-video-asset-content" data-video-subtab-panel="asset" style="display:none;">
<div class="wfm-video-asset-layout">
<div class="wfm-video-asset-list-col">
<div class="wfm-video-asset-toolbar">
<select id="wfm-video-asset-group" class="wfm-input" style="flex:1;"></select>
<input type="text" id="wfm-video-asset-search" class="wfm-input" placeholder="Search filename..." style="flex:1;">
<button type="button" id="wfm-video-asset-view-grid" class="wfm-btn wfm-btn-sm wfm-video-asset-view-btn active" title="Thumbnail view">▦</button>
<button type="button" id="wfm-video-asset-view-table" class="wfm-btn wfm-btn-sm wfm-video-asset-view-btn" title="Table view">☰</button>
<button type="button" id="wfm-video-asset-refresh" class="wfm-btn wfm-btn-sm" title="Refresh">↻</button>
</div>
<span id="wfm-video-asset-status" class="wfm-i2i-status"></span>
<div class="wfm-video-asset-grid" id="wfm-video-asset-grid"></div>
<div class="wfm-video-asset-table-wrap" id="wfm-video-asset-table-wrap" style="display:none;">
<table class="wfm-video-asset-table">
<thead>
<tr>
<th>Filename</th>
<th>Updated</th>
<th>Tags</th>
</tr>
</thead>
<tbody id="wfm-video-asset-table-body"></tbody>
</table>
</div>
</div>
<div class="wfm-video-asset-detail-col">
<div class="wfm-video-asset-detail" id="wfm-video-asset-detail">
<span class="wfm-placeholder">Select a video</span>
</div>
</div>
</div>
</div>
<!-- Plan: バッチ動画生成のタイムライン編集・実行(中央下部、Planタブ選択時のみ表示) -->
@@ -2891,9 +2918,37 @@
</div>
</div>
<!-- Edit: 将来の動画編集機能用プレースホルダー -->
<!-- Edit: 簡易動画編集(クリップのタイムライン配置・トリム・結合書き出し)。
プレビューは上部のSource/Resultペインを再利用する(専用videoは持たない)。
タイムライン+下の共有ツールバーはPlan subtabの.wfm-video-timeline-*と同じ構造
(個別行ボタンではなく「選択中クリップに対して働く」共通ボタン方式)。 -->
<div id="wfm-video-subtab-edit" class="wfm-video-subtab-panel wfm-video-edit-panel" data-video-subtab-panel="edit" style="display:none;">
<span id="wfm-video-edit-placeholder-label" class="wfm-placeholder">Editing tools coming soon</span>
<div class="wfm-video-timeline-wrap">
<div class="wfm-video-edit-timeline-track" id="wfm-video-edit-timeline-track"></div>
<div class="wfm-video-timeline-toolbar">
<button type="button" id="wfm-video-edit-move-left-btn" class="wfm-btn wfm-btn-xs" title="Move left">◀</button>
<button type="button" id="wfm-video-edit-move-right-btn" class="wfm-btn wfm-btn-xs" title="Move right">▶</button>
<button type="button" id="wfm-video-edit-duplicate-btn" class="wfm-btn wfm-btn-xs">Duplicate</button>
<button type="button" id="wfm-video-edit-delete-btn" class="wfm-btn wfm-btn-xs">Delete</button>
<button type="button" id="wfm-video-edit-preview-btn" class="wfm-btn wfm-btn-xs">▶ Preview</button>
<span class="wfm-i2i-status wfm-video-edit-total-duration" id="wfm-video-edit-total-duration" style="margin-left:auto;"></span>
<button type="button" id="wfm-video-edit-clear-btn" class="wfm-btn wfm-btn-xs wfm-btn-danger">Clear</button>
</div>
</div>
<div class="wfm-video-edit-main-row">
<div class="wfm-video-edit-trim-panel" id="wfm-video-edit-trim-panel"></div>
<div class="wfm-video-edit-export-panel">
<button type="button" id="wfm-video-edit-export-btn" class="wfm-btn wfm-btn-primary" style="width:100%;">Export</button>
<div class="wfm-gen-progress-container" style="margin-top:8px;">
<div class="wfm-gen-progress-track">
<div id="wfm-video-edit-progress-bar" class="wfm-gen-progress-bar"></div>
</div>
<span id="wfm-video-edit-progress-text" class="wfm-gen-progress-text">Ready</span>
</div>
</div>
</div>
</div>
</div>
<!-- 右ペイン: プロパティ(Frame抽出 / GIF変換の2タブ)。中央ペインと同様に常時表示 -->
@@ -2909,6 +2964,9 @@
<div class="wfm-i2i-preview-wrap" id="wfm-video-frame-preview-wrap" style="display:none;">
<img class="wfm-i2i-preview-img" id="wfm-video-frame-preview-img">
</div>
<label class="wfm-video-checkbox-inline" style="margin-top:6px;">
<input type="checkbox" id="wfm-video-frame-add-to-assets"> Add to Video Assets group
</label>
<button type="button" id="wfm-video-frame-save-btn" class="wfm-btn wfm-btn-primary wfm-btn-sm" style="width:100%;margin-top:6px;" disabled>Save to Output</button>
<span class="wfm-i2i-status" id="wfm-video-frame-status"></span>
</div>