Compare commits

...
29 Commits
Author SHA1 Message Date
ausboss be2a2a1444 Merge pull request #355 from ausboss/release/2.26.2
Release 2.26.2
2026-11-14 10:58:10 -06:00
ausboss 76eb4fc7e7 Release 2.26.2 2026-11-14 10:57:05 -06:00
ausboss 057f2bd05a Keep refused file names, script addresses and held runs off the disk
Three findings from the Comfy Registry's review of 2.25.2, all still in
2.26.1:

- The change check of Load Image, Load Image + Pad, Image Crop + Rotate +
  Pad and both Video Crop + Rotate + Pad nodes handed a value its resolver
  had refused to os.stat and Path.resolve. stable_file_fingerprint now
  opens only a Path a resolver returned; a refused value is hashed as text.
- The script version tagging joined the request's address to the js folder
  and resolved it before checking it. It now looks the address up in a
  list of the pack's scripts made at startup.
- Save Image's keep route read the run's list from a JSON file in the temp
  folder, which takes uploads, and built the copy source from its
  extension, so a planted list could copy a server file into output. Runs
  now stay in memory (the last 256), held pictures are named from the
  token, their number and Save Image's own formats, must sit directly in
  the held folder, and a run holds at most 10,000 pictures.
2026-11-14 10:56:27 -06:00
ausboss 172252ab02 Merge pull request #353 from ausboss/release/2.26.1
Release 2.26.1
2026-11-14 07:09:37 -06:00
ausboss ebc81ea57e Release 2.26.1 2026-11-14 07:08:54 -06:00
ausboss bc235e96e5 Merge pull request #352 from ausboss/fix/no-home-path-expansion
Stop expanding ~ paths and opening a typed LaMa model path
2026-11-14 06:53:14 -06:00
ausboss 6572b49386 Stop expanding "~" paths and opening a typed LaMa model path
Image Folder compared a pasted "~/..." path after expanding it; only a
path written out in full is compared now. LaMa Inpaint resolved a typed
path when ComfyUI's folder list was missing; it only takes a name from
models/lama now. Neither could read outside ComfyUI's folders, but both
read like it to a code scan.
2026-11-14 06:28:13 -06:00
ausboss d593e01fc9 Merge pull request #351 from ausboss/release/2.26.0
Release 2.26.0
2026-11-14 06:21:08 -06:00
ausboss 009aa95d98 Merge remote-tracking branch 'origin/main' into release/2.26.0 2026-11-14 06:12:49 -06:00
ausboss b61b3efc94 Merge pull request #350 from ausboss/feat/clip-timing
Clip timing as Start, Duration and Ends at, on the clip node, Load Video and Load Audio
2026-11-14 05:58:07 -06:00
ausboss 6cfed25a8e Timing wording follows the new boxes
Backend tooltips and descriptions, the README and the help pages say
Start, Duration and Ends at where they still said IN, OUT, Length or
Max length. Load Video's help no longer says a typed 0 runs to the end:
Whole video does that.

Load Video's timing card refreshes when a wire is connected or removed.
The old Length switch function is gone from the timing card.
2026-11-14 05:42:17 -06:00
ausboss 27e175aa08 Release 2.26.0 2026-11-14 05:31:40 -06:00
ausboss 6224bae13c Timing boxes: App mode fields, Duration 0, one link reader
Every nth, the frame limit and the audio Duration are hidden by the
widget card again, so App mode can still show them as fields.

Load Audio: an empty or 0 Duration runs to the end of the file, and a
box whose linked value is only known at run time stays empty. The rules
for what a pick stores are in audio_window.mjs with tests.

The shared link reader asks the frontend for an input's link before
reading the link table, and Layout Boxes and H3's clip lookup use it
alone.
2026-11-14 05:28:02 -06:00
ausboss bd49afae19 Merge main: keep both sets of Unreleased entries 2026-11-14 05:28:02 -06:00
ausboss 13e4d73dbd Merge pull request #347 from ausboss/feat/app-mode-cards
Make App mode work with AusBoss nodes: card fields, found models, clip upload
2026-11-14 05:17:16 -06:00
ausboss 37584519e8 Merge pull request #349 from ausboss/fix/lora-in-missing-models
List missing LoRAs in ComfyUI's missing-models list
2026-11-14 05:16:45 -06:00
ausboss 1ed921b6fb Load Video and Load Audio on Start, Duration and Ends at
Load Video uses the clip node's timing card: Start, Duration and Ends at
replace the IN/OUT fields and the Limit row. Its face reads the frame
count from the file, so a 247-frame clip no longer shows 248.

Load Audio gets the same three boxes in place of IN/OUT and Max length;
the Duration is the max_seconds widget, so saved values are unchanged.

One linked-number reader (linkOrigin) follows Reroutes, subgraphs and
older Primitive nodes for the clip node, both loaders and Layout Boxes.
2026-11-14 04:07:29 -06:00
ausboss 15e5803a06 List LoRA Loader's missing files in ComfyUI's missing-models list
ComfyUI builds its missing-models list (the Issues panel and Download all)
from list widgets only. LoRA Loader keeps its files in the rows' text, so a
LoRA a workflow needs was never listed, and Download all then Run stopped on
'missing LoRA file'. Each row that needs a file now gets a hidden list widget
holding its name: kept out of the saved workflow and the prompt, with no
socket, made again from the rows whenever they change. A replacement picked
in the Issues panel goes back to its row.
2026-11-14 03:57:14 -06:00
ausboss a0327f6ddd Clip timing as Start, Duration and Ends at
The clip node's Length on/off switch is replaced by three boxes. Dragging
the start moves the clip, dragging the end or typing a Duration changes
its length, and a seconds | frames switch picks the units. Extra details
moved into hover text, and a note shows only when something needs fixing.

With a linked frame rate, the latest start was worked out on the source
frame grid, so a typed start of 60 settled on 7. It now uses the output
rate. A rate typed inside a subgraph is followed, so Person Swap shows its
clip length before a run. A cap the video cannot fill says so, and Ends
at no longer runs past the video's last frame.

H3 Prompt Writer shows how many of the clip's frames H3 makes. The Crop +
Rotate + Pad panel rows fill the node's width instead of stopping at
460 px, and the size line drops its empty warning row.

Frontend only: inputs, outputs and saved values are unchanged.
2026-11-14 03:27:00 -06:00
ausboss e65612bb28 Merge main: keep the tile snap entry and the App mode entries in Unreleased 2026-11-14 02:55:58 -06:00
ausboss 11d79b252d Merge pull request #348 from ausboss/fix/tile-snap-visible-edge
Snap tiles by their visible card
2026-11-14 02:52:00 -06:00
ausboss 7e5cadaa06 Snap tiles by their visible card
A frameless tile (link, title or note tile) draws a card inside a wider
transparent node. Snap into line and Line up measured the node, so tiles
lined up with a gap around them. A tile also moves itself and keeps its
pointer moves to itself, so Snap into line never saw a tile being dragged.

The tile now names its card as its outline, and its drag reports each
move to Snap into line once the tile is placed. The move itself still
stops at the tile: letting it through made Nodes 2.0 pan the canvas.
2026-11-14 01:59:46 -06:00
ausboss 94d302e112 Contributor guide: App mode needs upload flags on file lists 2026-11-13 23:15:34 -06:00
ausboss fb26f3ae06 Let the video crop nodes take uploads in App mode
Their video list did not carry video_upload, so in an App mode form the
clip field was a bare list with no way to upload a clip, while the picture
field next to it had a picker and an Upload button. Both video crop nodes
now declare the flag, as Load Video does. ComfyUI adds its upload button to
the node, which the crop panel already hides, so the node face is unchanged.
2026-11-13 21:58:15 -06:00
ausboss 11638b0557 Pick a model the user already has in a subfolder without a click
A workflow saved with a bare model name opens with that loader red when
the user keeps the file in a subfolder. The Guide already found the copy
and offered Use it; App mode shows no Guide, so the form opened with
"2 issues found" and Run blocked. Now the Guide points the loaders at the
copy as the workflow opens, when there is exactly one, and says so in a
toast. Two copies in different subfolders still get the Use it button.
Setting AusBoss.Models.PickFoundCopy (on by default) turns it off.
2026-11-13 19:41:17 -06:00
ausboss ad81fbcca1 Show card widgets as real controls in App mode
App mode reads the same hidden flag the pack's cards set on the widgets
they replace, so every field from a carded node (Load Image, the video
loaders, H3 Prompt Writer) drew an empty row in the form. While the open
workflow is in App mode, the widgets its form lists are now shown; back in
the graph they are hidden again, so node faces do not change.

showWidget also stops leaving computeSize, computeLayoutSize and draw
behind as own undefined properties: the frontend took those for a
custom-drawn widget and picked the legacy renderer.
2026-11-13 19:04:50 -06:00
ausboss 9cc91ffba8 Merge pull request #346 from ausboss/fix/playhead-readout-hint
Release 2.25.3
2026-11-13 15:15:54 -06:00
ausboss 0450466422 Release 2.25.3 2026-11-13 15:15:00 -06:00
ausboss d5442cd659 Explain the video clip's frame readout in plain words
The readout beside Play (fr 52 · 0:02.17) now says on hover which frame
the picture shows and how many seconds into the video it is, and the
help page explains it.
2026-11-13 15:12:53 -06:00
62 changed files with 2225 additions and 899 deletions
+111
View File
@@ -2,6 +2,117 @@
All notable changes to ComfyUI-AusBoss are documented here.
## 2.26.2 - 2026-11-14
- **Loaders never look up a file name they refused.** Before each run,
Load Image 🆎, Load Image + Pad 🆎, Image Crop + Rotate + Pad 🆎 and both
Video Crop + Rotate + Pad nodes check whether their file changed. When the
name was one they do not accept, such as a whole path or a network share,
that check still looked it up on disk. On Windows, looking up a share
contacts its server and hands it the computer's login. Now a refused name
is only compared as text.
- **The pack's scripts are found without looking up the address.** The pack
tags its scripts with a version as the browser asks for them. It found
each one by joining the address the browser sent to its own folder and
looking the result up on disk, and only then checked that the file was
its own. Now it looks the address up in a list of its scripts made when
ComfyUI starts, so no address reaches the disk.
- **Save Image's Save button copies only pictures it holds.** With Auto
save off, the list of a run's held pictures was a file in ComfyUI's temp
folder. That folder takes uploads, so a planted list could copy another
file on the server into the output folder. The list now stays in
ComfyUI's memory, and a held picture is found only by its run, its number
and one of Save Image's formats. The Save button works for the last 256
runs, up to 10,000 pictures each; held pictures still go when ComfyUI
restarts, as before.
## 2.26.1 - 2026-11-14
- **A path that starts with `~` is no longer expanded.** Image Folder used
to turn a pasted `~/...` path into a full one before checking that it sits
inside ComfyUI's folders; now only a path written out in full is checked.
LaMa Inpaint only opens a model from ComfyUI's `models/lama` list. Nothing
outside those folders could be read before either; this removes the code
that looked as if it could.
## 2.26.0 - 2026-11-14
- **Missing LoRAs show in ComfyUI's missing-models list.** When a workflow
needs a LoRA you don't have, ComfyUI's Issues panel now lists it with the
other missing models, so **Download all** fetches it too. Before, the
list skipped every LoRA in a LoRA Loader 🆎, and Run then stopped on
"missing LoRA file". A LoRA that moved to another folder, or a row that is
switched off, is not listed.
- **Link tiles and title tiles snap by the edge you see.** A tile draws a
card inside a wider see-through frame, and Snap into line used that frame,
so tiles lined up with a gap around them, and a tile you dragged never
snapped at all. Now a dragged tile lines up, and other nodes line up with
it, by the card's own edges.
- **Cards work in App mode.** App mode is ComfyUI's simple form view of a
workflow: a few labelled fields and a Run button. A field from a node
with a card (a picture or video loader, H3 Prompt Writer) used to show
as an empty row there. Now it shows a real control: a file list with an
upload button, a video list, a text box. Back in the graph, the node
looks the same as before.
- **The video crop nodes take uploads in App mode.** Video Crop + Rotate +
Pad and its Clip version now tell ComfyUI that their video list takes
uploads, as the picture nodes do. In App mode the clip field gets the same
picker as a picture field: your videos as thumbnails, an Upload button and
a folder button. On the node itself nothing changes.
- **Models you already have are picked for you.** When a workflow asks for
a model file you keep in a subfolder (`minimax-h3/model.safetensors`),
ComfyUI used to mark its loader red until you clicked **Use it** on the
workflow's Guide. Now the Guide switches the loader to your copy as the
workflow opens and says so in a short message. That matters most in App
mode, which shows no Guide to click. With two copies in different
subfolders it still asks. Turn it off in Settings, 🆎 AusBoss, Models.
- **The video clip's timing is three boxes: Start, Duration, Ends at.** On
Video Crop + Rotate + Pad (Clip), the Length on/off switch is gone. Drag
the start to move the clip, drag the end or type a Duration to change how
long it is, and switch between seconds and frames. Details sit in hover
text; a short note shows only when something needs fixing, with a button
to fix it. Saved workflows open with the same values and run the same.
- **A linked frame rate no longer stops the clip's start too early.** With
a rate wired in, a typed start of frame 60 used to settle on frame 7; it
now lands where you put it, and the start handle stops only where the
Duration no longer fits. A rate set inside a subgraph now counts as
known, so the clip shows its length before you run.
- **Linked clip lengths say where they come from.** A box set by another
node shows a **linked** button that jumps to that node. A cap that the
video cannot fill says how many frames you get, and a count only known
when the graph runs shows the room left after the start.
- **H3 Prompt Writer says how much of the clip H3 uses.** When the video
comes from the clip node, it shows how many of the clip's frames H3
makes and where in the video that stops, and which Durations use all of
it.
- **Crop + Rotate + Pad panels fill the node's width.** The rows under the
picture used to stop at 460 px and sit in the middle of a wide node.
- **Load Video uses the same timing boxes as the clip node.** Start,
Duration and Ends at replace the IN and OUT fields and the separate
Limit row, with the same seconds | frames switch. Saved workflows open
with the same values and run the same.
- **Load Video counts the frames the file really has.** The face used to
work the count out from the length and could say one frame too many (248
for a 247-frame clip); it now reads it from the file.
- **Load Audio has Start, Duration and Ends at boxes.** They replace the IN
and OUT times and the separate Max length row, so the red "cut" stripe is
gone: the Duration is the length you get.
- **A number wired through a Reroute or a subgraph now shows on the face.**
The clip node, Load Video, Load Audio and Layout Boxes read a linked
number the same way, so it no longer drops out behind a Reroute, a
subgraph or an older Primitive node.
## 2.25.3 - 2026-11-13
- **The video clip's frame readout explains itself.** On Video Crop + Rotate
+ Pad (Clip), the small `fr 52 · 0:02.17` beside Play now says in plain
words, when you point at it, which frame the picture shows and how many
seconds into the video it is. The help page explains it too.
## 2.25.2 - 2026-11-13
- **The video clip's IN handle always drags.** On Video Crop + Rotate + Pad
+8 -2
View File
@@ -210,8 +210,7 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
never a classic canvas number widget on a finished node face. Units
(`px`, `MP`, `×`) ride inside the box in a fixed-width slot that every
single-field row reserves, so the numbers down a card share one centre
line. Known, deliberate exceptions: the Seed card's seed (typed) and Load
Video's trim timecodes (typed).
line. Known, deliberate exception: the Seed card's seed (typed).
- **Node faces are widget cards.** A node whose face would be classic
LiteGraph widgets (full-width rows with an arrow at each end) gets an
entry in `js/widget_cards/index.js` instead: `mountWidgetCard` from
@@ -234,6 +233,13 @@ example_workflows/ # example workflows (regular workflow JSON, not API JSON)
widget per row. A value that is meant to be wired rather than typed is a
backend `forceInput: True` socket (Math Expression `a`/`b`/`c`), and a
multi-type string such as `"FLOAT,INT"` accepts either kind of link.
- **App mode** is ComfyUI's form view of a workflow (fields and a Run
button). A file list from the input folder declares its upload flag
(`image_upload`, `video_upload`, `audio_upload`): the form builds the
field's Upload button from it, and without it the field is a bare list.
`tests/test_video_upload_flag.py` holds the video lists to it. A card's
hidden widgets reach the form through `js/app_mode/`, so a card needs
nothing of its own for App mode.
- Preview-carrying nodes (Select Frame, Mask Refine, Mask by Name, LaMa
Inpaint, Save Image) share
`js/input_preview/`: a thin bar (node tools left, a small `preview`
+4 -4
View File
@@ -180,13 +180,13 @@ The example keeps the clip's audio when there is any. The outpaint LoRA needs a
### Load Video
Upload a video, or pick one from the Source list, which plays the clip under the pointer. Trim it with IN and OUT handles or typed timecodes. The player plays the part you kept and can loop it. Width and height resize while decoding, and setting only one keeps the shape. `every_nth` skips frames and lowers the reported fps so the timing stays right, and `max_frames` caps how many frames load.
Upload a video, or pick one from the Source list, which plays the clip under the pointer. Set the part you want with Start, Duration and Ends at, in seconds or frames, or drag the handles under the player. The player plays the part you kept and can loop it. Width and height resize while decoding, and setting only one keeps the shape. `every_nth` skips frames and lowers the reported fps so the timing stays right, and the Duration caps how many frames load.
It returns the frames, audio, frame count, fps, width, height, duration and a core `VIDEO`. Only the part you kept is decoded, and it checks memory before a large load. When you save the frames, wire its fps into the save node.
### Load Audio
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the IN and OUT handles to keep only the part you want, or type the times. Press play to hear just that part. Set **Max length** to the longest sound the next step can take, such as a video's length: anything past it turns red and is cut off, so you see what comes out before you run. Click the red length next to OUT to move OUT to the cut.
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the two handles to keep only the part you want, or type a Start, a Duration or an Ends at. Press play to hear just that part. Set the Duration to the length the next step needs, such as a video's length.
It returns the `audio` you kept and its length in `seconds`. Only that part is decoded. [Help page](js/docs/AUSBOSS_NODES_LoadAudio.md).
@@ -196,7 +196,7 @@ Picks one frame from a video, then gives you the same rotate, crop and pad contr
### Video Crop + Rotate + Pad → Clip
Applies one rotate, crop and pad to every frame of a trimmed clip. It has the source picker, a timeline with a playhead and frame-accurate IN and OUT handles, frame skipping, a frame limit, the transform handles and output resizing. While you drag a trim handle, the node shows the exact first or last frame the run keeps. The bright part of the selection is what gets output.
Applies one rotate, crop and pad to every frame of a trimmed clip. It has the source picker, a timeline with a playhead and frame-accurate start and end handles, Start, Duration and Ends at boxes, frame skipping, the transform handles and output resizing. While you drag a trim handle, the node shows the exact first or last frame the run keeps. The bright part of the selection is what gets output.
Fill, feather and the resize budget are in **Crop, pad & resize** below the timeline, and a new clip keeps them. That matters for video outpainting, because the black, hard-edged canvas the model needs survives a source swap. A fresh Clip node starts with that canvas, and the editor's **Reset transform** goes back to it. **Frames for** trims the end to the frame count the next video model takes: LTX (8n+1) or Wan (4n+1). Tap a ratio to pad the clip to it; a new clip is padded to the lit ratio too. The padlock keeps the shape while you drag a handle.
@@ -486,7 +486,7 @@ People who download your workflow get the nodes through ComfyUI-Manager's missin
- Hold Shift while you turn the green rotation handle to snap to 15° steps.
- In the full-screen editor, the mouse wheel zooms, and the middle mouse button or Alt-drag pans. On the node itself, the wheel and middle mouse button still move the graph.
- **Alt+E** opens the selected node's transform editor. Change the key in Settings → Keybindings.
- The video editors have frame stepping, playback and exact timeline seeking, on the node face as well as in the editor. The Clip node's IN and OUT handles sit on the source's own frames, so the frame shown for IN is the first one decoded and the frame shown for OUT is the last.
- The video editors have frame stepping, playback and exact timeline seeking, on the node face as well as in the editor. The Clip node's start and end handles sit on the source's own frames, so the frame shown at the start is the first one decoded and the frame shown at the end is the last.
- Your own aspect presets go in `ausboss_presets.json` beside the pack. Copy [`ausboss_presets_example.json`](ausboss_presets_example.json) to start. Your file survives updates.
LoRA Loader and Latent Size have their own gear menus for per-node preferences.
+3 -3
View File
@@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.25.2">
<title>release: v2.25.2</title>
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.2">
<title>release: v2.26.2</title>
<path fill="#555" d="M0 0h48v20H0z"/>
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="24" y="14">release</text>
<text x="76.5" y="14">v2.25.2</text>
<text x="76.5" y="14">v2.26.2</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+45
View File
@@ -0,0 +1,45 @@
// App mode for nodes with cards: the simple form view shows a real control
// for each field instead of an empty row. The logic is in
// js/shared/app_mode.mjs; this file watches which mode the open workflow is
// in and hands the fields over.
import { app } from "../../../scripts/app.js";
import { createAppModeSync, workflowMode } from "../shared/app_mode.mjs";
const sync = createAppModeSync({
find(nodeId, name) {
const graph = app.rootGraph ?? app.graph;
const node = graph?.getNodeById?.(/^\d+$/.test(nodeId) ? Number(nodeId) : nodeId);
const widget = node?.widgets?.find((entry) => entry.name === name);
return widget ? { node, widget } : null;
},
changed(node) {
node.setDirtyCanvas?.(true, true);
},
});
let queued = false;
// After the current task: a card hides its widgets in a microtask once the
// node has loaded, and the form's fields are shown after that.
function schedule() {
if (queued) return;
queued = true;
setTimeout(() => {
queued = false;
try {
const workflow = app.extensionManager?.workflow?.activeWorkflow;
sync(workflowMode(workflow), (app.rootGraph ?? app.graph)?.extra?.linearData);
} catch (error) {
console.warn("[AusBoss] App mode fields:", error);
}
}, 0);
}
app.registerExtension({
name: "ausboss.app.mode",
setup() {
app.extensionManager?.workflow?.$subscribe?.(schedule);
},
afterConfigureGraph() {
schedule();
},
});
+16 -22
View File
@@ -5,37 +5,31 @@ clip, a song or any sound a video model or a save node takes, when you want
one part of the file and not the whole thing.
The node shows the whole file as a wave, so you can see where the loud parts
are. The part that comes out is bright. Drag the white **IN** and **OUT**
handles to set where it starts and stops, drag the bright part to slide it,
or click somewhere else on the wave to move it there. You can also type a time
under the wave, in seconds (`12.5`) or minutes and seconds (`1:02.5`).
are. The part that comes out is bright. Under the wave are three boxes:
**Start**, **Duration** and **Ends at**, in seconds. Drag the left handle to
move the start, drag the right handle or type a Duration to change how long
the sound is, or drag the bright part to slide it. Click somewhere else on
the wave to move it there. Typing **Ends at** sets the Duration for you.
Press **▶** to hear only the part that comes out. **LOOP** plays it again and
again.
## Max length
Set the Duration to the length the next step needs, such as the length of
the video you are making. An empty Duration runs to the end of the file.
Set **Max length** to the longest sound the next step can take, such as the
length of the video you are making. The start stays where it is, and anything
past the limit turns red with a dashed line where it is cut. Next to OUT,
the node shows how long the sound that comes out is, such as `15.0 s`. It
turns red when part of your pick is cut; hold the mouse over it to see how
much, and click it to move OUT to the cut. Play stops at the cut, so what you
hear is what comes out. `0` means no limit.
Max length can be wired. When the wire comes from a number node such as
Float 🆎, the wave shows the cut for that number; otherwise the length's tooltip says
`max wired` and the run still cuts the sound to the wired length.
A box set by another node, such as Float 🆎, shows a **linked** button that
jumps to that node, and the wave shows the part that number picks.
## Controls
- **Source** (`audio`): a sound file in ComfyUI's input folder. **Upload**
adds one. Videos are listed as well, for their sound.
- **Max length** (`max_seconds`): the longest the sound may be, in seconds.
`0` means no limit.
- **IN** (`start_seconds`): where the sound starts.
- **OUT** (`end_seconds`): where the sound stops. `0` means the end of the
file.
- **Start** (`start_seconds`): where the sound starts.
- **Duration** (`max_seconds`): how long the sound is, in seconds. Empty, or
`0`, runs to the end of the file.
- **Ends at**: where the sound stops. Typing it sets the Duration.
A workflow saved with an end time (`end_seconds`) keeps it and runs the
same.
## Outputs
@@ -49,4 +43,4 @@ Float 🆎, the wave shows the cut for that number; otherwise the length's toolt
- The sound keeps its own sample rate and channels.
- A start past the end of the file stops the run with a message that says so.
- The wave is drawn in the browser from the file itself; nothing extra is
stored with the workflow besides the four values above.
stored with the workflow besides the node's own values.
+39 -43
View File
@@ -1,37 +1,33 @@
# Load Video
Loads a video from ComfyUI's input folder as an `IMAGE` frame batch plus its
audio. One responsive player shows the source and previews the selected trim.
Drag the high-contrast **IN** and **OUT** handles below it, drag the selected
range to move the whole window, or type a time into the two fields, in seconds
(`95.5`) or as a timecode (`1:35.5`). Click the strip outside the selection to
move the window to that spot.
The playhead follows each edit, so the frame at either boundary is visible
while trimming. In **Source**, the list plays the clip under the pointer, muted, and filters as you type.
audio. The player shows the video; the timing card under it picks the part
that comes out.
Playback is constrained to the selected window. **LOOP** repeats it; turn loop
off and playback pauses at OUT. The reload button refreshes the source without
creating a second preview. The player takes the height you give the node:
drag the node taller for a bigger picture. A tall video is shown whole, never
cropped.
The timing card has three boxes: **Start**, **Duration** and **Ends at**.
Drag the left handle on the bar to move the start, drag the right handle or
type a Duration to change how long the clip is, or drag the middle of the
clip to slide it. **s | fr** switches every box between seconds and frames;
it only changes what you see, never a saved value. **Use as start** starts
the clip at the frame in the picture, and **Whole video** puts the clip back
to the full file. In **Source**, the list plays the clip under the pointer,
muted, and filters as you type.
**FRAME** switches the loader into a frame picker: the trim strip becomes a
single scrub rail, and only the frame at the marker loads — a one-image batch,
ready for image workflows without a separate frame-select node. Click or drag
anywhere on the rail to choose the frame, or type an exact time into the AT
field. Playback runs the whole source freely in this mode so you can hunt for
the right moment. Picking a frame moves IN to that time. When you toggle back,
OUT stays where it was, unless the frame is at or after OUT: then OUT moves to
the end of the video.
The player takes the height you give the node: drag the node taller for a
bigger picture. A tall video is shown whole, never cropped. **LOOP** plays
the clip again and again; with it off, playback pauses at the clip's end.
The reload button refreshes the source.
The label between IN and OUT reports what one Run will actually load — e.g.
`0:04.0 of 0:10.0 · 48 frames @ 12 fps`, or `1 frame at 0:05.2` while FRAME
is on. The preview cannot re-render `every_nth` frame drops or a `max_frames`
cap, so it counts them instead: the frame total and playback rate come from
the source's real frame rate (probed from the file, since the browser's
player never exposes it) with `every_nth` and `max_frames` applied. When a
deciding value arrives over a link, or the rate cannot be probed, the count
drops out rather than guessing.
**FRAME** turns the loader into a frame picker: only the frame at the marker
loads, as a one-image batch, ready for image workflows without a separate
frame-select node. Drag the bar to choose the frame, or type it into the
**FRAME** box. Playback runs the whole video in this mode so you can hunt for
the right moment. Picking a frame moves the clip's start there.
The boxes count real frames: the frame rate and frame count come from the
file itself, so a 4.1 s clip at 60 fps reads 247 frames, the same number
the run loads. When a box is set by another node it shows a **linked**
button that jumps to that node.
## Drop a video onto the node
@@ -48,21 +44,21 @@ embedded workflow replaces the whole graph.
- **Source** (`video`): A file in the input folder; **Upload** adds new ones.
A video ComfyUI made, named like `clip.mp4 [output]`, loads too.
- **IN** (`start_seconds`): Skip everything before this time.
- **OUT** (`end_seconds`): Stop at this time; `0` means the source end until a
handle is moved.
- **Every nth** (`every_nth`): Keep one frame in this many — `2` halves the frame count.
The `fps` output divides to match, so the clip still plays at real speed
downstream.
- **Limit** (`max_frames`): Stop after this many kept frames; `0` loads the
whole trim window. Caps memory on long clips — the decode ends early
instead of loading and discarding.
- **LOOP**: Repeat the selected window during preview. It starts on and is
saved with the workflow.
- **FRAME** (`single_frame`): Load only the frame at the IN time (the field
reads **AT** while FRAME is on) as a one-image batch; `end_seconds`,
`every_nth`, and `max_frames` are ignored while it is on.
- **↻**: Reload the selected source preview.
- **Start** (`start_seconds`): Skip everything before this time.
- **Duration** (`max_frames`): How many frames the clip keeps. **Whole
video** removes the limit, so the clip runs to the end (the widget holds
`0`). The decode stops early, so a short clip from a long video stays
quick.
- **Ends at**: Where the clip stops. Typing it sets the Duration. A
workflow saved with an end time (`end_seconds`) keeps it and runs the same.
- **Every nth** (`every_nth`): Keep one frame in this many; `2` halves the
frame count. The `fps` output divides to match, so the clip still plays at
real speed downstream.
- **LOOP**: Repeat the clip during preview. It starts on and is saved with
the workflow.
- **FRAME** (`single_frame`): Load only the frame at the marker as a
one-image batch; the Duration and Every nth are ignored while it is on.
- **↻**: Reload the source preview.
- **Width** / **Height** (`custom_width` / `custom_height`): `0` keeps the
source size. Set one side only and the other follows the aspect ratio,
rounded to an even number.
+8
View File
@@ -266,6 +266,14 @@ red with advice to re-pick. Thumbnails, the info card, and range lookups
all use the resolved name, so a moved file keeps its previews and Civitai
data.
A missing LoRA is also listed in ComfyUI's own missing-models list (the
Issues panel, and the "Download all" button) next to the other models the
workflow needs, with a Download button when the workflow saved where the
file comes from. Rows that are switched off, at zero strength, or whose
file moved folders are left off that list, because the run does not need
them or finds them anyway. Rows that come into the node over a link are
listed by the node that sets them, not here.
The run side matches: a stale saved path resolves by name at load time
(exact → unique case-insensitive path → unique basename, with a one-line
console note when it remaps). A LoRA that is genuinely missing **stops the
+1 -1
View File
@@ -65,7 +65,7 @@ file's name. A caption on the `caption_text` input writes the paired `.txt`.
are saved under the name and folder set above, in the format picked,
with the workflow inside if **Embed workflow** is on. They wait in
ComfyUI's temp folder, which is emptied when ComfyUI restarts, so save
what you want before that.
what you want before that. The Save button works for the last 256 runs.
- **Preview steps** (`step_preview`, off by default): the switch left of
**preview** shows the picture while it is being made, one step at a time,
where the saved image goes, with a **STOP** button on the bar. Stop a run
+45 -37
View File
@@ -14,28 +14,43 @@ model that paints black regions.
- **Inputs**: Pick an existing input video (the list plays the clip under the pointer, muted, and filters as you type), click **Load**, or drop a video file
onto the node. The old source widgets remain compatible with saved workflows, but
are now driven by this compact card. Choosing another video keeps the canvas
settings - Fill, Feather, **Align**, Resize, Every nth, Frames for, Length - and
settings - Fill, Feather, **Align**, Resize, Every nth, Frames for, Duration - and
fits the new clip to the lit ratio button, the way **Fit** is set. Rotation, crop,
padding, IN/OUT and the playhead start over.
padding, the clip's timing and the playhead start over.
- **Outputs** (`source_mode` / `local_path`): Pick a video from ComfyUI's output folder,
such as one you just rendered. The list shows the newest first and previews the video
under the pointer. The video is read in place, without an upload copy. In an API prompt
it is named the way ComfyUI names a file there: `clip.mp4 [output]`. A whole path such
as `/home/me/ComfyUI/output/clip.mp4` is not read, for queued runs and the editor's live
preview alike.
- **Play / Pause** beside the scrubber previews the selected frames and stops at OUT. Press Play at OUT to start from IN again.
- **Timeline** (right under the preview and size line): The rail on the node and in the editor is one timeline. Press or
drag anywhere on it to scrub the **playhead**, with Length on or off; the stage shows
that frame. Drag the **IN** or **OUT** handle to trim: the playhead rides on the handle, so what you see
is the first (IN) or last (OUT) frame the run keeps, and it stays there when you let
go. IN and OUT are frames, snapped to the source's frame grid; the boxes under the
rail take a frame number, and `start_seconds` / `end_seconds` are derived from them
(OUT is exclusive, 0 means the end of the source). Arrow keys on a handle move one
second, Shift one frame. **OUT always sits on the last frame the run outputs**, so
the handle and the bright bar end together; with Every nth or Frames for it steps to the
frames the run keeps, and a dim tail marks frames the window holds but the run
drops. In the editor, **Set IN** / **Set OUT** (or the **I** / **O** keys) put a
trim point at the playhead, and **Full clip** resets the window. The editor also
- **Play / Pause** beside the timeline plays the clip from its start and stops at its end. Pause and Play again to carry on from where you stopped.
- **Timeline** (right under the picture): Press or drag anywhere on it to look at
another frame; the picture shows it. Point at the bar to see where you are, the
clip in words and the source's frame rate. Drag the **start** handle to move the
clip (its Duration stays), and the **end** handle to change the Duration. The
start stops where the whole Duration still fits, and a short note says so.
**Use as start** starts the clip at the frame on the picture.
- **Start / Duration / Ends at**: the clip in three boxes. Start and Ends at are
places in the source video; Duration is how long the clip is. Type any of them,
or drag over a box to scrub it. The small **s | fr** switch shows them in seconds
or frames: Start and Ends at count source frames, Duration counts the frames the
clip sends on, at the output rate. Point at a box for the other unit and what it
covers. Typing a Start that leaves too little video is allowed: an amber note says
how many frames still fit and offers to shorten the clip or move the start.
- **Linked timing**: when another node feeds `start_frame`, `end_frame`,
`frame_load_cap` or `fixed_frames`, that box is locked and its label shows a small
**linked** button that jumps to the node. `fixed_frames` is an exact count;
`frame_load_cap` is only a limit, so when the video ends first the note says how
many frames you get. A count only worked out when the graph runs (a Math
Expression, say) shows as **at run time**, and the timeline shows striped room
after the start instead of a clip. A rate typed inside a subgraph counts as known.
- **Technical details**: `start_seconds` / `end_seconds` are derived from the frames
(the end is exclusive, 0 means the end of the source), and the Duration is stored
as `max_frames`. Arrow keys on a handle move one second, Shift one frame. With
Every nth or Frames for the end steps to the frames the run keeps, and a dim tail
marks frames the window holds but the run drops.
In the editor, **Set IN** / **Set OUT** (or the **I** / **O** keys) put a
trim point at the playhead, and **Whole video** resets the clip. The editor also
has buttons for the first and last frame, steps of 1, 25, 50 and 100 frames, and
**Play**. Arrow keys step one frame (10 with Shift), Home and End jump to the
ends, and Space plays or pauses. **Save & close** keeps your edits; **Cancel** or
@@ -55,23 +70,16 @@ model that paints black regions.
fill colour with a faint hatch, so black bands show on the black stage. A fresh clip node starts
with black and feather 0 and the editor's **Reset transform** returns to them;
the image nodes keep their grey fill and feathered mask.
- **Length** (`max_frames`): the one other way to set how long the clip is. **Off**
(the default): OUT ends the clip. **On**: a number of output frames from IN; OUT
sits that many frames after IN and follows it when you drag IN, and dragging OUT or
typing the number changes the Length. To move the whole clip, drag IN or the small
grip in the middle of the kept part (the grip also slides a trimmed window with
Length off). When the Length is as long as the clip or longer, the row says
"= the whole clip": the clip's own end is OUT, and dragging IN starts the clip
later without changing the Length. The Length stays when you
swap the video, so a workflow built for 97 frames keeps taking 97. Turning it on or
off never moves anything: the count becomes the OUT, or the OUT the count. If the
source ends first, the footer says how many frames are left. **To start** moves IN
to the start of the source.
- **Whole video / To start** (bottom right of the timing card): **Whole video**
uses the whole source, with no Duration limit. When the length is linked, the
button reads **To start** and moves the start to the beginning instead. The
Duration stays when you swap the video, so a workflow built for 97 frames keeps
taking 97.
- **Every nth** (`every_nth`): Thin the batch. The `fps` output divides to match
every_nth, so the clip keeps real-time downstream; a Length counts the frames kept.
every_nth, so the clip keeps real-time downstream; a Duration counts the frames kept.
- **Frames for** (`frame_snap`): Keep a frame count a video model takes:
**LTX (8n+1)** (49, 97, 121) or **Wan (4n+1)**. **any** keeps every frame in the window.
OUT drags and the Length step through those counts.
Dragging the end and typing a Duration step through those counts.
With it on, `frame_count`, `duration`, the audio window and the stitcher all match the
clip the sampler hands back, so wiring `frame_count` into the empty latent's length
never leaves the stitch with more source frames than generated ones.
@@ -103,7 +111,7 @@ with the padlock on it also takes away the bands the lock added.
**Reset** on the node clears rotation, crop and padding and turns the padlock off;
fill, feather, **Align** and the timeline stay.
**Reset transform** in the editor resets rotation, crop, padding, fill, feather and
**Align**; it keeps the source, current frame, trim, Length, resize and stitch
**Align**; it keeps the source, current frame, trim, Duration, resize and stitch
settings. **Align** makes the width and height divide evenly by the number
you pick: padding grows by a few pixels, and a side with no padding is trimmed by
a few instead. Some models need sizes divisible by 8, 16 or 32; 1 turns it off.
@@ -163,8 +171,8 @@ Five optional sockets sit on the left, above the editor:
| `force_rate` | Sample at this fps before Every nth. 0 keeps the source rate. Drops or repeats frames to keep playback speed. Accepts FLOAT or INT. |
| `start_frame` | Zero-based source start frame. Overrides timeline IN. |
| `end_frame` | Exclusive source end frame. 0 means the end of the source. Overrides timeline OUT. |
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: OUT, Length and Frames for step aside. |
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Length. When the count is known, dragging IN stops at the last start that fits the kept frames. |
| `fixed_frames` | Exact output frames from IN; the source must be long enough. Connected, it sets the length: Duration, Ends at and Frames for step aside. |
| `frame_load_cap` | Maximum frames after rate conversion and Every nth, before Frames for. 0 means unlimited. Connected, it sets the length in place of Duration. When the count is known, dragging the start stops at the last start that fits the kept frames. |
| `last_seconds` | Load only this many seconds from the end of the clip, or of the part before OUT. 0 loads all of it. Use it to carry on from a clip: a long clip then costs no more memory than a short one. |
Frame bounds use the source's frame-rate grid, independent of `force_rate`.
@@ -178,17 +186,17 @@ For example, start 24 and end 72 select two seconds from a 24 fps source.
A 12 fps forced rate returns 24 frames; a cap of 10 then keeps only the first
10 of those. Audio and duration follow the returned batch.
A connected start or end locks that handle and its IN/OUT field on both
A connected start or end locks that handle and its box on both
the node and fullscreen editor. Hover to see why. Disconnect to restore
local control. While timing inputs are connected, the preview shows the local
trim as a reference and avoids claiming an output count before the linked
values are evaluated at run time.
**A connected length input takes over the length.** Connect a count to
`fixed_frames` (exact) or `frame_load_cap` (at most) and the OUT handle goes
away, OUT and Length grey out, and only IN is left to set: the clip starts at
IN and the input decides where it ends. Literal Integer/Float nodes (including
`fixed_frames` (exact) or `frame_load_cap` (at most) and the end handle goes
away, Duration and Ends at lock, and only Start is left to set: the clip starts
there and the input decides where it ends. Literal Integer/Float nodes (including
AusBoss cards and reroutes) show the resulting frames on the rail before
running; calculated counts show "at run time". An older workflow that saved a
Fixed frames number without a connection reads as a Length; the first change
Fixed frames number without a connection reads as a Duration; the first change
here turns it into one.
+6 -4
View File
@@ -60,10 +60,12 @@ answered on the same line as the button.
- A found file swaps its Download button for an **✓ installed** pill; hovering
the pill shows where it was found. A file that lives in a subfolder still
counts. When a loader in the workflow still asks for the bare file name,
which ComfyUI cannot find there (it marks that loader red), the row says
where the file is instead (**in LTXV 2.3/**) and **Use it** points those
loaders at the copy it found. The check only asks the ComfyUI server for its
own model lists.
which ComfyUI cannot find there (it marks that loader red), the note points
that loader at your copy by itself and says so in a short message. If you
have two copies in different subfolders, the row says where one is
(**in LTXV 2.3/**) and **Use it** picks it. To always choose yourself, turn
off Settings, 🆎 AusBoss, Models, **Pick found files**. The check only asks
the ComfyUI server for its own model lists.
- **↻ check files** re-runs the check after you move files in. ComfyUI's own
**R** refresh triggers it as well.
- Folder `input` is for a sample image or clip shipped with the workflow: it
+28 -13
View File
@@ -20,21 +20,36 @@ export function outputWindow(durationValue, startValue, endValue, maxValue = 0)
return { start, end, keepEnd, length: keepEnd - start, cut: Math.max(0, end - keepEnd) };
}
// "0:12.0" style, the way the IN and OUT fields write a time.
export function secondsLabel(value) {
const seconds = Math.max(0, finite(value));
if (seconds < 60) return `${seconds.toFixed(1)} s`;
const minutes = Math.floor(seconds / 60);
return `${minutes}:${(seconds - minutes * 60).toFixed(1).padStart(4, "0")}`;
const hundredth = (value) => Math.round(value * 100) / 100;
// What the face stores for a pick from `start` to `end`: a Start and a
// Duration (max_seconds, with end_seconds at 0, "to the end"). A pick that
// reaches the end of the file needs no Duration. When another node sets the
// Duration or the end, the pick is stored as a start and an end instead.
// A key left out is not written.
export function pickWrites(durationValue, startValue, endValue, { maxLinked = false, endLinked = false } = {}) {
const duration = Math.max(0, finite(durationValue));
const start = hundredth(Math.min(Math.max(0, finite(startValue)), duration));
const end = hundredth(Math.max(start, Math.min(finite(endValue), duration)));
const toEnd = end >= duration - 0.005;
if (endLinked) return { start };
if (maxLinked) return { start, end: toEnd ? 0 : end };
return { start, end: 0, max: toEnd ? 0 : Math.max(0.01, hundredth(end - start)) };
}
// The line between IN and OUT: what comes out, and what the max cuts off.
export function outputSummary(window, { maxFromLink = false } = {}) {
if (!window || window.length <= 0) return "";
const parts = [secondsLabel(window.length)];
if (window.cut > 0.005) parts.push(`cut ${secondsLabel(window.cut)}`);
if (maxFromLink) parts.push("max wired");
return parts.join(" · ");
// A value typed into Start, Duration or Ends at, as the pick it makes.
// Start keeps the Duration; Duration and Ends at keep the start. An empty
// or 0 Duration, and an empty Ends at, run to the end of the file.
export function typedPick(key, value, window, durationValue, minimum = 0.1) {
const duration = Math.max(0, finite(durationValue));
const clampTime = (time) => Math.min(duration, Math.max(0, finite(time)));
if (key === "start") {
const start = clampTime(value);
return { start, end: Math.min(duration, start + window.length) };
}
if (value == null || (key === "duration" && !(finite(value) > 0))) return { start: window.start, end: duration };
const end = key === "duration" ? window.start + Math.max(minimum, finite(value)) : Math.max(window.start + minimum, finite(value));
return { start: window.start, end: clampTime(end) };
}
// Loud and quiet across the file: for each of `buckets` slices, the lowest
+118 -110
View File
@@ -1,30 +1,35 @@
// Load Audio 🆎 - the wave, the trim and the player.
// Load Audio 🆎 - the wave, the timing and the player.
//
// The card above (js/widget_cards) holds Source and Max length. This panel
// draws the whole file as a wave: the part that comes out is bright, the
// part a Max length cuts off is red, and the rest is dim. Drag a handle to
// move IN or OUT, drag the middle to slide the pick, or click elsewhere to
// move it there. Play plays only what comes out. The widgets underneath
// (start_seconds, end_seconds, max_seconds) stay the source of truth.
// The card above (js/widget_cards) holds Source. This panel draws the whole
// file as a wave: the part that comes out is bright and the rest is dim.
// Under it, Start, Duration and Ends at, as on the video nodes. Drag a
// handle on the wave to move the start or the end, drag the middle to slide
// the sound, or click elsewhere to move it there. Play plays only what comes
// out. The widgets underneath stay the source of truth: the Duration is
// max_seconds with end_seconds at 0. A saved end (or a linked Max length)
// still works: the part a Max length cuts off shows red.
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
import { formatTimecode } from "../shared/timecode.mjs";
import { inputNumber } from "../shared/clip_rate.mjs";
import { makeScrubInput } from "../shared/scrub_input.mjs";
import { linkedNodeInfo } from "../shared/timing_links.mjs";
import { parseImageReference } from "../shared/pad_canvas.mjs";
import { mediaViewQuery, splitMediaName } from "../shared/video_preview.mjs";
import { ensureVideoCss, hideCanvasWidget, makeToolButton } from "../shared/video_ui.mjs";
import { MIN_TRIM_SECONDS, dragTrimHandle, slideTrimWindow } from "../load_video/trim_preview.mjs";
import { grabZone, outputSummary, outputWindow, secondsLabel, wavePeaks } from "./audio_window.mjs";
import { grabZone, outputWindow, pickWrites, typedPick, wavePeaks } from "./audio_window.mjs";
const NODE_NAME = "AUSBOSS_NODES_LoadAudio";
const PANEL_WIDGET = "ausboss_load_audio_wave";
// The frontend's own player for an audio_upload input. The wave replaces it.
const CORE_AUDIO_WIDGET = "audioUI";
const MIN_WIDTH = 280;
// 8px root padding + the wave's 28px floor + 6px gap + the 22px play, IN/OUT and loop row.
const PANEL_MIN_HEIGHT = 64;
// 8px root padding + the wave's 28px floor + 6px gap + the 38px Start,
// Duration and Ends at row (a label over a box).
const PANEL_MIN_HEIGHT = 80;
// Opens small and neat: 300 px wide, with a wave about as tall as a field
// (32 px). Drag the corner down for a taller wave.
const DEFAULT_WIDTH = 300;
@@ -50,26 +55,32 @@ function hideCoreAudio(node) {
}
}
// A wired Max length: the number the wire carries, when the far end is a
// node that shows it (Float, Integer, a Primitive). null when it can't be known.
function wiredMax(node) {
const input = node.inputs?.find((slot) => slot?.widget?.name === "max_seconds");
if (!input || input.link == null) return { wired: false, value: null };
const graph = node.graph;
const link = graph?.getLink?.(input.link) ?? graph?.links?.get?.(input.link) ?? graph?.links?.[input.link];
const origin = link ? graph?.getNodeById?.(link.origin_id) : null;
const shown = origin?.widgets?.find((widget) => typeof widget?.value === "number");
return { wired: true, value: shown ? Number(shown.value) : null };
function linked(node, name) {
return !!node.inputs?.some((slot) => slot?.widget?.name === name && slot.link != null);
}
// A value as the run will see it: the widget, or the number a linked input
// carries when the far end is a typed number (through Reroutes and
// subgraphs). null when only the run knows it.
function valueOf(state, name, widget) {
if (!linked(state.node, name)) return Number(widget?.value) || 0;
return inputNumber(state.node, name, null);
}
function maxSeconds(state) {
const wired = wiredMax(state.node);
if (wired.wired) return { value: wired.value ?? 0, fromLink: true, known: wired.value != null };
return { value: Number(state.maxWidget?.value) || 0, fromLink: false, known: true };
const fromLink = linked(state.node, "max_seconds");
const value = valueOf(state, "max_seconds", state.maxWidget);
return { value: value ?? 0, fromLink, known: value != null };
}
function currentWindow(state) {
return outputWindow(state.duration, state.startWidget.value, state.endWidget.value, maxSeconds(state).value);
const start = valueOf(state, "start_seconds", state.startWidget) ?? 0;
const max = maxSeconds(state).value;
let end = valueOf(state, "end_seconds", state.endWidget) ?? 0;
// No end and a Duration: the Duration is where the sound stops, so
// nothing past it shows as cut off. Only an end past the Duration does.
if (!(end > 0) && max > 0 && state.duration > 0) end = Math.min(state.duration, Math.max(0, start) + max);
return outputWindow(state.duration, start, end, max);
}
async function loadPeaks(name, route) {
@@ -105,16 +116,15 @@ function ensureAudioCss() {
.ausboss-audio-error{pointer-events:auto;border:0;background:transparent;color:#e6bf87;font:11px system-ui;cursor:pointer;white-space:nowrap}
.ausboss-audio-root canvas.ausboss-audio-wave{position:absolute;inset:0;width:100%;height:100%;display:block;}
.ausboss-audio-root .ausboss-video-stage:not(.is-empty) .ausboss-video-status{display:none;}
.ausboss-audio-root .ausboss-audio-row{display:flex;align-items:center;gap:6px;flex:none;padding:0 2px;}
.ausboss-audio-root .ausboss-audio-row .ausboss-video-values{flex:1 1 auto;min-width:0;}
.ausboss-audio-root .ausboss-audio-play{min-width:30px;font-size:10px;}
.ausboss-audio-root .ausboss-audio-length{flex:none;padding:0 2px;color:#7fd9d2;font-size:10px;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:default;}
.ausboss-audio-root .ausboss-audio-length:empty{display:none;}
.ausboss-audio-root .ausboss-audio-length.has-cut{color:#ff9aa0;cursor:pointer;text-decoration:underline dotted rgba(224,82,90,.8);text-underline-offset:2px;}
.ausboss-audio-root .ausboss-audio-row .ausboss-video-tool{flex:none;}
.ausboss-audio-root .ausboss-video-values{display:flex;gap:8px;}
.ausboss-audio-root .ausboss-video-value input{width:48px;}
.ausboss-audio-root .ausboss-audio-length{margin-left:auto;}
.ausboss-audio-root .ausboss-audio-wave-row{display:flex;align-items:stretch;gap:6px;flex:1 1 auto;min-height:28px;}
.ausboss-audio-root .ausboss-audio-wave-row .ausboss-video-stage{flex:1 1 auto;min-width:0;}
.ausboss-audio-root .ausboss-audio-play{flex:none;align-self:center;min-width:30px;font-size:10px;}
.ausboss-audio-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;flex:none;padding:0 2px;color:#ddd;font:11px system-ui;}
.ausboss-audio-field{display:flex;flex-direction:column;gap:2px;min-width:0;}
.ausboss-audio-field .ausboss-scrub{width:100%;box-sizing:border-box;}
.ausboss-audio-field-label{display:flex;align-items:center;gap:6px;min-width:0;color:#cadddb;}
.ausboss-audio-go{border:0;background:transparent;padding:0;color:#45d6cb;font:600 10px system-ui;text-decoration:underline;cursor:pointer;}
.ausboss-audio-go[hidden]{display:none;}
`;
document.head.appendChild(style);
}
@@ -192,21 +202,31 @@ function draw(state) {
}
}
// One box's look: its value, whether it can be typed, and the "linked"
// button when another node sets it.
function showField(state, key, value, lockedBy, tip) {
const field = state.fields[key];
field.control.set(value);
field.control.root.style.opacity = lockedBy ? ".45" : "";
field.control.root.inert = Boolean(lockedBy);
field.go.hidden = !lockedBy;
field.cell.title = lockedBy ? `Set by ${lockedBy.title}. Click "linked" to go to that node.` : tip;
if (lockedBy) field.go.onclick = () => lockedBy.go?.();
}
function updateFace(state) {
const win = currentWindow(state);
const max = maxSeconds(state);
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(win.start);
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(win.end);
if (state.duration > 0) {
const summary = outputSummary(win, { maxFromLink: max.fromLink && !max.known });
state.summary.textContent = win.length > 0 ? secondsLabel(win.length) : "";
state.summary.classList.toggle("has-cut", win.cut > 0.005);
state.summary.title = win.cut > 0.005
? `${summary}. Max length is ${max.value} s, so ${formatTimecode(win.keepEnd)} to ${formatTimecode(win.end)} is cut off (red). Click to move OUT to ${formatTimecode(win.keepEnd)}.`
: `${summary}: ${formatTimecode(win.start)} to ${formatTimecode(win.keepEnd)} comes out.`;
} else {
state.summary.textContent = "";
}
const link = (name) => (linked(state.node, name) ? linkedNodeInfo(state.node, name) : null);
// A linked value the page cannot read is only known when the graph runs:
// its box, and the boxes that depend on it, stay empty.
const known = (name) => !linked(state.node, name) || inputNumber(state.node, name, null) != null;
const has = state.duration > 0;
const startKnown = has && known("start_seconds");
const lengthKnown = startKnown && known("max_seconds") && known("end_seconds");
showField(state, "start", startKnown ? win.start : null, link("start_seconds"), `Where the sound starts in the file, of ${formatTimecode(state.duration)}.`);
showField(state, "duration", lengthKnown ? win.length : null, link("max_seconds"),
win.cut > 0.005 ? `How long the sound is. It stops ${formatTimecode(win.cut)} before the saved end (red).` : "How long the sound is. Clear it, or type 0, to run to the end of the file.");
showField(state, "end", lengthKnown ? win.keepEnd : null, link("end_seconds"), "Where the sound stops in the file. Typing it changes the Duration.");
draw(state);
}
@@ -217,12 +237,19 @@ function writeWidget(widget, value) {
widget.callback?.(next);
}
// The pick, stored the way the face shows it (pickWrites): a Start and a
// Duration, or a start and an end when another node sets the Duration.
function writeTrim(state, bounds) {
state.writing = true;
try {
writeWidget(state.startWidget, bounds.start);
// OUT at the very end stays 0, the widget's own "to the end".
writeWidget(state.endWidget, bounds.end >= state.duration - 0.005 ? 0 : bounds.end);
const startLinked = linked(state.node, "start_seconds");
const writes = pickWrites(state.duration, startLinked ? currentWindow(state).start : bounds.start, bounds.end, {
maxLinked: linked(state.node, "max_seconds") || !state.maxWidget,
endLinked: linked(state.node, "end_seconds"),
});
if (!startLinked) writeWidget(state.startWidget, writes.start);
if (writes.end !== undefined) writeWidget(state.endWidget, writes.end);
if (writes.max !== undefined) writeWidget(state.maxWidget, writes.max);
} finally {
state.writing = false;
}
@@ -248,7 +275,7 @@ function installDrag(state) {
event.preventDefault();
event.stopPropagation();
const initial = infoAt(event.clientX);
const bounds = { start: initial.win.start, end: initial.win.end };
const bounds = { start: initial.win.start, end: initial.win.keepEnd };
const anchor = initial.fraction * state.duration;
const downX = event.clientX;
let moved = false;
@@ -262,7 +289,7 @@ function installDrag(state) {
const next = infoAt(clientX);
if (initial.zone === "start" || initial.zone === "end") {
const now = currentWindow(state);
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.end }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.keepEnd }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
} else if (initial.zone === "move") {
writeTrim(state, slideTrimWindow(state.duration, bounds, next.fraction * state.duration - anchor));
} else {
@@ -336,19 +363,6 @@ function installPlayer(state) {
state.stopPlayer = () => { audio.pause(); stop(); };
}
function commitTimeInput(state, edge, input) {
if (state.duration <= 0) return;
const seconds = parseTimecode(input.value);
const win = currentWindow(state);
if (seconds === null) {
input.value = formatTimecode(edge === "start" ? win.start : win.end);
return;
}
writeTrim(state, dragTrimHandle(state.duration, { start: win.start, end: win.end }, edge, seconds / state.duration, MIN_TRIM_SECONDS));
notifyAusbossChange();
input.blur();
}
function watchWidget(state, widget) {
if (!widget || widget.__ausbossAudioWatch) return;
widget.__ausbossAudioWatch = true;
@@ -385,37 +399,44 @@ function buildPanel(node) {
playButton.classList.add("ausboss-audio-play");
const loopButton = makeToolButton("LOOP", "Play it again and again");
stage.append(canvas, status);
// Play and Loop sit either side of the wave, so neither covers a handle.
loopButton.classList.add("ausboss-audio-play");
const waveRow = document.createElement("div");
waveRow.className = "ausboss-audio-wave-row";
waveRow.append(playButton, stage, loopButton);
const values = document.createElement("div");
values.className = "ausboss-video-values";
const makeValue = (labelText, title) => {
const wrap = document.createElement("div");
wrap.className = "ausboss-video-value";
const label = document.createElement("label");
label.textContent = labelText;
const input = document.createElement("input");
input.type = "text";
input.inputMode = "decimal";
input.placeholder = "m:ss.s";
input.title = title;
input.addEventListener("keydown", (event) => {
keepKeyInField(event);
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
});
wrap.append(label, input);
return { wrap, input };
// Start, Duration and Ends at, as on the video nodes, in seconds.
const fieldsRow = document.createElement("div");
fieldsRow.className = "ausboss-audio-fields";
const fields = {};
const commit = (key, value) => {
const state = node.__ausbossLoadAudio;
if (!state || state.duration <= 0) return;
writeTrim(state, typedPick(key, value, currentWindow(state), state.duration, MIN_TRIM_SECONDS));
};
const startValue = makeValue("IN", "Where the sound starts. Type seconds (12.5) or a time (0:12.5).");
const endValue = makeValue("OUT", "Where the sound stops. Type seconds (24) or a time (0:24.0).");
// How long the output is, beside OUT and off the wave. Red when Max
// length cuts the pick short; the tooltip says how much.
const summary = document.createElement("div");
summary.className = "ausboss-audio-length";
values.append(startValue.wrap, endValue.wrap);
const row = document.createElement("div");
row.className = "ausboss-audio-row";
row.append(playButton, values, summary, loopButton);
root.append(stage, row);
for (const [key, caption] of [["start", "Start"], ["duration", "Duration"], ["end", "Ends at"]]) {
const cell = document.createElement("div");
cell.className = "ausboss-audio-field";
const label = document.createElement("span");
label.className = "ausboss-audio-field-label";
label.textContent = caption;
const go = document.createElement("button");
go.type = "button";
go.className = "ausboss-audio-go";
go.textContent = "linked";
go.hidden = true;
label.append(go);
const control = makeScrubInput({
value: 0, min: 0, max: 86400, step: 0.1, fineStep: 0.01, decimals: 2, minDecimals: 0, unit: "s", unitWidth: 14,
allowEmpty: true,
onChange: (value) => commit(key, value),
onSettle: () => notifyAusbossChange(),
});
cell.append(label, control.root);
fieldsRow.append(cell);
fields[key] = { cell, control, go };
}
root.append(waveRow, fieldsRow);
const widget = node.addDOMWidget(PANEL_WIDGET, "ausboss_audio", root, {
serialize: false,
@@ -435,22 +456,11 @@ function buildPanel(node) {
audio.preload = "auto";
const abort = new AbortController();
const state = node.__ausbossLoadAudio = {
node, root, stage, canvas, status, playButton, loopButton, summary, audio,
startInput: startValue.input, endInput: endValue.input,
node, root, stage, canvas, status, playButton, loopButton, audio, fields,
audioWidget, startWidget, endWidget, maxWidget: findWidget(node, "max_seconds"),
duration: 0, peaks: null, abort, writing: false, dragging: false, raf: 0, loading: 0,
};
// Clicking the red length moves OUT to where the sound really ends.
summary.addEventListener("click", (event) => {
const win = currentWindow(state);
if (win.cut <= 0.005) return;
event.preventDefault();
event.stopPropagation();
writeTrim(state, { start: win.start, end: win.keepEnd });
notifyAusbossChange();
});
const updateLoop = () => loopButton.classList.toggle("active", loopEnabled(node));
updateLoop();
loopButton.addEventListener("click", (event) => {
@@ -509,8 +519,6 @@ function buildPanel(node) {
watchWidget(state, startWidget);
watchWidget(state, endWidget);
watchWidget(state, state.maxWidget);
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
const observer = new ResizeObserver(() => draw(state));
observer.observe(stage);
state.observer = observer;
+145 -355
View File
@@ -1,9 +1,11 @@
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
import { inputNumber } from "../shared/clip_rate.mjs";
import { clipInfo, windowSeconds } from "../shared/timeline_math.mjs";
import { mountTransformTrim } from "../shared/transform_trim.mjs";
import { linkedNodeInfo, timingUnits } from "../shared/timing_links.mjs";
import { parseImageReference } from "../shared/pad_canvas.mjs";
import {
mediaInfo,
@@ -19,42 +21,31 @@ import {
suppressCoreVideoPreview,
} from "../shared/video_ui.mjs";
import {
MIN_TRIM_SECONDS,
clampTrimSeek,
closestTrimHandle,
dragTrimHandle,
loadSummary,
playbackBoundaryAction,
singleFrameFraction,
singleFrameTime,
slideTrimWindow,
trimAfterFramePick,
trimBounds,
trimFractions,
} from "./trim_preview.mjs";
const NODE_NAME = "AUSBOSS_NODES_LoadVideo";
const PREVIEW_WIDGET = "ausboss_load_video_viewer";
const PREVIEW_CHROME = 88;
// The shared video root's CSS minimum: 8px root padding + the stage's 112px
// floor + 6px gap + the 76px trim strip. The declared floor adds
// WIDGET_FRAME on top, or the element comes up short and clips the trim
// strip's bottom border at the node's minimum height.
const PANEL_MIN_HEIGHT = 202;
// 8px root padding + the stage's 112px floor + 6px gap + the 152px timing
// card (js/shared/transform_trim.mjs). The declared floor adds WIDGET_FRAME
// on top, or the element comes up short and clips the card's bottom border
// at the node's minimum height.
const PANEL_MIN_HEIGHT = 278;
// Height the node opens at. It used to fall out of the panel's computeSize;
// with the panel free to follow the node, the default has to be stated. The
// chrome covers the transport row and the trim strip under the player.
const DEFAULT_NODE_SIZE = [380, responsivePreviewHeight(380) + PREVIEW_CHROME + 190];
// extra covers the tools over the picture and the timing card under it.
const DEFAULT_NODE_SIZE = [380, responsivePreviewHeight(380) + PREVIEW_CHROME + 210];
const TRIM_EPSILON = 0.04;
function findWidget(node, name) {
return node.widgets?.find((widget) => widget.name === name);
}
function roundHundredth(value) {
return Math.round(Number(value || 0) * 100) / 100;
}
function getLoopEnabled(node) {
node.properties ??= {};
if (node.properties.ausboss_load_video_loop === undefined) {
@@ -66,14 +57,25 @@ function getLoopEnabled(node) {
function setEmpty(state, text) {
state.stage.classList.add("is-empty");
state.status.textContent = text;
state.status.hidden = false;
}
function setReady(state, text) {
state.stage.classList.remove("is-empty");
state.status.textContent = text;
state.status.hidden = !text;
}
// The run's window in seconds, as the timing card works it out (Start, and
// the Duration or the end), or the plain start/end before the video's frame
// rate is known.
function currentBounds(state) {
const info = clipInfo(state.metadata);
const window = state.card?.window?.();
if (info.fps > 0 && window && Number.isFinite(window.first)) {
const last = Number.isFinite(window.last) ? window.last : info.count - 1;
return { start: window.first / info.fps, end: Math.min(info.duration || Infinity, (last + 1) / info.fps) };
}
return trimBounds(state.video.duration, state.startWidget.value, state.endWidget.value);
}
@@ -82,271 +84,116 @@ function isSingleFrame(state) {
}
// Where the preview belongs for the current mode: the chosen frame, or the
// trim window's IN point.
// clip's start.
function homeTime(state) {
return isSingleFrame(state)
? singleFrameTime(state.video.duration, state.startWidget.value)
: currentBounds(state).start;
}
function applyMode(state) {
const single = isSingleFrame(state);
state.root.classList.toggle("is-single-frame", single);
state.frameButton?.classList.toggle("active", single);
state.startLabel.textContent = single ? "AT" : "IN";
state.range.title = single
? "Drag or click to choose the frame that loads"
: "Drag either handle to set the trim; drag the selected range to move it";
updateTrimFace(state);
}
function widgetLinkDriven(node, name) {
return !!node.inputs?.some((input) => input?.widget?.name === name && input.link != null);
}
// The honest "what will actually load" text for the label under the trim
// strip, or "" when there is nothing honest to say. Any of the deciding
// widgets driven by a link means its face value is stale, so the count
// drops out rather than guessing.
function trimLoadSummary(state, duration, bounds) {
const deciders = ["start_seconds", "end_seconds", "every_nth", "max_frames", "single_frame"];
if (deciders.some((name) => widgetLinkDriven(state.node, name))) return "";
return loadSummary(
duration,
bounds,
state.sourceFps,
state.everyNthWidget?.value,
state.maxFramesWidget?.value,
isSingleFrame(state),
);
}
// The <video> element never exposes the source frame rate, so the frame
// count in the label needs a probe of the pack's metadata route. Fail-soft:
// on any error the label simply omits the count and the timecodes stand.
async function probeSourceFps(state, name) {
state.sourceFps = 0;
// Frame rate and the real frame count come from the pack's metadata route:
// the <video> element knows neither, and its length rounds up a frame.
// Fail-soft: without it the card waits for a source.
async function probeMetadata(state, name) {
state.metadata = null;
try {
const query = new URLSearchParams({ source_mode: "input folder", video: name });
const type = parseImageReference(name)?.type;
if (type && type !== "input") {
query.set("source_mode", "local path");
query.set("local_path", name);
}
const response = await api.fetchApi(`/ausboss/transform/video/metadata?${query}`);
if (!response.ok) return;
const metadata = await response.json();
if (state.videoWidget.value !== name) return; // a newer selection won
state.sourceFps = Math.max(0, Number(metadata?.fps) || 0);
updateTrimFace(state);
state.metadata = metadata;
state.card?.sync();
} catch (_error) {
/* no fps, no frame count */
/* no metadata, no timing card numbers */
}
}
function writeWidget(widget, value) {
const next = roundHundredth(value);
if (Math.abs(Number(widget.value || 0) - next) < 0.0001) return;
widget.value = next;
widget.callback?.(next);
function setWidget(widget, value) {
if (!widget) return;
if (widget.value === value) return;
widget.value = value;
widget.callback?.(value);
}
function writeTrim(state, bounds, seekEdge = null) {
state.writing = true;
try {
writeWidget(state.startWidget, bounds.start);
writeWidget(state.endWidget, bounds.end);
} finally {
state.writing = false;
}
updateTrimFace(state);
if (state.video.readyState >= 1 && seekEdge) {
state.video.currentTime = seekEdge === "start"
? bounds.start
: Math.max(bounds.start, bounds.end - TRIM_EPSILON);
}
state.node.setDirtyCanvas?.(true, true);
state.node.graph?.setDirtyCanvas?.(true, true);
}
function writeFrameTime(state, timeValue) {
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
const time = singleFrameTime(duration, timeValue);
state.writing = true;
try {
writeWidget(state.startWidget, time);
} finally {
state.writing = false;
}
updateTrimFace(state);
if (state.video.readyState >= 1) state.video.currentTime = time;
state.node.setDirtyCanvas?.(true, true);
state.node.graph?.setDirtyCanvas?.(true, true);
}
function updateTrimFace(state) {
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
if (isSingleFrame(state)) {
const time = singleFrameTime(duration, state.startWidget.value);
const percent = singleFrameFraction(duration, time) * 100;
state.selection.style.width = "0%";
state.startHandle.style.left = `${percent}%`;
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(time);
// "1 frame at 0:05.2" - the count comes from the same pure summary the
// trim label uses, so both modes report what one Run will load.
const summary = trimLoadSummary(state, duration, null);
state.durationLabel.textContent = duration > 0
? `${summary || "frame"} at ${formatTimecode(time)}`
: "load a video to pick a frame";
if (duration > 0) state.status.textContent = `frame at ${formatTimecode(time)}`;
return;
}
const bounds = trimBounds(duration, state.startWidget.value, state.endWidget.value);
const fractions = trimFractions(duration, bounds);
const startPercent = fractions.start * 100;
const endPercent = fractions.end * 100;
state.selection.style.left = `${startPercent}%`;
state.selection.style.width = `${Math.max(0, endPercent - startPercent)}%`;
state.startHandle.style.left = `${startPercent}%`;
state.endHandle.style.left = `${endPercent}%`;
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(bounds.start);
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(bounds.end);
const selected = Math.max(0, bounds.end - bounds.start);
// The preview cannot re-render every_nth or max_frames, so the label
// reports them instead: "0:04.0 of 0:10.0 · 48 frames @ 12 fps".
const summary = trimLoadSummary(state, duration, bounds);
state.durationLabel.textContent = duration > 0
? `${formatTimecode(selected)} of ${formatTimecode(duration)}${summary ? ` · ${summary}` : ""}`
: "load a video to trim";
state.status.textContent = duration > 0
? `${formatTimecode(bounds.start)} → ${formatTimecode(bounds.end)}`
: state.status.textContent;
}
function installTrimDrag(state) {
const { range } = state;
const infoAt = (clientX) => {
const rect = range.getBoundingClientRect();
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
const bounds = currentBounds(state);
const fractions = trimFractions(duration, bounds);
const x = clientX - rect.left;
const hit = 10;
let zone = "jump";
const closest = closestTrimHandle(
fractions.start,
fractions.end,
rect.width ? x / rect.width : 0,
rect.width,
hit,
);
if (closest) zone = closest;
else if (x > fractions.start * rect.width && x < fractions.end * rect.width) zone = "move";
return { rect, duration, bounds, fraction: rect.width ? x / rect.width : 0, zone };
};
range.addEventListener("pointermove", (event) => {
if (state.dragging) return;
if (isSingleFrame(state)) {
range.style.cursor = "ew-resize";
return;
}
const { zone } = infoAt(event.clientX);
range.style.cursor = zone === "start" || zone === "end"
? "ew-resize"
: zone === "move" ? "grab" : "pointer";
});
range.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || state.dragging) return;
const initial = infoAt(event.clientX);
if (initial.duration <= 0) return;
event.preventDefault();
event.stopPropagation();
if (isSingleFrame(state)) {
// Frame-picker gesture: the strip is one scrub rail. A click already
// sets the frame; a drag keeps refining it until release.
state.dragging = true;
try { range.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
const scrub = (clientX) => {
const next = infoAt(clientX);
writeFrameTime(state, next.fraction * next.duration);
};
scrub(event.clientX);
const move = (moveEvent) => {
if (!(moveEvent.buttons & 1)) { finish(); return; }
scrub(moveEvent.clientX);
};
const finish = () => {
if (!state.dragging) return;
state.dragging = false;
range.removeEventListener("pointermove", move);
try { range.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
// One notification per gesture: the frame changed on pointerdown.
notifyAusbossChange();
};
range.addEventListener("pointermove", move);
range.addEventListener("pointerup", finish, { once: true });
range.addEventListener("pointercancel", finish, { once: true });
range.addEventListener("lostpointercapture", finish, { once: true });
return;
}
state.dragging = true;
try { range.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
const downX = event.clientX;
const anchorTime = initial.fraction * initial.duration;
let moved = false;
const apply = (clientX) => {
const next = infoAt(clientX);
if (initial.zone === "start" || initial.zone === "end") {
writeTrim(
state,
dragTrimHandle(next.duration, currentBounds(state), initial.zone, next.fraction),
initial.zone,
);
} else if (initial.zone === "move") {
const pointerTime = next.fraction * next.duration;
writeTrim(
state,
slideTrimWindow(next.duration, initial.bounds, pointerTime - anchorTime),
"start",
);
} else {
const span = initial.bounds.end - initial.bounds.start;
const centeredStart = next.fraction * next.duration - span / 2;
writeTrim(
state,
slideTrimWindow(next.duration, initial.bounds, centeredStart - initial.bounds.start),
"start",
);
// The timing card: the clip node's own, with Start, Duration and Ends at,
// or, while FRAME is on, its frame picker. The player above it is the
// picture, so the card leaves out its own Play button.
function mountCard(state) {
const { node } = state;
const widgetFor = (name) => node.widgets?.find((widget) => widget.name === name);
const fps = () => clipInfo(state.metadata).fps;
const single = isSingleFrame(state);
const card = mountTransformTrim({
get: (name, fallback) => {
if (name === "frame_index") return state.head ?? 0;
const widget = widgetFor(name);
return widget ? widget.value : fallback;
},
set: (name, value) => {
state.writing = true;
try { setWidget(widgetFor(name), value); } finally { state.writing = false; }
if (state.video.readyState >= 1 && !state.video.paused) return;
node.setDirtyCanvas?.(true, true);
},
has: (name) => Boolean(widgetFor(name)),
driven: (name) => widgetLinkDriven(node, name),
number: (name, fallback) => inputNumber(node, name, fallback),
metadata: () => state.metadata,
trim: !single,
play: false,
isPlaying: () => !state.video.paused,
onTogglePlayback: () => {},
onSeek: (frame, settled) => {
state.head = frame;
const rate = fps();
if (single && rate > 0) {
state.writing = true;
try { setWidget(state.startWidget, windowSeconds(clipInfo(state.metadata), frame, frame).start_seconds); } finally { state.writing = false; }
}
};
const move = (moveEvent) => {
if (!(moveEvent.buttons & 1)) { finish(moveEvent); return; }
if (!moved && Math.abs(moveEvent.clientX - downX) < 3) return;
moved = true;
apply(moveEvent.clientX);
};
const finish = (finishEvent) => {
if (!state.dragging) return;
state.dragging = false;
range.removeEventListener("pointermove", move);
try { range.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
if (!moved && initial.zone === "jump") {
const next = infoAt(finishEvent?.clientX ?? downX);
const span = initial.bounds.end - initial.bounds.start;
const centeredStart = next.fraction * next.duration - span / 2;
writeTrim(
state,
slideTrimWindow(next.duration, initial.bounds, centeredStart - initial.bounds.start),
"start",
);
}
// One notification per gesture, on release — never per pointermove.
if (moved || initial.zone === "jump") notifyAusbossChange();
};
range.addEventListener("pointermove", move);
range.addEventListener("pointerup", finish, { once: true });
range.addEventListener("pointercancel", finish, { once: true });
range.addEventListener("lostpointercapture", finish, { once: true });
if (state.video.readyState >= 1 && rate > 0) state.video.currentTime = Math.min(state.video.duration || Infinity, (frame + 0.5) / rate);
if (settled) notifyAusbossChange();
},
onCommit: notifyAusbossChange,
linkInfo: (name) => linkedNodeInfo(node, name),
units: () => timingUnits(),
setUnits: (next) => timingUnits(next),
});
state.card?.root.remove();
state.card = card;
state.cardSlot.append(card.root);
return card;
}
function applyMode(state) {
const single = isSingleFrame(state);
state.root.classList.toggle("is-single-frame", single);
state.frameButton?.classList.toggle("active", single);
if (state.cardMode !== single) {
state.cardMode = single;
mountCard(state);
}
state.card?.sync();
}
// The playhead follows the player, so the card's marker and readout move
// with the picture.
function followPlayer(state) {
const rate = clipInfo(state.metadata).fps;
if (!(rate > 0)) return;
const frame = Math.max(0, Math.floor(state.video.currentTime * rate + 1e-6));
if (frame === state.head) return;
state.head = frame;
state.card?.sync();
}
function installPlayback(state) {
@@ -356,9 +203,9 @@ function installPlayback(state) {
state.playRaf = 0;
};
const tick = () => {
if (video.paused || video.ended) { stopTick(); return; }
// Frame picking plays the whole source freely — the trim window is not
// in force, so there is no boundary to loop or stop at.
if (video.paused || video.ended) { stopTick(); followPlayer(state); return; }
// Frame picking plays the whole source freely - the clip is not in
// force, so there is no boundary to loop or stop at.
if (!isSingleFrame(state)) {
const bounds = currentBounds(state);
const action = playbackBoundaryAction(video.currentTime, bounds, getLoopEnabled(state.node), TRIM_EPSILON);
@@ -367,9 +214,11 @@ function installPlayback(state) {
} else if (action === "stop") {
video.pause();
video.currentTime = Math.max(bounds.start, bounds.end - TRIM_EPSILON);
followPlayer(state);
return;
}
}
followPlayer(state);
state.playRaf = requestAnimationFrame(tick);
};
video.addEventListener("play", () => {
@@ -390,7 +239,7 @@ function installPlayback(state) {
state.correctingSeek = true;
video.currentTime = target;
}, { signal: state.abort.signal });
video.addEventListener("seeked", () => { state.correctingSeek = false; }, { signal: state.abort.signal });
video.addEventListener("seeked", () => { state.correctingSeek = false; followPlayer(state); }, { signal: state.abort.signal });
state.stopTick = stopTick;
}
@@ -401,8 +250,8 @@ function watchTrimWidget(state, widget) {
widget.callback = function (...args) {
const result = prior?.apply(this, args);
if (!state.writing) {
updateTrimFace(state);
if (state.video.readyState >= 1) state.video.currentTime = homeTime(state);
state.card?.sync();
if (state.video.readyState >= 1 && state.video.paused) state.video.currentTime = homeTime(state);
}
return result;
};
@@ -416,7 +265,10 @@ function watchFrameWidget(state, widget) {
const result = prior?.apply(this, args);
if (!isSingleFrame(state)) {
const reopened = trimAfterFramePick(state.startWidget.value, state.endWidget.value);
if (reopened) writeTrim(state, reopened);
if (reopened) {
state.writing = true;
try { setWidget(state.endWidget, reopened.end); } finally { state.writing = false; }
}
}
applyMode(state);
if (state.video.readyState >= 1) state.video.currentTime = homeTime(state);
@@ -424,28 +276,6 @@ function watchFrameWidget(state, widget) {
};
}
function commitTimeInput(state, edge, input) {
const duration = Number.isFinite(state.video.duration) ? state.video.duration : 0;
if (duration <= 0) return;
const seconds = parseTimecode(input.value);
if (seconds === null) {
// Malformed entry: restore the previous value and keep focus for a retry.
const bounds = currentBounds(state);
input.value = formatTimecode(edge === "start" ? bounds.start : bounds.end);
return;
}
if (isSingleFrame(state)) {
writeFrameTime(state, seconds);
notifyAusbossChange();
input.blur();
return;
}
const fraction = seconds / duration;
writeTrim(state, dragTrimHandle(duration, currentBounds(state), edge, fraction), edge);
notifyAusbossChange();
input.blur();
}
function buildPreview(node) {
if (node.__ausbossLoadVideo) return node.__ausbossLoadVideo;
const videoWidget = findWidget(node, "video");
@@ -461,6 +291,8 @@ function buildPreview(node) {
hideCanvasWidget(startWidget);
hideCanvasWidget(endWidget);
if (frameWidget) hideCanvasWidget(frameWidget);
// Every nth and the frame limit (the Duration) live in the timing card;
// the widget card hides their widgets (js/widget_cards).
const root = document.createElement("div");
root.className = "ausboss-video-root";
@@ -475,7 +307,7 @@ function buildPreview(node) {
status.textContent = "Choose or upload a video";
const tools = document.createElement("div");
tools.className = "ausboss-video-tools";
const loopButton = makeToolButton("LOOP", "Loop playback inside the selected trim");
const loopButton = makeToolButton("LOOP", "Play the clip again and again");
loopButton.classList.add("ausboss-video-loop");
const reloadButton = makeToolButton("↻", "Reload the selected source video");
const frameButton = frameWidget
@@ -485,45 +317,12 @@ function buildPreview(node) {
tools.append(loopButton, reloadButton);
stage.append(video, status, tools);
const trim = document.createElement("div");
trim.className = "ausboss-video-trim";
const range = document.createElement("div");
range.className = "ausboss-video-range";
range.title = "Drag either handle to set the trim; drag the selected range to move it";
const selection = document.createElement("div");
selection.className = "ausboss-video-selection";
const startHandle = document.createElement("div");
startHandle.className = "ausboss-video-handle";
const endHandle = document.createElement("div");
endHandle.className = "ausboss-video-handle is-end";
range.append(selection, startHandle, endHandle);
const values = document.createElement("div");
values.className = "ausboss-video-values";
const makeValue = (labelText) => {
const wrap = document.createElement("div");
wrap.className = "ausboss-video-value";
const label = document.createElement("label");
label.textContent = labelText;
const input = document.createElement("input");
input.type = "text";
input.inputMode = "decimal";
input.placeholder = "m:ss.s";
input.title = `${labelText} point - type seconds (95.5) or a timecode (1:35.5, 1:02:03.5)`;
input.addEventListener("keydown", (event) => {
keepKeyInField(event);
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
});
wrap.append(label, input);
return { wrap, input, label };
};
const startValue = makeValue("IN");
const endValue = makeValue("OUT");
endValue.wrap.classList.add("is-end");
const durationLabel = document.createElement("div");
durationLabel.className = "ausboss-video-duration";
values.append(startValue.wrap, durationLabel, endValue.wrap);
trim.append(range, values);
root.append(stage, trim);
// The timing card goes here (mountCard): the clip node's Start,
// Duration and Ends at, or the frame picker while FRAME is on.
const cardSlot = document.createElement("div");
cardSlot.className = "ausboss-video-timing";
cardSlot.style.flex = "none";
root.append(stage, cardSlot);
const widget = node.addDOMWidget(PREVIEW_WIDGET, "ausboss_video", root, {
serialize: false,
@@ -544,15 +343,9 @@ function buildPreview(node) {
const abort = new AbortController();
const state = node.__ausbossLoadVideo = {
node, root, stage, video, status, loopButton, reloadButton, frameButton,
trim, range, selection, startHandle, endHandle, startInput: startValue.input,
endInput: endValue.input, startLabel: startValue.label, durationLabel,
cardSlot, card: null, cardMode: null, metadata: null, head: 0,
videoWidget, startWidget, endWidget, frameWidget,
// Absent on a backend without these widgets; the summary then reads
// its defaults (keep every frame, no cap).
everyNthWidget: findWidget(node, "every_nth"),
maxFramesWidget: findWidget(node, "max_frames"),
sourceFps: 0,
widget, abort, writing: false, dragging: false, correctingSeek: false, playRaf: 0,
widget, abort, writing: false, correctingSeek: false, playRaf: 0,
};
const updateLoopButton = () => loopButton.classList.toggle("active", getLoopEnabled(node));
@@ -583,9 +376,9 @@ function buildPreview(node) {
if (!name || typeof name !== "string") {
video.pause();
video.removeAttribute("src");
state.sourceFps = 0;
state.metadata = null;
setEmpty(state, "Choose or upload a video");
updateTrimFace(state);
state.card?.sync();
return;
}
const parts = splitMediaName(name);
@@ -595,7 +388,7 @@ function buildPreview(node) {
const type = parseImageReference(name)?.type ?? "input";
video.src = api.apiURL(`/view?${mediaViewQuery({ ...parts, type }, "input")}`);
video.load();
probeSourceFps(state, name);
probeMetadata(state, name);
};
state.refresh = refresh;
reloadButton.addEventListener("click", (event) => {
@@ -605,31 +398,23 @@ function buildPreview(node) {
});
video.addEventListener("loadedmetadata", () => {
const single = isSingleFrame(state);
const bounds = currentBounds(state);
if (!single && bounds.end - bounds.start < MIN_TRIM_SECONDS && video.duration >= MIN_TRIM_SECONDS) {
writeTrim(state, { start: Math.max(0, bounds.end - MIN_TRIM_SECONDS), end: bounds.end });
}
video.currentTime = homeTime(state);
setReady(state, single
? `frame at ${formatTimecode(homeTime(state))}`
: `${formatTimecode(currentBounds(state).start)} → ${formatTimecode(currentBounds(state).end)}`);
// Quiet source hint: resolution and duration from the loaded metadata.
// The card says where the clip is; the stage only names the source on hover.
setReady(state, "");
const sourceInfo = mediaInfo(null, video);
durationLabel.title = sourceInfo ? `Source: ${sourceInfo}` : "";
updateTrimFace(state);
stage.title = sourceInfo ? `Source: ${sourceInfo}` : "";
state.card?.sync();
node.setDirtyCanvas?.(true, true);
}, { signal: abort.signal });
video.addEventListener("error", () => setEmpty(state, "Preview could not load this video"), { signal: abort.signal });
installTrimDrag(state);
installPlayback(state);
watchTrimWidget(state, startWidget);
watchTrimWidget(state, endWidget);
watchFrameWidget(state, frameWidget);
watchTrimWidget(state, findWidget(node, "every_nth"));
watchTrimWidget(state, findWidget(node, "max_frames"));
applyMode(state);
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
const priorVideoCallback = videoWidget.callback;
videoWidget.callback = function (...args) {
@@ -664,6 +449,11 @@ app.registerExtension({
}
});
});
// A wire into a timing input changes what the card can show.
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
const state = this.__ausbossLoadVideo;
if (state) queueMicrotask(() => state.card?.sync());
});
chainCallback(nodeType.prototype, "onRemoved", function () {
const state = this.__ausbossLoadVideo;
state?.stopTick?.();
+46
View File
@@ -13,6 +13,7 @@ import { makeScrubInput } from "../shared/scrub_input.mjs";
import { isAppShortcut, keepKeyInField } from "../shared/canvas_passthrough.mjs";
import { resetUnknownValues } from "../shared/widget_card_math.mjs";
import { boxRowInputs, boxRowsWidget, boxesOf, hostBox, rowsInputName, workflowNodes } from "../shared/lora_box.mjs";
import { coreLoraList, syncFileWidgets } from "../shared/lora_file_widgets.mjs";
import {
SETTINGS_PROPERTY as SWITCHES_PROPERTY, releaseStackGroup, releaseStackRow, renameStackGroup, stackGroupOwners, stackRowOwners,
} from "../shared/workflow_switches.mjs";
@@ -724,9 +725,47 @@ function commitRows(state, rows, { structural = false, record = true } = {}) {
state.node.graph?.setDirtyCanvas(true, true);
if (structural) renderRows(state);
else updateRowValues(state);
syncLoraFiles(state.node);
if (record) notifyAusbossChange();
}
// ComfyUI's missing-models list sees a row's file only through a list
// widget, so each row that needs a file gets a hidden one
// (js/shared/lora_file_widgets.mjs). Rows that come in over a link (from a
// box or another node) are not this node's to list.
function syncLoraFiles(node) {
if (node?.type !== NODE_CLASS) return;
const widget = node.widgets?.find((item) => item.name === "loras");
if (!widget) return;
const fed = node.inputs?.find((item) => item?.name === "loras")?.link != null;
syncFileWidgets(node, fed ? [] : parseRows(widget.value), {
installed: () => coreLoraList(globalThis.LiteGraph?.registered_node_types?.LoraLoader?.nodeData)
?? node.__ausbossLoraState?.available ?? null,
hide: hideWidget,
onPick: (rowId, name) => pickRowFile(node, rowId, name),
});
}
// ComfyUI put another file in a row's hidden list (a replacement picked in
// its Issues panel): the row takes that file.
function pickRowFile(node, rowId, name) {
const widget = node.widgets?.find((item) => item.name === "loras");
if (!widget) return;
const rows = parseRows(widget.value);
const row = rows.find((item) => item.id === rowId);
if (!row || row.name === name) return;
row.name = name;
const state = node.__ausbossLoraState;
if (state && !state.disposed && !state.readOnly && state.widget === widget) {
commitRows(state, rows, { structural: true });
return;
}
widget.value = serializeRows(rows);
node.graph?.setDirtyCanvas(true, true);
syncLoraFiles(node);
notifyAusbossChange();
}
// A box shows its loader's rows the way the loader does: one strength per
// row, or model and CLIP apart.
function linked(state) {
@@ -3027,6 +3066,7 @@ function syncRows(state) {
state.toggleSnapshot = snapshotEnabled(state.rows);
renderRows(state);
fitNode(state);
syncLoraFiles(state.node);
return true;
}
@@ -3324,6 +3364,12 @@ app.registerExtension({
});
chainCallback(nodeType.prototype, "onConfigure", function () {
resetUnknownValues(this.widgets, RESET_UNKNOWN);
// Now, not later: ComfyUI reads its missing-models list right after
// the workflow is restored.
syncLoraFiles(this);
});
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
syncLoraFiles(this);
});
},
// A box (subgraph node) shows the rows of a loader inside once they come
+59
View File
@@ -0,0 +1,59 @@
// App mode and the pack's cards. Pure logic, no DOM: tested under node:test.
//
// App mode is ComfyUI's simple form view of a workflow: a saved list of
// fields (extra.linearData.inputs) and a Run button. Each field is a
// widget. A node with a card or panel hides its standard widgets and shows
// its own controls instead, and App mode reads that hidden flag too, so the
// form drew an empty row for every field on such a node.
//
// While a workflow is in App mode, the widgets its form lists are shown
// again; App mode draws its own control for each. Back in the graph they are
// hidden again, so the node's face is unchanged. Only listed widgets move.
import { hideWidget, isWidgetHidden, showWidget } from "./widget_visibility.mjs";
export const APP_MODE = "app";
// "app", "graph" or "builder:..." for the open workflow.
export function workflowMode(workflow) {
return workflow?.activeMode ?? workflow?.initialMode ?? "graph";
}
// The form's fields as { nodeId, widget } pairs. A field is saved as
// [nodeId, widgetName] or [nodeId, widgetName, { description }].
export function appFields(linearData) {
const inputs = Array.isArray(linearData?.inputs) ? linearData.inputs : [];
const fields = [];
for (const entry of inputs) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const [nodeId, widget] = entry;
if ((typeof nodeId !== "string" && typeof nodeId !== "number") || typeof widget !== "string") continue;
fields.push({ nodeId: String(nodeId), widget });
}
return fields;
}
// find(nodeId, widgetName) -> { node, widget } or null
// changed(node) is called after a widget on that node changed visibility.
export function createAppModeSync({ find, changed = () => {} }) {
const lent = new Map(); // widget -> node, shown for the form
return function sync(mode, linearData) {
if (mode === APP_MODE) {
for (const { nodeId, widget: name } of appFields(linearData)) {
const found = find(nodeId, name);
if (!found?.widget || !isWidgetHidden(found.widget)) continue;
showWidget(found.widget);
// An explicit false, not a deleted flag: the frontend keeps its own
// copy of the hidden state and only hears about a written value.
if (found.widget.options) found.widget.options.hidden = false;
lent.set(found.widget, found.node);
changed(found.node);
}
return lent.size;
}
for (const [widget, node] of lent) {
if (hideWidget(widget)) changed(node);
}
lent.clear();
return 0;
};
}
+64 -16
View File
@@ -1,30 +1,78 @@
// Read only literal numeric sources. Calculated inputs must remain unknown
// until execution; never evaluate an arbitrary upstream graph for a label.
export function inputNumber(node, name, fallback) {
const input = node.inputs?.find((slot) => slot.name === name || slot.widget?.name === name);
if (input?.link == null) return fallback;
const graph = node.graph;
let linkId = input.link;
// A subgraph's output that comes straight from a literal inside it (Person
// Swap's "Pick the model files" hands out its video fps that way) counts as
// that literal: it is still a typed number, not a calculation.
function tableLink(graph, id) {
if (id == null || !graph) return null;
return graph.getLink?.(id) ?? graph.links?.get?.(id) ?? graph.links?.[id] ?? graph._links?.get?.(id) ?? null;
}
// The link into one of a node's inputs: the frontend's own accessor first
// (newer frontends warn on reading input.link), the link table after it.
// undefined when nothing is connected.
function linkInto(node, index, graph) {
if (typeof node?.getInputLink === "function" && node.graph) {
try {
return node.getInputLink(index) ?? undefined;
} catch {
return undefined;
}
}
const id = node?.inputs?.[index]?.link;
return id == null ? undefined : tableLink(node.graph ?? graph, id);
}
// Where a linked input really comes from: the node and output slot at the
// far end, through Reroutes and into a subgraph whose output is wired
// straight to a node inside it. null for a muted or bypassed source, a loop,
// or a subgraph output with nothing behind it. undefined when the input is
// not linked at all.
export function linkOrigin(node, name) {
const index = node?.inputs?.findIndex((slot) => slot?.name === name || slot?.widget?.name === name) ?? -1;
if (index < 0) return undefined;
let graph = node.graph;
let link = linkInto(node, index, graph);
if (link === undefined) return undefined;
const seen = new Set();
for (let depth = 0; depth < 16; depth++) {
if (seen.has(linkId)) return null;
seen.add(linkId);
const link = graph?.links?.[linkId] ?? graph?._links?.get?.(linkId);
const source = graph?.getNodeById?.(link?.origin_id);
if (!link || seen.has(link)) return null;
seen.add(link);
const source = graph?.getNodeById?.(link.origin_id);
if (!source || (source.mode ?? 0) !== 0) return null;
if (source.type === "Reroute") {
linkId = source.inputs?.[0]?.link;
if (linkId == null) return null;
if ((source.comfyClass ?? source.type) === "Reroute") {
link = linkInto(source, 0, graph) ?? null;
continue;
}
if (!["PrimitiveFloat", "PrimitiveInt", "AUSBOSS_NODES_Integer", "AUSBOSS_NODES_Float"].includes(source.type) || link.origin_slot !== 0) return null;
if (source.inputs?.some((slot) => slot.name === "value" && slot.link != null)) return null;
const value = source.widgets?.find((widget) => widget.name === "value")?.value;
return typeof value === "number" && Number.isFinite(value) ? value : null;
const inner = source.subgraph;
if (inner && typeof source.isSubgraphNode === "function" && source.isSubgraphNode()) {
link = tableLink(inner, inner.outputs?.[link.origin_slot]?.linkIds?.[0]);
graph = inner;
continue;
}
return { node: source, slot: link.origin_slot };
}
return null;
}
const LITERALS = ["PrimitiveFloat", "PrimitiveInt", "AUSBOSS_NODES_Integer", "AUSBOSS_NODES_Float"];
export function inputNumber(node, name, fallback) {
const origin = linkOrigin(node, name);
if (origin === undefined) return fallback;
if (!origin) return null;
const { node: source, slot } = origin;
// ComfyUI's older Primitive node holds the value of the widget it feeds.
if ((source.comfyClass ?? source.type) === "PrimitiveNode") {
const value = source.widgets?.[0]?.value;
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
if (!LITERALS.includes(source.type) || slot !== 0) return null;
if (source.inputs?.some((input) => input.name === "value" && input.link != null)) return null;
const value = source.widgets?.find((widget) => widget.name === "value")?.value;
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
export function clipOutputRate(node, sourceFps, everyNth = 1) {
const forced = inputNumber(node, "force_rate", 0);
const nth = inputNumber(node, "every_nth", everyNth);
+39
View File
@@ -1,3 +1,5 @@
import { linkOrigin } from "./clip_rate.mjs";
// The same live-input rule used by the writer timeline: muted/bypassed
// sources do not reach this node. This inspects the wire, never media bytes.
export function linkSource(node, name) {
@@ -9,6 +11,43 @@ export function linkSource(node, name) {
return (source?.mode ?? 0) === 0 ? source ?? null : null;
}
// Keep in step with Python video_frames (node_h3_prompt_writer.py): H3 makes
// 5 frames plus steps of 17, at most 15 s at 24 fps, rounding a clip down.
export const H3_FPS = 24;
export function h3VideoFrames(frames) {
const count = Math.trunc(Number(frames));
if (!(count > 0)) return null;
return Math.max(1, Math.floor((Math.min(count, 15 * H3_FPS) - 5) / 17)) * 17 + 5;
}
// What the clip node's face last worked out for its run ({frames,
// startSeconds, endSeconds}), or null when the clip is not that node or its
// count is only known at run time.
export function clipTimingFor(node) {
// Through Reroutes and subgraphs, as every linked value is read.
const timing = linkOrigin(node, "video")?.node?.__ausbossClipTiming;
return timing && timing.frames > 0 ? timing : null;
}
// The words under "From the clip": what H3 will make of the clip's frames.
export function clipLengthWords(timing) {
if (!timing) return null;
const made = h3VideoFrames(timing.frames);
const seconds = (frames) => String(Number((frames / H3_FPS).toFixed(2)));
if (made < timing.frames) {
const up = made + 17;
const room = timing.roomFrames ?? Infinity;
const stops = timing.startSeconds + made / H3_FPS;
return {
title: `H3 makes ${made} of the clip's ${timing.frames} frames · ${seconds(made)} s`,
note: `Stops at ${String(Number(stops.toFixed(2)))} s in the video. To use all of it, set the clip's Duration to ${seconds(made)} s${up <= Math.min(room, 15 * H3_FPS) ? ` or ${seconds(up)} s` : ""}.`,
warn: true,
};
}
if (made === timing.frames) return { title: `H3 uses all ${made} frames · ${seconds(made)} s`, note: "The clip is already a length H3 makes.", warn: false };
return { title: `H3 makes ${made} frames · ${seconds(made)} s`, note: `That is its shortest length; the clip has ${timing.frames} frames.`, warn: true };
}
// Keep in step with Python KEEPS_ITS_LENGTH. Other jobs use seconds normally.
export function clipSetsDuration(node, values) {
return ["swap the person", "new voice", "change something"].includes(values.video_job)
+1 -1
View File
@@ -9,7 +9,7 @@ import { app } from "../../../scripts/app.js";
// Must match `version` in pyproject.toml — scripts/release_preflight.py
// enforces it. The backend serves its copy at /ausboss/pack_version; a
// mismatch means the browser cached JavaScript from an older install.
export const AUSBOSS_JS_VERSION = "2.25.2";
export const AUSBOSS_JS_VERSION = "2.26.2";
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
export const BRAND_DARK = "#007f78";
+5 -2
View File
@@ -13,6 +13,7 @@
// what it always was. The turn is made in canvas pixels, so a turned box is a
// true rectangle on a canvas of any shape (nodes/_layout_boxes_helpers.py
// turns it the same way).
import { linkOrigin } from "./clip_rate.mjs";
export const DIM_MIN = 64;
export const DIM_MAX = 16384;
@@ -683,8 +684,10 @@ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
// (Integer, Primitive). Reroutes are followed. Null when the input is not
// wired or the value is only known once the workflow runs.
export function wiredNumber(node, inputName) {
const source = wiredSource(node, inputName);
return source ? wiredFrom(source.node, source.slot) : null;
// Through Reroutes and into subgraphs (js/shared/clip_rate.mjs), then
// this node's own rule for which numbers count.
const origin = linkOrigin(node, inputName);
return origin ? wiredFrom(origin.node, origin.slot) : null;
}
// The node (and its output slot) an input is wired to, through Reroutes.
+87
View File
@@ -0,0 +1,87 @@
// ComfyUI's missing-models list (the Issues panel, "Download all") only
// looks at list widgets: a model is listed when a list on some node holds a
// file name that is not one of its choices. LoRA Loader keeps its files in
// the rows' text, so a LoRA a workflow needs never made that list, and
// "Download all" then Run stopped on "missing LoRA file".
//
// The loader therefore carries one hidden list widget per row that needs a
// file. Nothing else reads them: they are kept out of the saved workflow and
// the prompt, have no socket, and are made again from the rows every time.
// The rows stay the one source of truth.
import { resolveLoraName } from "./lora_stack.mjs";
export const FILE_WIDGET_PREFIX = "ausboss_lora_file_";
export const FILE_WIDGET_FLAG = "ausbossLoraFile";
// Rows the server needs a file for when it runs: named, on, in a group that
// is on, and not at zero strength (nodes/_lora_helpers.py, missing_lora_rows).
export function rowsNeedingFiles(rows) {
return (Array.isArray(rows) ? rows : []).filter((row) => {
const name = typeof row?.name === "string" ? row.name.trim() : "";
if (!name || row.enabled === false || row.group_off === true) return false;
const strength = Number(row.strength ?? 1);
const clip = Number(row.strength_clip ?? strength);
return !(strength === 0 && clip === 0);
});
}
// The list ComfyUI checks a row's file against. A file the loader would
// find anyway (saved in another folder, or with other capitals) counts as
// installed; so does every file while the install's list is unknown, so a
// slow list never shows a false alarm.
export function fileChoices(name, installed) {
if (!Array.isArray(installed)) return [name];
return resolveLoraName(name, installed).status === "missing" ? installed : [...installed, name];
}
// The install's LoRA files as ComfyUI's own LoRA loader lists them. The node
// list arrives before any workflow opens, so this answers at once; null when
// there is no such node to ask.
export function coreLoraList(definition) {
const spec = definition?.input?.required?.lora_name;
if (!Array.isArray(spec)) return null;
if (Array.isArray(spec[0])) return spec[0];
if (spec[0] === "COMBO" && Array.isArray(spec[1]?.options)) return spec[1].options;
return null;
}
export function isFileWidget(widget) {
return Boolean(widget?.[FILE_WIDGET_FLAG]);
}
// Bring the node's file widgets in line with its rows. `installed()` returns
// the install's files (or null), `hide(widget)` folds a widget away, and
// `onPick(rowId, name)` runs when ComfyUI puts another file in a widget
// (choosing a replacement in the Issues panel). Returns true when a widget
// was added or removed.
export function syncFileWidgets(node, rows, { installed, hide, onPick }) {
if (!node || !Array.isArray(node.widgets)) return false;
const needed = rowsNeedingFiles(rows);
const current = node.widgets.filter(isFileWidget);
let changed = false;
needed.forEach((row, index) => {
let widget = current[index];
if (!widget) {
widget = node.addWidget("combo", `${FILE_WIDGET_PREFIX}${index + 1}`, row.name, (value) => {
if (typeof value === "string" && value !== widget.ausbossRowName) onPick?.(widget.ausbossRowId, value);
}, { values: () => fileChoices(widget.value, installed?.()), serialize: false });
widget[FILE_WIDGET_FLAG] = true;
widget.serialize = false;
hide?.(widget);
changed = true;
}
widget.value = row.name;
widget.ausbossRowName = row.name;
widget.ausbossRowId = row.id;
});
for (const widget of current.slice(needed.length)) {
if (typeof node.removeWidget === "function") node.removeWidget(widget);
else {
const at = node.widgets.indexOf(widget);
if (at >= 0) node.widgets.splice(at, 1);
}
changed = true;
}
return changed;
}
+7 -4
View File
@@ -2,7 +2,7 @@
// bar as long as the clip, with the cuts as marks. The server reads the script with the same code a run uses,
// so the bar shows what will happen. It also colours the script box, so the
// words the node reads as instructions (@1, 3s:, a cut) stand out.
import { clipSetsDuration, linkSource } from "./h3_duration.mjs";
import { clipLengthWords, clipSetsDuration, clipTimingFor, linkSource } from "./h3_duration.mjs";
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { BRAND, chainCallback } from "./index.mjs";
@@ -290,12 +290,15 @@ export function momentStrip(node) {
asked += 1;
ruler.textContent = "";
track.textContent = "";
const message = el("ausboss-strip-words", "Length comes from the clip");
// Say what H3 will make of the clip's frames, when the clip node knows
// its count; it rounds down to 5 + 17n, so a 48-frame clip gives 39.
const words = clipLengthWords(clipTimingFor(node));
const message = el("ausboss-strip-words", words?.title ?? "Length comes from the clip");
message.style.cssText = "display:flex;align-items:center;height:100%";
track.append(message);
note.textContent = "Set the clip's length upstream. Timing controls are unavailable here.";
note.textContent = words?.note ?? "Set the clip's length on the clip node. H3 makes 5 + 17n frames (22, 39, 56 ...), rounding the clip down.";
note.title = note.textContent;
note.classList.remove("warn");
note.classList.toggle("warn", Boolean(words?.warn));
return;
}
if (wired(node, "script")) {
+10
View File
@@ -5,6 +5,11 @@
// 2.0 draws each node as an element on the page, which can run past those
// bounds (its frame, a footer), so there the element itself is measured.
// Groups are drawn on the canvas in both looks.
//
// A frameless tile (a link tile, a title, a note tile) draws only a card
// inside a transparent node, so what people see is the card, not the node's
// bounds. Such a node names that card as `ausbossOutlineElement`, and its
// outline is the card's, in both looks.
function graphRectOf(element, canvas) {
const box = element.getBoundingClientRect();
@@ -34,6 +39,11 @@ export function nodeElements() {
}
export function outlineOf(item, canvas, { node = true, elements = null } = {}) {
const face = node && !item?.flags?.collapsed ? item?.ausbossOutlineElement : null;
if (face?.isConnected && canvas?.canvas && canvas.ds) {
const rect = graphRectOf(face, canvas);
if (rect) return rect;
}
if (node && globalThis.LiteGraph?.vueNodesMode === true && item?.id != null && canvas?.canvas && canvas.ds) {
const element = elements
? elements.get(String(item.id))
+10
View File
@@ -28,11 +28,15 @@ export function setTileFace(node, root, enabled, onEdit) {
});
}
const listeners = new AbortController();
// Snap into line and Line up use the card people see, not the
// transparent node around it (js/shared/outline.mjs).
node.ausbossOutlineElement = root.querySelector(".ausboss-callout-card,.ausboss-note-card") || root;
installTileDrag(node, root, listeners.signal, onEdit);
installTileResize(node, root, listeners.signal);
originalDescriptors.set(node, { descriptors, listeners });
} else {
previous.listeners.abort();
delete node.ausbossOutlineElement;
for (const [key, descriptor] of previous.descriptors) {
if (descriptor) Object.defineProperty(node, key, descriptor);
else delete node[key];
@@ -44,6 +48,9 @@ export function setTileFace(node, root, enabled, onEdit) {
function skipBadges() {}
// Sent from a tile's own drag after each move: js/snap_lines/ lines it up.
export const TILE_MOVE = "ausboss-tile-move";
// A normal node moves by its header. Give the tile that gesture while
// keeping a short click on a link or the info button as its usual action.
function installTileDrag(node, root, signal, onEdit) {
@@ -87,6 +94,9 @@ function installTileDrag(node, root, signal, onEdit) {
for (const start of press.starts) start.item.pos = [start.x + dx / zoom, start.y + dy / zoom];
node.setDirtyCanvas?.(true, true);
event.stopPropagation();
// The move stops here (Nodes 2.0 would pan the canvas with it), so tell
// Snap into line separately, after the tile has been placed.
root.dispatchEvent(new CustomEvent(TILE_MOVE, { bubbles: true, detail: event }));
}, capture);
const finish = (event) => {
if (event.pointerId !== press?.id) return;
+29 -1
View File
@@ -273,7 +273,14 @@ export function clipLengthPlan(info, values = {}) {
latestStart = clamp(Math.floor((end - lastTick - TRIM_EPSILON) * info.fps), 0, endFrame);
}
}
if (values.resampled) return { ...base, last: cap > 0 ? null : window.last, requested, latestStart };
if (values.resampled) {
// A known output rate places every output frame: the backend samples
// and holds on ticks at start + k / rate (decode_video_range), so the
// count, the last source frame shown and the end are all known here.
if (!(values.outputFps > 0) || !(info.fps > 0)) return { ...base, last: cap > 0 ? null : window.last, requested, latestStart };
const resampled = resampledFrames(info, values, nth, requested, snap);
return { ...base, ...resampled, requested, latestStart, truncated: requested != null && resampled.frames < requested };
}
const kept = keptFrames(window, nth, cap, snap);
return { ...base, last: kept.lastKept, frames: kept.frames, requested, latestStart, truncated: requested != null && kept.frames < requested };
};
@@ -288,6 +295,27 @@ export function clipLengthPlan(info, values = {}) {
return capped(mode === "length" ? stored : 0);
}
// Output frames of a run that resamples to a known rate: ticks at
// start + k / tickRate while before the end, thinned by every nth, capped,
// then snapped. `last` is the source frame the final tick holds.
export function resampledFrames(info, values, everyNth = 1, cap = null, snap = "free") {
const nth = Math.max(1, Math.floor(finite(everyNth, 1)) || 1);
const tickRate = finite(values.outputFps) * nth;
const duration = info.duration || info.count / info.fps;
const start = Math.max(0, finite(values.start));
const end = finite(values.end) > 0 ? Math.min(finite(values.end), duration) : duration;
const ticks = Math.max(0, Math.ceil((end - start) * tickRate - TRIM_EPSILON));
let frames = Math.ceil(ticks / nth);
if (cap != null && cap > 0) frames = Math.min(frames, cap);
frames = snapFrameCount(frames, snap);
const first = frameWindow(info, start, values.end).first;
const lastTime = start + Math.max(0, frames - 1) * nth / tickRate;
const last = clamp(Math.floor(lastTime * info.fps + TRIM_EPSILON), first, info.count - 1);
const windowLast = frameWindow(info, start, values.end).last;
// The last frame is held for one output frame, but never past the video.
return { first, last, windowLast, frames, endSeconds: Math.min(end, start + frames / finite(values.outputFps)) };
}
// Playback rate for a label, trimmed of float noise: 24 -> "24",
// 23.976023... -> "23.976".
export function formatFps(value) {
+40
View File
@@ -0,0 +1,40 @@
// Small pieces every timing card shares (the clip node, Load Video, Load
// Audio): the seconds | frames choice and the "linked" button that goes to
// the node feeding a value.
import { app } from "../../../scripts/app.js";
// Seconds or frames on a timing card: a per-browser choice, like a view
// setting. It never changes a stored value.
const UNITS_KEY = "AusBoss.ClipTiming.Units";
let unitsCache = null;
export function timingUnits(next) {
if (next === "s" || next === "f") {
unitsCache = next;
try { localStorage.setItem(UNITS_KEY, next); } catch { /* private window */ }
return next;
}
if (unitsCache) return unitsCache;
try { unitsCache = localStorage.getItem(UNITS_KEY) === "f" ? "f" : "s"; } catch { unitsCache = "s"; }
return unitsCache;
}
// The node feeding a linked input, by its title, with a way to go to it.
export function linkedNodeInfo(node, name) {
const slot = node.inputs?.find((input) => input?.name === name || input?.widget?.name === name);
if (slot?.link == null) return null;
const graph = node.graph;
const link = graph?.links?.get?.(slot.link) ?? graph?.links?.[slot.link] ?? graph?._links?.get?.(slot.link);
const source = graph?.getNodeById?.(link?.origin_id);
if (!source) return { title: "the subgraph's input", go: null };
const title = source.title || source.type || "another node";
return {
title,
go: () => {
try {
app.canvas?.selectNode?.(source);
app.canvas?.centerOnNode?.(source);
app.canvas?.setDirty?.(true, true);
} catch { /* an older canvas */ }
},
};
}
+16 -4
View File
@@ -1,5 +1,6 @@
import { api } from "../../../scripts/api.js";
import { app } from "../../../scripts/app.js";
import { linkedNodeInfo, timingUnits as clipUnits } from "./timing_links.mjs";
import { PANEL_LABELS } from "./panel_controls.mjs";
import { hideInputsInDef, hideWidget } from "./widget_visibility.mjs";
import { mountTransformTrim } from "./transform_trim.mjs";
@@ -103,7 +104,6 @@ const trimInputDriven = (node, name) => node.inputs?.some(
const RESIZE_METHODS = ["lanczos", "area", "bicubic", "bilinear", "nearest-exact"];
// The widest the control rows get on a big node; the picture takes the rest.
const CONTROL_MAX_WIDTH = 460;
const TRANSFORM_DEFAULTS = resetTransformValues(false);
const CORE_IMAGE_PREVIEW_WIDGET = "$$canvas-image-preview";
@@ -150,7 +150,7 @@ function installStyles() {
style.id = "ausboss-transform-styles";
style.textContent = `
.ausboss-transform-panel{display:flex;flex-direction:column;gap:8px;padding:8px;color:#ddd;font:12px system-ui;box-sizing:border-box;width:100%;height:100%;overflow:hidden}
.ausboss-transform-panel>:not(.ausboss-transform-preview){width:100%;max-width:${CONTROL_MAX_WIDTH}px;align-self:center;box-sizing:border-box}
.ausboss-transform-panel>:not(.ausboss-transform-preview){width:100%;align-self:stretch;box-sizing:border-box}
.ausboss-transform-preview{width:100%;flex:1 1 180px;min-height:0;border:1px solid #50555b;border-radius:8px;background:#111;display:block;touch-action:none}
.ausboss-transform-source{display:flex;flex-direction:column;gap:7px;flex:0 0 auto;padding:8px;border:1px solid rgba(0,184,174,.28);border-radius:8px;background:rgba(0,0,0,.24)}
.ausboss-transform-source-image{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center}
@@ -189,13 +189,14 @@ function installStyles() {
.ausboss-transform-group-meta{min-width:0;overflow:hidden;text-overflow:ellipsis}
.ausboss-transform-group-body{display:flex;flex-direction:column;gap:7px;padding:8px;box-sizing:border-box}
.ausboss-transform-group-body[hidden]{display:none}
.ausboss-transform-readout{flex:0 0 auto;margin-top:-3px;color:#c9d0d6;font:11px/14px system-ui;font-variant-numeric:tabular-nums;text-align:center;overflow:hidden;cursor:default;user-select:none}
.ausboss-transform-readout{flex:0 0 auto;margin:-5px 0 -3px;color:#c9d0d6;font:11px/14px system-ui;font-variant-numeric:tabular-nums;text-align:center;overflow:hidden;cursor:default;user-select:none}
.ausboss-transform-readout:empty{display:none}
.ausboss-transform-readout span{color:#8ca8a5}.ausboss-transform-readout b{color:#fff;font-weight:600}
.ausboss-transform-readout>div,.ausboss-transform-readout i{display:flex;align-items:center;justify-content:center;gap:3px;height:14px;white-space:nowrap}
.ausboss-transform-readout .ausboss-transform-ellipsis{min-width:0;overflow:hidden;text-overflow:ellipsis;color:inherit}
.ausboss-transform-readout b,.ausboss-transform-readout button{flex:none}
.ausboss-transform-readout i{color:#ffc46b;font-style:normal}
.ausboss-transform-readout i:empty{display:none}
.ausboss-transform-readout em{color:#8ca8a5;font-style:normal}
.ausboss-transform-readout em.note.ausboss-transform-ellipsis{color:#ffc46b}
.ausboss-transform-readout button{margin:0 0 0 6px;height:14px;padding:0 6px;border:1px solid #6b5a33;border-radius:3px;background:#2a2417;color:#ffd79a;font:600 9.5px/12px system-ui;cursor:pointer;vertical-align:top}
@@ -2320,6 +2321,11 @@ function buildTrim(state) {
onTogglePlayback: () => timelineCommand(state, "play"),
onSeek: (frame, settled) => scrubTo(state, frame, settled),
onCommit: notifyAusbossChange,
linkInfo: (name) => linkedNodeInfo(state.node, name),
// H3 Prompt Writer reads this to say what H3 makes of the clip.
publish: (timing) => { state.node.__ausbossClipTiming = timing; },
units: () => clipUnits(),
setUnits: (next) => { clipUnits(next); for (const view of state.trimViews) view.sync(); },
});
state.trimViews.add(control);
return control.root;
@@ -2340,6 +2346,7 @@ function setPlayhead(state, index) {
// also snaps the widgets to the decoded frame.
function scrubTo(state, index, settled) {
if (state.playing) stopPlayback(state, false);
state.pausedAt = null;
const frame = setPlayhead(state, index);
syncTimelineRange(state);
if (settled) { void seekFrame(state); return; }
@@ -2400,7 +2407,11 @@ function startPlayback(state) {
const trim = [...state.trimViews][0];
const { first, last } = trim.window();
const head = clampFrame(value(state.node, "frame_index", 0), info);
let next = head < first || head >= last ? first : head + 1;
// Play shows the clip from its start, so what plays is what the run
// keeps; only a resume right after a pause inside the clip carries on.
const resume = state.pausedAt != null && state.pausedAt === head && head >= first && head < last;
let next = resume ? head + 1 : first;
state.pausedAt = null;
state.playing = true;
syncTimelineRange(state);
const session = ++state.playbackSession;
@@ -2421,6 +2432,7 @@ function startPlayback(state) {
function stopPlayback(state, settle = true) {
const wasPlaying = Boolean(state.playing);
state.playing = false;
if (wasPlaying) state.pausedAt = clampFrame(value(state.node, "frame_index", 0), clipInfo(state.metadata));
state.playbackSession = (state.playbackSession || 0) + 1; // orphan in-flight ticks
if (state.playbackTimer) clearTimeout(state.playbackTimer);
state.playbackTimer = null;
+389 -169
View File
@@ -41,7 +41,7 @@ import {
windowSeconds,
} from "./timeline_math.mjs";
const CSS_ID = "ausboss-transform-trim-css-v4";
const CSS_ID = "ausboss-transform-trim-css-v5";
const HANDLE_HIT_PX = 9;
// Connected inputs that set the length themselves, in the backend's order of
// precedence: fixed_frames replaces the window, a cap replaces the Length.
@@ -101,6 +101,25 @@ function installCss() {
.ausboss-transform-trim-reset{flex:none;height:18px;box-sizing:border-box;border:1px solid #2c4d4b;border-radius:4px;background:#1b2627;color:#cadddb;font:600 10px/16px system-ui;cursor:pointer;padding:0 8px;white-space:nowrap}
.ausboss-transform-trim-reset:hover{border-color:#8fa3a1;color:#fff}
.ausboss-transform-trim-reset:disabled{opacity:.45;cursor:not-allowed}
.ausboss-transform-trim-span.is-room{background:repeating-linear-gradient(90deg,rgba(0,180,170,.38) 0 6px,rgba(0,180,170,.1) 6px 12px)}
.ausboss-transform-trim-line .ausboss-transform-trim-readout{text-align:left}
.ausboss-transform-trim-inside{color:#45d6cb}
.ausboss-transform-trim-outside{color:#8ca8a5}
.ausboss-transform-trim-clip{flex:1 1 0;min-width:0;color:#45d6cb;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
.ausboss-transform-trim-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;min-width:0}
.ausboss-transform-trim-field{display:flex;flex-direction:column;gap:3px;min-width:0}
.ausboss-transform-trim-field .ausboss-scrub{width:100%;box-sizing:border-box}
.ausboss-transform-trim-field-label{color:#cadddb;display:flex;align-items:center;gap:6px;min-width:0}
.ausboss-transform-trim-go[hidden]{display:none}
.ausboss-transform-trim-sub{color:#8ca8a5;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums;min-height:12px}
.ausboss-transform-trim-link{color:#9fe3dc;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ausboss-transform-trim-link[hidden]{display:none}
.ausboss-transform-trim-go{border:0;background:transparent;padding:0;color:#45d6cb;font:600 10px system-ui;text-decoration:underline;cursor:pointer}
.ausboss-transform-trim-note{display:flex;align-items:center;gap:6px;flex-wrap:wrap;color:#9fe3dc;font-size:11px;line-height:1.35}
.ausboss-transform-trim-note[hidden]{display:none}
.ausboss-transform-trim-note>span{flex:1 1 180px;min-width:0}
.ausboss-transform-trim-note.warn{background:#3a2a10;box-shadow:inset 3px 0 0 #e0a040;border-radius:6px;padding:6px 8px;color:#ffdca8}
.ausboss-transform-trim-note button[hidden]{display:none}
`;
document.head.append(style);
}
@@ -113,6 +132,8 @@ function el(tag, className = "", text = "") {
}
const pct = (fraction) => `${(fraction * 100).toFixed(3)}%`;
// Seconds for people: at most two decimals (1, 1.5, 2.17).
const secondsText = (value) => String(Number((Number(value) || 0).toFixed(2)));
// options:
// get(name, fallback) / set(name, value) widget access
@@ -126,7 +147,12 @@ const pct = (fraction) => `${(fraction * 100).toFixed(3)}%`;
// (the clip node) or playhead only
// onSeek(frame, settled) the playhead moved; settled on release
// onCommit() a stored value settled (undo point)
export function mountTransformTrim({ get, set, has = () => true, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate, metadata, trim = true, isPlaying, onTogglePlayback, onSeek, onCommit }) {
// linkInfo(name) {title, go()} of the node feeding
// a linked input, or null
// publish(timing) the clip's {frames, startSeconds,
// endSeconds, roomFrames}, or null
// units() / setUnits(units) "s" (seconds) or "f" (frames)
export function mountTransformTrim({ get, set, has = () => true, driven = () => false, number = (name, fallback) => get(name, fallback), outputRate, metadata, trim = true, isPlaying, onTogglePlayback, onSeek, onCommit, linkInfo = () => null, publish, units: getUnits = () => "s", setUnits = () => {}, play: showPlay = true }) {
installCss();
const root = el("div", "ausboss-transform-trim");
const rail = el("div", "ausboss-transform-trim-rail");
@@ -144,7 +170,9 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const play = el("button", "ausboss-transform-trim-play");
play.type = "button";
play.addEventListener("click", onTogglePlayback);
transport.append(play, rail);
// A host with its own player (Load Video) leaves out the Play button.
if (showPlay) transport.append(play);
transport.append(rail);
const info = () => clipInfo(metadata());
const everyNth = () => Math.max(1, Math.trunc(Number(number("every_nth", get("every_nth", 1))) || 1));
const snapRule = () => String(get("frame_snap", "free"));
@@ -160,11 +188,10 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
return number(name, get(name, 0)) ?? get(name, 0);
};
const countAtRunTime = () => COUNT_INPUTS.some((name) => driven(name) && number(name, null) == null);
const plan = () => {
if (!trim) return null;
const clip = info();
const outFps = () => (outputRate ? outputRate() : info().fps / everyNth());
const planValues = () => {
const wired = wiredBy();
return clipLengthPlan(clip, {
return {
start: boundSeconds("start"),
end: boundSeconds("end"),
everyNth: everyNth(),
@@ -173,9 +200,48 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
fixedFrames: driven("fixed_frames") ? 0 : get("fixed_frames", 0),
wired,
wiredFrames: wired ? number(wired, null) : null,
outputFps: outputRate ? outputRate() : clip.fps,
outputFps: outputRate ? outputRate() : info().fps,
resampled: driven("force_rate"),
});
};
};
const plan = () => (trim ? clipLengthPlan(info(), planValues()) : null);
// Output frames that fit between IN and the end of the video: the most a
// Duration can be from here.
const roomFrames = () => {
if (!trim) return null;
const room = clipLengthPlan(info(), { ...planValues(), maxFrames: 0, fixedFrames: 0, wired: null, wiredFrames: null });
return room.frames ?? null;
};
// Where the clip ends, in source seconds (exclusive), when it is known.
const endSecondsOf = (current) => {
const clip = info();
if (current?.endSeconds != null) return current.endSeconds;
if (current?.last == null || !clip.fps) return null;
return (current.last + 1) / clip.fps;
};
const endDriven = () => driven("end_frame") || driven("end_seconds");
// The latest IN that keeps the whole Duration. With a connected rate the
// count is in output frames, so the source grid would stop IN far too soon
// (the 2.25 face stopped a 240-frame Length at IN 7 on a 247-frame clip).
const latestIn = (current) => {
const clip = info();
if (driven("force_rate")) {
if (current.latestStart == null) return clip.count - 1;
return current.latestStart > 0 ? current.latestStart : clip.count - 1;
}
return latestInFor(clip, current.requested ?? get("max_frames", 1), everyNth());
};
// A Duration as long as the whole video only caps it: IN moves freely and
// the clip runs to the end.
const durationFills = (current) => {
if (current.mode !== "length" || current.requested == null) return false;
const whole = roomFromStart();
return whole != null && current.requested >= whole;
};
const roomFromStart = () => {
if (!trim) return null;
const room = clipLengthPlan(info(), { ...planValues(), start: 0, maxFrames: 0, fixedFrames: 0, wired: null, wiredFrames: null });
return room.frames ?? null;
};
const currentWindow = () => {
const clip = info();
@@ -185,7 +251,8 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
};
const playheadFrame = () => clampFrame(get("frame_index", 0), info());
const controls = {};
let syncLength = () => {};
// A short line under the fields after a drag stops at the video's end.
let stopNote = "";
// IN is locked by a connected bound; OUT by a connected bound in free
// trim, and always when a connected input sets the length.
const locked = (edge) => {
@@ -196,10 +263,10 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
return false;
};
const lockTip = (edge) => edge === "start"
? "The starting frame is supplied by a connected input. Disconnect it to edit IN here."
? "The starting frame is supplied by a connected input. Disconnect it to set Start here."
: wiredBy()
? `The connected ${wiredBy()} input sets the length, so the clip ends where it says. Disconnect it to use OUT or Length.`
: "The ending frame is supplied by a connected input. Disconnect it to edit OUT here.";
? `The connected ${wiredBy()} input sets the length, so the clip ends where it says. Disconnect it to set Duration or Ends at here.`
: "The ending frame is supplied by a connected input. Disconnect it to set Ends at here.";
const disableControl = (control, disabled, tip) => {
if (!control) return;
control.root.style.opacity = disabled ? ".45" : "";
@@ -217,7 +284,16 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const writeEnd = (first, last) => set("end_seconds", windowSeconds(info(), first, last).end_seconds);
// An older face's Fixed frames reads as a Length; the first edit makes it
// one, keeping the window where the fixed count had placed it.
// The face has no modes: a clip is a Start and a Duration. A window saved
// as IN -> OUT (Length off) becomes a Duration of the same frames on its
// first edit, so the run outputs exactly what it did. A connected end
// keeps the window as it is.
const adoptLength = (current) => {
if (current.mode === "free" && !endDriven() && current.frames != null) {
set("max_frames", Math.max(1, current.frames));
set("end_seconds", 0);
return plan();
}
if (current.mode !== "fixed") return current;
set("fixed_frames", 0);
set("max_frames", Math.max(1, current.requested ?? current.frames ?? 1));
@@ -235,9 +311,14 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
let parked;
if (edge === "start") {
if (current.mode === "length") {
// A Length drags the whole window, stopping where OUT meets the end;
// a Length past the clip's end only caps it, so IN moves freely.
parked = Math.max(0, Math.min(clampFrame(frame, clip), latestInFor(clip, current.requested ?? get("max_frames", 1), nth)));
// A Duration drags the whole clip, stopping where its end meets the
// video's end; a Duration past the video's end only caps it, so IN
// moves freely.
const latest = latestIn(current);
parked = Math.max(0, Math.min(clampFrame(frame, clip), latest));
stopNote = clampFrame(frame, clip) > latest
? `Start stops at ${secondsText(parked / clip.fps)} s so all ${current.requested} frames fit.`
: "";
set("end_seconds", 0);
} else if (current.mode === "wired" && current.latestStart != null && !countAtRunTime()) {
parked = Math.min(clampFrame(frame, clip), current.latestStart);
@@ -247,11 +328,18 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
writeStart(parked);
} else {
const target = Math.max(current.first, clampFrame(frame, clip));
const frames = framesThrough(current.first, target, nth, snapRule());
stopNote = "";
let frames = framesThrough(current.first, target, nth, snapRule());
if (driven("force_rate") && outFps() > 0) {
// Output frames at the linked rate from IN to the handle's boundary.
frames = snapToValid(Math.max(1, Math.round(((target + 1) / clip.fps - boundSeconds("start")) * outFps())), snapRule());
const room = roomFrames();
if (room != null) frames = Math.min(frames, Math.max(1, room));
}
if (current.mode === "length") {
set("max_frames", frames);
set("end_seconds", 0);
parked = Math.min(clip.count - 1, lastFrameFor(current.first, frames, nth));
parked = plan()?.last ?? Math.min(clip.count - 1, lastFrameFor(current.first, frames, nth));
} else {
parked = driven("force_rate") ? target : lastFrameFor(current.first, frames, nth);
writeEnd(current.first, parked);
@@ -263,7 +351,8 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
// The grip slides the kept part: a Length moves with IN (OUT follows), a
// free window keeps its span and both edges move.
const canSlide = () => {
if (!trim || locked("start")) return false;
// With a connected rate, IN itself slides the clip at its Duration.
if (!trim || locked("start") || driven("force_rate")) return false;
const current = plan();
if (!current || !["length", "fixed", "free"].includes(current.mode)) return false;
if (current.mode === "free" && locked("end")) return false;
@@ -285,26 +374,6 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
}
moveEdge("start", first, settled);
};
// Length on keeps what the rail shows now as the count; off turns the
// Length into an OUT at the same frame. Either way nothing moves.
const setLength = (on) => {
const current = plan();
if (!current || current.mode === "wired" || (on === (current.mode !== "free"))) return;
if (on) {
const frames = current.frames ?? framesThrough(current.first, current.windowLast, everyNth(), snapRule());
set("max_frames", Math.max(1, frames));
set("end_seconds", 0);
} else {
const last = current.last ?? current.windowLast;
writeStart(current.first);
writeEnd(current.first, last);
set("max_frames", 0);
if (!driven("fixed_frames")) set("fixed_frames", 0);
}
sync();
onCommit?.();
};
const readout = el("span", "ausboss-transform-trim-readout");
const summary = el("div", "ausboss-transform-trim-summary");
@@ -312,7 +381,7 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
const clip = info();
const playing = isPlaying();
play.setAttribute("aria-label", playing ? "Pause" : "Play");
play.title = playing ? "Pause on this frame" : trim ? "Play the selected clip" : "Play the video to pick a frame";
play.title = playing ? "Pause on this frame" : trim ? "Play the clip from its start" : "Play the video to pick a frame";
play.classList.toggle("is-playing", playing);
play.disabled = !clip.count;
const head = playheadFrame();
@@ -320,33 +389,41 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
playhead.style.left = pct(fractionOfFrame(head, clip, "center"));
playhead.style.visibility = clip.count ? "" : "hidden";
readout.replaceChildren();
const current = trim ? plan() : null;
if (clip.count) {
readout.append(el("b", "", `fr ${head}`), document.createTextNode(` · ${formatTimecode(frameTime(head, clip))}`));
readout.title = `Playhead: frame ${head} of ${clip.count} at ${frameTime(head, clip).toFixed(3)} s. Press or drag the rail to scrub; ${trim ? "the trim handles carry it with them." : "this is the frame the node outputs."}`;
readout.append(document.createTextNode("Preview "), el("b", "", `${secondsText(frameTime(head, clip))} s`), document.createTextNode(` · src fr ${head}`));
if (trim) {
const end = countAtRunTime() ? null : current.last;
const inside = head >= current.first && (end == null || head <= end);
readout.append(el("span", inside ? "ausboss-transform-trim-inside" : "ausboss-transform-trim-outside", inside ? " · in the clip" : " · outside the clip"));
}
readout.title = `The picture shows frame ${head} of ${clip.count}, ${frameTime(head, clip).toFixed(2)} seconds into the video. Press or drag the bar to look at another frame${trim ? "; Use as start starts the clip here." : "; this is the frame the node outputs."}`;
}
controls.frame?.set(head);
if (!trim) return;
const current = plan();
const wired = wiredBy();
const unknown = countAtRunTime();
const hasOut = current.last != null && current.mode !== "wired";
const hasOut = current.last != null && current.mode !== "wired" && !unknown;
const outFrame = current.last ?? current.windowLast;
const startFraction = fractionOfFrame(current.first, clip, "start");
const endFraction = fractionOfFrame(outFrame, clip, "end");
const endSec = endSecondsOf(current);
const endFraction = endSec != null && !unknown
? Math.max(startFraction, Math.min(1, endSec * clip.fps / clip.count))
: fractionOfFrame(outFrame, clip, "end");
// Dim: frames the free window holds but the run drops (every nth, snap).
const tailFraction = current.mode === "free" ? fractionOfFrame(current.windowLast, clip, "end") : endFraction;
span.style.left = pct(startFraction);
span.style.width = pct(current.last == null && current.mode !== "free" ? 0 : Math.max(0, tailFraction - startFraction));
span.classList.toggle("is-room", unknown || current.last == null);
// A length only the run knows: the dim part is the room the clip has.
span.style.width = pct(unknown || current.last == null ? 1 - startFraction : Math.max(0, tailFraction - startFraction));
kept.style.left = pct(startFraction);
kept.style.width = current.last == null || unknown ? "0%" : pct(Math.max(0, endFraction - startFraction));
const fills = lengthFillsClip(clip, current, everyNth());
span.title = unknown || current.last == null ? "Room for the clip: its length is set when the graph runs." : "";
const railWidth = rail.getBoundingClientRect().width || 0;
const keptWidth = Math.max(0, endFraction - startFraction) * railWidth;
grip.hidden = !canSlide() || unknown || (railWidth > 0 && keptWidth < 34);
grip.style.left = pct((startFraction + endFraction) / 2);
grip.title = current.mode === "free"
? "Drag to slide the kept part: IN and OUT move together."
: "Drag to slide the clip: OUT follows at the Length.";
grip.title = "Drag to slide the clip; its Duration stays.";
for (const edge of ["start", "end"]) {
const handle = handles[edge];
const frame = edge === "start" ? current.first : outFrame;
@@ -359,10 +436,9 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
handle.style.cursor = isLocked ? "not-allowed" : "";
handle.title = isLocked ? lockTip(edge)
: edge === "start"
? current.mode === "free" ? "Drag IN to trim; Shift + arrow moves one frame."
: fills ? "Drag IN to start later. The Length is as long as the clip, so the clip's end is OUT."
: "Drag IN to move the clip; OUT follows at the Length. Shift + arrow moves one frame."
: current.mode === "free" ? "Drag OUT to trim; it lands on the last frame the run keeps." : "Drag OUT to change the Length; IN stays.";
? durationFills(current) ? "Drag to start later. The Duration is longer than the video, so the clip runs to its end."
: "Drag to move the clip; its Duration stays. Shift + arrow moves one frame."
: "Drag to change the Duration; the start stays.";
handle.setAttribute("aria-valuemin", "0");
const maxFrame = edge === "start" && current.mode === "wired" && !unknown
? current.latestStart ?? current.windowLast : Math.max(0, clip.count - 1);
@@ -370,16 +446,16 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
handle.setAttribute("aria-valuenow", String(frame));
handle.setAttribute("aria-valuetext", `frame ${frame}, ${formatTimecode(frameTime(frame, clip))}`);
}
controls.start_seconds?.set(current.first);
controls.end_seconds?.set(outFrame);
disableControl(controls.start_seconds, locked("start"), lockTip("start"));
disableControl(controls.end_seconds, locked("end") || !hasOut, lockTip("end"));
syncLength(current, wired);
if (useStart) {
useStart.disabled = !clip.count || locked("start");
useStart.title = locked("start") ? lockTip("start") : "Start the clip at the frame on the stage. The Duration stays.";
}
if (clip.count) syncFields(clip, current, wired, unknown);
if (controls.reset) {
const free = current.mode === "free";
controls.reset.textContent = free ? "Full clip" : "To start";
controls.reset.title = free ? "Reset IN/OUT to the full source. Keeps Every nth and Frames for." : "Move IN to the start of the source; the length stays.";
controls.reset.disabled = !free && locked("start");
const free = current.mode !== "wired";
controls.reset.textContent = free ? "Whole video" : "To start";
controls.reset.title = free ? `Use the whole video: start at 0 with no Duration limit. Keeps Every nth${has("frame_snap") ? " and Frames for" : ""}.` : "Move the start to the beginning of the video; the linked length stays.";
controls.reset.disabled = locked("start") && !free;
}
controls.every_nth?.set(get("every_nth", 1));
disableControl(controls.every_nth, driven("every_nth"), "Every nth is supplied by a connected input.");
@@ -387,50 +463,21 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
controls.frame_snap.value = snapRule();
const exact = current.mode === "fixed" || (current.mode === "wired" && wired === "fixed_frames");
controls.frame_snap.disabled = exact || driven("frame_snap");
controls.frame_snap.title = exact ? "An exact fixed_frames count is used as it is; this does not apply." : "Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. OUT and Length step to those counts. Any keeps every frame.";
controls.frame_snap.title = exact ? "An exact fixed_frames count is used as it is; this does not apply." : "Keep a frame count the video model takes: LTX wants 8n+1 (49, 97, 121), Wan 4n+1. The Duration steps to those counts. Any keeps every frame.";
}
syncSummary(clip, current, wired, unknown);
syncSummary(clip);
};
const syncSummary = (clip, current, wired, unknown) => {
const syncSummary = (clip) => {
if (!clip.count) {
summary.textContent = "Choose a source to set the clip window";
summary.textContent = "Choose a source to set the clip";
summary.title = "";
return;
}
const rate = outputRate?.();
const fps = `Source ${formatFps(clip.fps)} fps → Output ${rate == null ? "rate at run time" : `${formatFps(rate)} fps`}`;
if (current.mode === "wired") {
summary.textContent = current.frames == null ? `${fps} · length from ${wired} at run time` : `${fps} · ${current.frames} frames from ${wired}`;
summary.title = `The connected ${wired} input sets the length, so only IN is set here. Disconnect it to use OUT or a Length.`;
return;
}
if (unknown || current.frames == null) {
summary.textContent = `${fps} · frame count at run time`;
summary.title = "IN, OUT and the playhead refer to source frames. A connected input decides the exact frame count when the workflow runs. Connect the fps output to the next video node's fps input.";
return;
}
const from = formatTimecode(frameTime(current.first, clip));
const to = formatTimecode((current.last + 1) / clip.fps);
if (current.mode === "fixed") {
summary.textContent = current.tooLong
? `Fixed length needs more than the source's ${clip.duration.toFixed(3)}s`
: `${fps} · exactly ${current.frames} frames · ${from} → ${to}`;
summary.title = "An older Fixed frames value: an exact count from IN. Any change here turns it into a Length.";
return;
}
const total = current.windowLast - current.first + 1;
const count = current.mode === "length"
? current.truncated ? `${current.frames} of ${current.requested} frames, source ends` : `${current.frames} frames`
: current.frames < total ? `${current.frames} of ${total} frames` : `${current.frames} frames`;
summary.textContent = `${fps} · ${count} · ${from} → ${to}`;
summary.title = current.mode === "length"
? current.truncated
? `The source ends ${current.frames} frames after IN, before the Length of ${current.requested}. Move IN earlier or shorten the Length.`
: "Length keeps OUT this many output frames after IN; drag IN to move the clip, OUT to change the Length."
: current.frames < total
? `The window holds ${total} frames; every nth and the snap rule keep ${current.frames}, ending at frame ${current.last}, where OUT sits. The dim part is dropped.`
: "Frames the run outputs, at the fps the node reports.";
summary.textContent = `Source ${formatFps(clip.fps)} fps · ${clip.count} frames · ends at ${secondsText(clip.duration || clip.count / clip.fps)} s · clip out at ${rate == null ? "the rate set at run time" : `${formatFps(rate)} fps`}`;
summary.title = "Start and Ends at are places in the source video. Duration counts the frames the clip sends on, at the output rate.";
if (trim) rail.title = [clipLine?.textContent, summary.textContent, readout.textContent].filter(Boolean).join("\n");
};
// --- rail gestures --------------------------------------------------------
@@ -532,21 +579,19 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
}
// --- rows -----------------------------------------------------------------
const timeRow = el("div", "ausboss-transform-trim-line");
// The clip node: Preview (the playhead, and Use as start), the clip in
// words with a Seconds | Frames switch, then Start, Duration and Ends at.
// Start and Ends at are positions in the source video; Duration counts the
// frames the clip sends on, at the output rate. No modes: dragging IN
// slides the clip, dragging OUT or typing a Duration or an end changes the
// Duration.
const previewRow = el("div", "ausboss-transform-trim-line");
let useStart = null;
if (trim) {
for (const [name, caption, edge] of [["start_seconds", "IN", "start"], ["end_seconds", "OUT", "end"]]) {
const label = el("label");
label.append(el("span", "ausboss-transform-trim-caption", caption));
controls[name] = makeScrubInput({
value: 0, min: 0, max: 10000000, step: 1, decimals: 0,
title: edge === "start" ? "IN frame: the first frame the run keeps (stored as start_seconds)." : "OUT frame: the last frame the run keeps. With Length on it follows IN; typing it changes the Length.",
onChange: (frame) => moveEdge(edge, frame, false),
onSettle: () => { const window = currentWindow(); seek(edge === "start" ? window.first : window.last, true); onCommit?.(); },
});
label.append(controls[name].root);
timeRow.append(label);
if (edge === "start") timeRow.append(readout);
}
useStart = el("button", "ausboss-transform-trim-reset", "Use as start");
useStart.type = "button";
useStart.title = "Start the clip at the frame on the stage. The Duration stays.";
useStart.addEventListener("click", () => moveEdge("start", playheadFrame(), true));
} else {
const label = el("label");
label.append(el("span", "ausboss-transform-trim-caption", "FRAME"));
@@ -557,67 +602,237 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
onSettle: () => seek(playheadFrame(), true),
});
label.append(controls.frame.root);
timeRow.append(label, readout);
previewRow.append(label, readout);
}
root.append(transport, timeRow);
root.append(transport);
if (!trim) root.append(previewRow);
// Length: off, OUT ends the clip; on, a frame count from IN (max_frames,
// end left open), so OUT follows IN and the count survives a new source.
if (trim && has("max_frames")) {
const lengthRow = el("div", "ausboss-transform-trim-line wrap");
const label = el("label", "", "Length");
const pill = el("div", "ausboss-transform-trim-pill");
const off = el("button", "", "off");
const on = el("button", "", "on");
off.type = on.type = "button";
off.title = "OUT ends the clip: drag both handles freely.";
on.title = "Set the clip by a frame count from IN: OUT follows IN, and the count stays when you swap the video.";
off.addEventListener("click", () => setLength(false));
on.addEventListener("click", () => setLength(true));
pill.append(off, on);
const hint = el("span", "ausboss-transform-trim-hint");
const count = makeScrubInput({ value: 1, min: 1, max: 100000, step: 1, decimals: 0, unit: "fr", width: 72,
title: "Output frames from IN. Under a snap rule it steps to the counts the model keeps (97, 105, ... for 8n+1).",
onChange: (next) => {
const current = adoptLength(plan());
if (current.mode !== "length") { sync(); return; }
const was = current.requested ?? get("max_frames", 1);
set("max_frames", snapToValid(next, snapRule(), Math.sign(next - was)));
set("end_seconds", 0);
sync();
},
onSettle: () => { const window = currentWindow(); seek(window.last, true); onCommit?.(); },
});
label.append(pill, count.root);
lengthRow.append(label, hint);
root.append(lengthRow);
syncLength = (current, wired) => {
const active = current.mode !== "free";
const blocked = current.mode === "wired";
off.classList.toggle("on", !active);
on.classList.toggle("on", active);
off.setAttribute("aria-pressed", String(!active));
on.setAttribute("aria-pressed", String(active));
pill.classList.toggle("is-disabled", blocked);
off.disabled = on.disabled = blocked;
pill.title = blocked ? lockTip("end") : "";
count.root.style.display = active ? "" : "none";
const step = snapStep(snapRule());
count.setStep(step, step);
count.set(blocked ? (current.requested ?? current.frames ?? 0) : (current.requested ?? get("max_frames", 1)));
disableControl(count, blocked, lockTip("end"));
const fills = lengthFillsClip(info(), current, everyNth());
hint.textContent = blocked ? `from ${wired}` : current.mode === "fixed" ? "exact (older setting)" : fills ? "= the whole clip" : active ? "" : "OUT ends the clip";
hint.classList.toggle("note", fills && !blocked);
hint.title = fills && !blocked ? `The Length (${current.requested ?? current.frames} frames) is as long as the clip, so the clip's end is OUT. Drag IN to start later; drag OUT or type a smaller Length to end sooner.` : "";
const fields = {};
let clipLine = null;
let unitPill = null;
let noteRow = null;
let noteText = null;
const noteButtons = [];
if (trim) {
const clipRow = el("div", "ausboss-transform-trim-line");
clipLine = el("span", "ausboss-transform-trim-clip");
unitPill = el("div", "ausboss-transform-trim-pill");
for (const [key, words, tip] of [["s", "s", "Show times in seconds."], ["f", "fr", "Show times in frames: source frames for Start and Ends at, clip frames for Duration."]]) {
const button = el("button", "", words);
button.type = "button";
button.dataset.units = key;
button.title = tip;
button.addEventListener("click", () => { setUnits(key); sync(); });
unitPill.append(button);
}
const grid = el("div", "ausboss-transform-trim-fields");
const toFrames = {
start: (value) => (getUnits() === "f" ? Math.round(value) : Math.round(value * info().fps)),
};
// Output frames for a Duration typed in the current units.
const durationFrames = (value) => {
if (getUnits() === "f") return Math.round(value);
const rate = outFps();
return rate > 0 ? Math.round(value * rate) : null;
};
// Output frames from IN to an end typed in the current units.
const framesToEnd = (value) => {
const clip = info();
const current = plan();
const end = getUnits() === "f" ? (Math.round(value) + 1) / clip.fps : value;
if (driven("force_rate")) {
const rate = outFps();
return rate > 0 ? Math.round((end - boundSeconds("start")) * rate) : null;
}
return framesThrough(current.first, Math.ceil(end * clip.fps - 1e-7) - 1, everyNth(), snapRule());
};
const setDuration = (frames) => {
if (frames == null || !Number.isFinite(frames)) return;
const current = adoptLength(plan());
if (current.mode !== "length") return;
const was = current.requested ?? get("max_frames", 1);
set("max_frames", snapToValid(Math.max(1, frames), snapRule(), Math.sign(frames - was)));
set("end_seconds", 0);
stopNote = "";
};
const defs = [
["start", "Start", "Where the clip starts in the source video."],
["duration", "Duration", "How long the clip is. Counted in clip frames at the output rate."],
["end", "Ends at", "Where the clip ends in the source video. Typing it changes the Duration."],
];
for (const [key, caption, tip] of defs) {
const cell = el("div", "ausboss-transform-trim-field");
const label = el("span", "ausboss-transform-trim-field-label", caption);
const go = el("button", "ausboss-transform-trim-go", "linked");
go.type = "button";
label.append(go);
const control = makeScrubInput({
value: 0, min: 0, max: 10000000, step: 1, decimals: 2, minDecimals: 0, unit: "s", unitWidth: 34,
title: tip,
onChange: (value) => {
if (key === "start") {
if (locked("start")) return;
// A typed start is kept even when the Duration no longer fits;
// the note below says what fits and offers both fixes.
adoptLength(plan());
const frame = clampFrame(toFrames.start(value), info());
writeStart(frame);
stopNote = "";
seek(frame, false);
return;
}
if (key === "duration") setDuration(durationFrames(value));
else setDuration(framesToEnd(value));
sync();
},
onSettle: () => { const window = currentWindow(); seek(key === "start" ? window.first : window.last, true); onCommit?.(); },
});
cell.append(label, control.root);
grid.append(cell);
fields[key] = { control, go, cell, label };
}
noteRow = el("div", "ausboss-transform-trim-note");
noteText = el("span");
noteRow.append(noteText);
for (let index = 0; index < 2; index++) {
const button = el("button", "ausboss-transform-trim-reset");
button.type = "button";
noteButtons.push(button);
noteRow.append(button);
}
root.append(grid, noteRow);
}
// One field's look: its value in the current units, the line under it,
// and, when another node sets it, that node's name and a Go to button.
const showField = (key, { value, unit, decimals, sub, lockedBy, readOnly, placeholder = "" }) => {
const field = fields[key];
if (!field) return;
field.control.setRange({ decimals, minDecimals: 0, step: decimals ? 0.1 : 1, fineStep: decimals ? 0.01 : 1 });
field.control.set(value);
if (value == null) field.control.input.value = "";
field.control.input.placeholder = placeholder;
const unitSlot = field.control.root.querySelector(".ausboss-scrub-unit");
if (unitSlot) unitSlot.textContent = unit;
const tip = lockedBy ? `Set by ${lockedBy.title}: ${sub}. Click "linked" to go to that node.` : sub;
disableControl(field.control, readOnly, tip);
field.cell.title = tip;
field.go.hidden = !lockedBy;
if (lockedBy) {
field.go.title = `Set by ${lockedBy.title}. Click to go to that node.`;
field.go.onclick = () => lockedBy.go?.();
}
};
const showNote = (text, kind = "", actions = []) => {
if (!noteRow) return;
noteRow.hidden = !text;
noteRow.classList.toggle("warn", kind === "warn");
noteText.textContent = text;
noteButtons.forEach((button, index) => {
const action = actions[index];
button.hidden = !action;
if (action) { button.textContent = action.label; button.onclick = () => { action.run(); sync(); onCommit?.(); }; }
});
};
const syncFields = (clip, current, wired, unknown) => {
const seconds = getUnits() !== "f";
for (const button of unitPill.children) button.classList.toggle("on", button.dataset.units === (seconds ? "s" : "f"));
const rate = outFps();
const rateText = rate > 0 ? `${formatFps(rate)} fps` : "the output rate";
const first = current.first;
const endSec = unknown ? null : endSecondsOf(current);
const frames = unknown ? null : current.frames;
const startLink = locked("start") ? linkInfo(driven("start_frame") ? "start_frame" : "start_seconds") : null;
const lengthLink = current.mode === "wired" && wired ? linkInfo(wired) : null;
const endLink = endDriven() && current.mode === "free" ? linkInfo(driven("end_frame") ? "end_frame" : "end_seconds") : null;
const room = roomFrames();
const fills = durationFills(current);
showField("start", {
value: seconds ? frameTime(first, clip) : first,
unit: seconds ? "s" : "fr", decimals: seconds ? 2 : 0,
sub: seconds ? `source frame ${first}` : `source frame · ${secondsText(frameTime(first, clip))} s`,
lockedBy: startLink, readOnly: locked("start"),
});
// Duration: what was asked for (a Duration longer than what is left
// only caps the clip), in clip frames or seconds at the output rate.
const asked = current.mode === "wired" ? current.requested ?? current.frames : current.mode === "length" ? current.requested : frames;
let durationSub;
if (current.mode === "wired" && current.frames == null && current.requested == null) {
durationSub = room != null && rate > 0 ? `up to ${secondsText(room / rate)} s (${room} frames) fit after this start` : "set when the graph runs";
} else if (current.mode === "wired" && wired !== "fixed_frames" && current.truncated) {
durationSub = `the video ends first: ${frames} frames${rate > 0 ? ` (${secondsText(frames / rate)} s)` : ""}`;
} else if (current.mode === "wired") {
durationSub = wired === "fixed_frames" ? `${asked} clip frames required` : `up to ${asked} clip frames`;
} else if (frames == null) {
durationSub = "frame count at run time";
} else if (current.truncated) {
durationSub = `the video ends first: ${frames} frames${rate > 0 ? ` (${secondsText(frames / rate)} s)` : ""}`;
} else {
durationSub = seconds ? `${frames} clip frames at ${rateText}` : rate > 0 ? `clip frames · ${secondsText(frames / rate)} s at ${rateText}` : "seconds known at run time";
}
const durationInSeconds = seconds && rate > 0;
showField("duration", {
value: asked == null ? null : durationInSeconds ? asked / rate : asked,
unit: durationInSeconds ? "s" : "fr", decimals: durationInSeconds ? 2 : 0,
sub: durationSub, lockedBy: lengthLink,
readOnly: current.mode === "wired" || Boolean(endLink) || asked == null,
placeholder: current.mode === "wired" && asked == null ? "at run time" : "",
});
const lastSource = endSec == null ? null : Math.min(clip.count - 1, Math.max(first, Math.ceil(endSec * clip.fps - 1e-7) - 1));
showField("end", {
value: endSec == null ? null : seconds ? endSec : lastSource,
unit: seconds ? "s" : "fr", decimals: seconds ? 2 : 0,
sub: endSec == null ? "known after the run" : seconds ? `last source frame ${lastSource}` : `last source frame · ${secondsText(endSec)} s`,
lockedBy: endLink, readOnly: current.mode === "wired" || Boolean(endLink) || endSec == null,
placeholder: endSec == null ? "after Run" : "",
});
// The clip in words.
if (endSec == null) {
clipLine.textContent = `Clip from ${seconds ? `${secondsText(frameTime(first, clip))} s` : `src fr ${first}`} · length set when the graph runs`;
} else {
const span = seconds
? `Clip ${secondsText(frameTime(first, clip))} → ${secondsText(endSec)} s`
: `Clip src fr ${first} → ${lastSource}`;
clipLine.textContent = `${span} · ${frames} frames out`;
}
// What needs saying: a start that leaves too little video, a linked
// exact count that does not fit, or a drag that stopped at the end.
const latest = current.mode === "length" ? latestIn(current) : current.latestStart;
if (current.mode === "wired" && wired === "fixed_frames" && current.tooLong) {
showNote(`Needs ${asked} frames; the video is shorter.`, "warn");
} else if (current.mode === "wired" && wired === "fixed_frames" && latest != null && first > latest && !unknown) {
showNote(`Needs ${asked} frames; only ${room ?? "fewer"} fit from here. The run will fail.`, "warn",
locked("start") ? [] : [{ label: `Move start to ${secondsText(latest / clip.fps)} s`, run: () => writeStart(latest) }]);
} else if (current.mode === "length" && current.truncated && !fills) {
const actions = [{ label: `Shorten to ${rate > 0 ? `${secondsText(frames / rate)} s` : `${frames} frames`}`, run: () => { set("max_frames", Math.max(1, frames)); set("end_seconds", 0); } }];
if (!locked("start") && latest != null && latest < first) actions.push({ label: `Move start to ${secondsText(latest / clip.fps)} s`, run: () => writeStart(latest) });
showNote(`Only ${frames} of ${current.requested} frames fit from here.`, "warn", actions);
} else if (current.mode === "wired" && wired !== "fixed_frames" && current.truncated && frames != null) {
showNote(`Video ends first: ${frames} of ${asked} frames.`);
} else if (current.mode === "length" && fills && current.truncated) {
showNote("Runs to the end of the video.");
} else if (stopNote) {
showNote(stopNote);
} else {
showNote("");
}
publish?.(endSec == null || frames == null ? null : { frames, startSeconds: frameTime(first, clip), endSeconds: endSec, roomFrames: room });
};
if (trim) {
const sampling = el("div", "ausboss-transform-trim-line wrap");
const nthLabel = el("label", "", "Every nth");
controls.every_nth = makeScrubInput({ value: get("every_nth", 1), min: 1, max: 512, step: 1, decimals: 0,
title: "Keep one frame in this many. Output fps is adjusted to keep real-time playback; a Length counts the frames kept.",
title: "Keep one frame in this many. Output fps is adjusted to keep real-time playback; the Duration counts the frames kept.",
onChange: (next) => { if (!driven("every_nth")) set("every_nth", next); sync(); }, onSettle: onCommit,
});
nthLabel.append(controls.every_nth.root);
@@ -649,15 +864,20 @@ export function mountTransformTrim({ get, set, has = () => true, driven = () =>
reset.type = "button";
reset.addEventListener("click", () => {
const current = plan();
if (current.mode === "free") {
if (current.mode !== "wired") {
// The whole video: no start, no end, no Duration limit.
if (!locked("start")) set("start_seconds", 0);
if (!locked("end")) set("end_seconds", 0);
sync(); onCommit?.();
if (!endDriven()) set("end_seconds", 0);
set("max_frames", 0);
if (!driven("fixed_frames")) set("fixed_frames", 0);
stopNote = "";
seek(0, true); onCommit?.();
} else {
moveEdge("start", 0, true);
}
});
footer.append(summary, reset);
sampling.append(unitPill);
footer.append(useStart, el("span", "spacer"), reset);
root.append(sampling, footer);
}
root.addEventListener("pointerdown", (event) => {
+14 -3
View File
@@ -10,6 +10,7 @@
// panel's hidden storage widget stays hidden whichever renderer is on.
const STASH = "__ausbossVisibilityStash";
const PAINT_KEYS = ["computeSize", "computeLayoutSize", "draw"];
// Collapse a widget to zero height. Returns true when this call changed
// visibility, false when it was already hidden (callers use the return to
@@ -27,6 +28,10 @@ export function hideWidget(widget) {
computeSize: widget.computeSize,
computeLayoutSize: widget.computeLayoutSize,
draw: widget.draw,
// Which of the three the widget carried itself. One it lacked is deleted
// again on show: left behind as `undefined`, the frontend takes it for a
// custom-drawn widget and App mode draws an empty row.
own: Object.fromEntries(PAINT_KEYS.map((key) => [key, Object.prototype.hasOwnProperty.call(widget, key)])),
hidden: widget.hidden,
optionsHidden: options.hidden,
optionsDescriptor: Object.getOwnPropertyDescriptor(widget, "options"),
@@ -61,9 +66,10 @@ export function hideWidget(widget) {
export function showWidget(widget) {
const stash = widget?.[STASH];
if (!stash) return false;
widget.computeSize = stash.computeSize;
widget.computeLayoutSize = stash.computeLayoutSize;
widget.draw = stash.draw;
for (const key of PAINT_KEYS) {
if (stash.own && !stash.own[key]) delete widget[key];
else widget[key] = stash[key];
}
widget.hidden = stash.hidden;
const options = widget.options;
try {
@@ -84,6 +90,11 @@ export function showWidget(widget) {
return true;
}
// True while hideWidget holds the widget hidden.
export function isWidgetHidden(widget) {
return Boolean(widget?.[STASH]);
}
// Drive a widget toward a target visibility; true when anything changed.
export function setWidgetVisible(widget, visible) {
return visible ? showWidget(widget) : hideWidget(widget);
+13
View File
@@ -213,6 +213,19 @@ export function matchInstalled(name, files) {
return loose ? { found: true, path: loose } : { found: false, path: null };
}
// The copy of `name` to pick without asking: the exact path when the folder
// has it, else the only file of that name in any subfolder. Two copies in
// different subfolders give null: which one to use is the user's choice.
export function onlyCopy(name, files) {
const match = matchInstalled(name, files);
if (!match.found) return null;
const wanted = str(name, 1000).trim().replace(/\\/g, "/").toLowerCase();
if (match.path.toLowerCase() === wanted) return match.path;
const base = baseName(name).toLowerCase();
const copies = files.filter((file) => baseName(str(file, 1000).replace(/\\/g, "/")).toLowerCase() === base);
return copies.length === 1 ? match.path : null;
}
// Node packs present in a graph, from each node type's python_module
// ("custom_nodes.ComfyUI-AusBoss"). Core modules ("nodes",
// "comfy_extras.*") are skipped: nobody needs to install those. The first
+9
View File
@@ -11,6 +11,7 @@ import {
unionOf,
} from "../shared/snap_lines.mjs";
import { boundsOf, nodeElements, outlineOf } from "../shared/outline.mjs";
import { TILE_MOVE } from "../shared/tile_face.mjs";
// Snap into line: a node or group being dragged lines up with the nodes and
// groups around it, and a teal line shows what it lines up with. A corner
@@ -294,6 +295,13 @@ function onPointerMove(event) {
});
}
// A frameless tile moves itself and keeps its pointer moves to itself
// (js/shared/tile_face.mjs), then reports each move here once placed.
function onTileMove(event) {
if (!state.before || !event.detail) return;
step(event.detail);
}
function end() {
state.before = null;
state.corner = null;
@@ -348,6 +356,7 @@ function install() {
window.addEventListener("pointerdown", onPointerDown, true);
window.addEventListener("pointerdown", afterPointerDown);
window.addEventListener("pointermove", onPointerMove);
window.addEventListener(TILE_MOVE, onTileMove);
// Capture phase: the classic canvas stops its pointerup from bubbling.
window.addEventListener("pointerup", end, true);
window.addEventListener("pointercancel", end, true);
+8 -7
View File
@@ -424,24 +424,25 @@ const CARDS = {
],
},
AUSBOSS_NODES_LoadVideo: {
minWidth: 320, first: true, hide: ["upload"],
// Every nth and the frame limit (as Duration) are in the timing card
// under the player (js/load_video). The card hides them, so App mode can
// still show them as fields.
minWidth: 320, first: true, hide: ["upload", "every_nth", "max_frames"],
rows: [
{ widget: "video", label: "Source", kind: "select", preview: { kind: "video", url: viewUrl },
button: { text: PANEL_LABELS.load, title: "Upload a video into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
{ widget: "custom_width", label: "Width", suffix: "px", title: "0 keeps the source width; set one side only to keep the aspect." },
{ widget: "custom_height", label: "Height", suffix: "px", title: "0 keeps the source height; set one side only to keep the aspect." },
{ widget: "every_nth", label: "Every nth" },
{ widget: "max_frames", label: "Limit" },
],
},
AUSBOSS_NODES_LoadAudio: {
// The wave, IN and OUT live in the panel under the card (js/load_audio).
minWidth: 280, first: true, hide: ["upload"],
// The wave and Start, Duration and Ends at live in the panel under the
// card (js/load_audio); max_seconds is the Duration there. The card
// hides it, so App mode can still show it as a field.
minWidth: 280, first: true, hide: ["upload", "max_seconds"],
rows: [
{ widget: "audio", label: "Source", kind: "select",
button: { text: PANEL_LABELS.load, title: "Upload a sound file into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
{ widget: "max_seconds", label: "Max length", suffix: "s", decimals: 1, trimZeros: true,
title: "The longest the sound may be. Anything past it is cut off and shows in red. 0 means no limit." },
],
},
// Load Image: the file, then where it is in the folder and the size it
+61 -19
View File
@@ -15,7 +15,7 @@ import { app } from "../../../scripts/app.js";
import { setTileFace, TILE_FACE_CSS } from "../shared/tile_face.mjs";
import { NOTE_TYPES, serializeNoteIdentity } from "../shared/note_identity.mjs";
import { compactAction } from "../shared/panel_controls.mjs";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange, showToast } from "../shared/index.mjs";
import { collectGraphNodes } from "../shared/appearance.mjs";
import { copyToClipboard } from "../shared/clipboard.mjs";
import { confirmDiscard } from "../shared/discard_prompt.mjs";
@@ -38,6 +38,7 @@ import {
noteIsEmpty,
noteShowsTileFace,
normalizeNote,
onlyCopy,
packsFromGraph,
parseMarkdown,
rowFromCells,
@@ -46,8 +47,36 @@ import {
} from "../shared/workflow_note.mjs";
import { comboValues, commitWidgetValue } from "../shared/widget_card_math.mjs";
import { parseRows, serializeRows } from "../shared/lora_stack.mjs";
import { isFileWidget } from "../shared/lora_file_widgets.mjs";
const CSS_ID = "ausboss-workflow-note-css";
const PICK_FOUND_SETTING = "AusBoss.Models.PickFoundCopy";
function pickFoundCopies() {
return app.ui?.settings?.getSettingValue?.(PICK_FOUND_SETTING) !== false;
}
// Point the loaders (and LoRA Loader rows) that ask for a file by another
// spelling at the copy the note found. Returns how many it changed.
function useFoundCopy(path, loaders, loraRows, files) {
for (const entry of loaders) {
commitWidgetValue(entry.node, entry.widget, listedSpelling(path, entry.options), app.canvas);
entry.node.setDirtyCanvas?.(true, true);
}
const stacks = new Map();
for (const entry of loraRows) stacks.set(entry.widget, [...(stacks.get(entry.widget) ?? []), entry]);
for (const [widget, entries] of stacks) {
const rows = parseRows(widget.value);
for (const entry of entries) {
if (rows[entry.index]) rows[entry.index] = { ...rows[entry.index], name: listedSpelling(path, files) };
}
commitWidgetValue(entries[0].node, widget, serializeRows(rows), app.canvas);
entries[0].node.setDirtyCanvas?.(true, true);
}
app.graph?.setDirtyCanvas?.(true, true);
notifyAusbossChange();
return loaders.length + loraRows.length;
}
const WIDGET_NAME = "ausboss_workflow_note_panel";
const PANEL_MIN_WIDTH = 300;
const CARD_MIN_HEIGHT = 160;
@@ -417,22 +446,7 @@ function modelRow(state, row) {
use.title = `Point ${names} at ${path}.`;
use.addEventListener("pointerdown", (event) => event.stopPropagation());
use.addEventListener("click", () => {
for (const entry of loaders) {
commitWidgetValue(entry.node, entry.widget, listedSpelling(path, entry.options), app.canvas);
entry.node.setDirtyCanvas?.(true, true);
}
const stacks = new Map();
for (const entry of loraRows) stacks.set(entry.widget, [...(stacks.get(entry.widget) ?? []), entry]);
for (const [widget, entries] of stacks) {
const rows = parseRows(widget.value);
for (const entry of entries) {
if (rows[entry.index]) rows[entry.index] = { ...rows[entry.index], name: listedSpelling(path, files) };
}
commitWidgetValue(entries[0].node, widget, serializeRows(rows), app.canvas);
entries[0].node.setDirtyCanvas?.(true, true);
}
app.graph?.setDirtyCanvas?.(true, true);
notifyAusbossChange();
useFoundCopy(path, loaders, loraRows, files);
checkModels(state, false);
});
action.append(pill, use);
@@ -628,6 +642,7 @@ function renderSections(state, scroll) {
async function checkModels(state, fresh) {
const generation = (state.checkGeneration = (state.checkGeneration || 0) + 1);
const rows = state.rows;
const picked = [];
for (const entry of rows) setDot(entry.dot, "checking", "checking…");
const byDir = new Map();
for (const entry of rows) {
@@ -666,7 +681,14 @@ async function checkModels(state, fresh) {
const elsewhere = match.found && subfolderOf(match.path);
const loaders = elsewhere ? loadersNeeding(entry.row.name, match.path, graphListWidgets()) : [];
const loraRows = elsewhere ? loraRowsNeeding(entry.row.name, match.path, graphLoraLoaders(), files) : [];
if (match.found && (loaders.length || loraRows.length)) {
if (match.found && (loaders.length || loraRows.length) && pickFoundCopies() && onlyCopy(entry.row.name, files) === match.path) {
// One copy, so nothing to choose: the loaders take it without a
// click (App mode shows no Guide to click in).
useFoundCopy(match.path, loaders, loraRows, files);
picked.push(match.path);
setDot(entry.dot, "ok", `Found in ${subfolderOf(match.path)}/ and picked: ${match.path}`);
entry.showInstalled(match.path);
} else if (match.found && (loaders.length || loraRows.length)) {
setDot(entry.dot, "ok", `Found in ${subfolderOf(match.path)}/: ${match.path}`);
entry.showElsewhere(match.path, loaders, loraRows, files);
} else if (match.found) {
@@ -678,6 +700,14 @@ async function checkModels(state, fresh) {
}
}
}));
if (picked.length && generation === state.checkGeneration) {
const folders = [...new Set(picked.map(subfolderOf))].map((folder) => `${folder}/`).join(", ");
showToast({
summary: "Models found",
detail: `${picked.length === 1 ? "1 model file" : `${picked.length} model files`} found in ${folders} and picked for this workflow.`,
life: 4000,
});
}
if (state.domWidget && generation === state.checkGeneration) fitNote(state);
}
@@ -756,7 +786,7 @@ function graphListWidgets() {
seen.add(graph);
for (const node of graph._nodes ?? graph.nodes ?? []) {
for (const widget of node.widgets ?? []) {
if (widget?.type !== "combo" || typeof widget.value !== "string") continue;
if (widget?.type !== "combo" || typeof widget.value !== "string" || isFileWidget(widget)) continue;
out.push({ node, widget, value: widget.value, options: comboValues(widget) });
}
if (node.subgraph) walk(node.subgraph);
@@ -1178,6 +1208,18 @@ function buildPanel(node) {
app.registerExtension({
name: "AusBoss.WorkflowNote",
settings: [
{
id: PICK_FOUND_SETTING,
name: "Pick model files found in a subfolder",
type: "boolean",
defaultValue: true,
category: ["🆎 AusBoss", "Models", "Pick found files"],
tooltip:
"When a workflow's Guide finds a model you already have in a subfolder, the workflow switches to that "
+ "file by itself. Off: the Guide shows a Use it button instead.",
},
],
beforeRegisterNodeDef(nodeType, nodeData) {
if (!NOTE_TYPES.has(nodeData?.name)) return;
hideInputsInDef(nodeData, ["note"]);
+25 -5
View File
@@ -60,6 +60,26 @@ def add_module_version(source, token):
return _MODULE_IMPORT.sub(lambda m: f"{m.group(1)}{m.group(2)}{m.group(3)}?v={token}{m.group(2)}", source)
def list_served_scripts(js_root):
"""The pack's own scripts by their address below the js folder:
{"shared/index.mjs": <path>}. Made once at startup, so a request is
only looked up in it and the address a browser sends never reaches the
disk: no whole path, network share or ".." is ever opened. Links are
left out, and anything that resolves outside the js folder."""
root = Path(js_root).resolve()
scripts = {}
for path in sorted(root.rglob("*")):
try:
if path.suffix not in (".js", ".mjs") or path.is_symlink() or not path.is_file():
continue
if not path.resolve().is_relative_to(root):
continue
except OSError:
continue
scripts[path.relative_to(root).as_posix()] = path
return scripts
def make_revalidate_middleware(pack_name, js_root=None, token=None):
"""aiohttp middleware for this pack's scripts, nothing else touched.
@@ -69,7 +89,7 @@ def make_revalidate_middleware(pack_name, js_root=None, token=None):
from aiohttp import web
marker = f"/extensions/{pack_name}/"
root = Path(js_root).resolve() if js_root and token else None
scripts = list_served_scripts(js_root) if js_root and token else None
served = {}
def versioned(path):
@@ -90,15 +110,15 @@ def make_revalidate_middleware(pack_name, js_root=None, token=None):
def tagged_response(request):
"""The tagged script for this request, or None to let ComfyUI serve it."""
if root is None or request.method not in ("GET", "HEAD"):
if not scripts or request.method not in ("GET", "HEAD"):
return None
start = request.path.find(marker)
if start < 0 or not request.path.endswith((".js", ".mjs")):
return None
target = scripts.get(request.path[start + len(marker):])
if target is None:
return None
try:
target = (root / request.path[start + len(marker):]).resolve()
if not target.is_relative_to(root) or not target.is_file():
return None
found = versioned(target)
except (OSError, ValueError, UnicodeDecodeError):
return None
+3 -2
View File
@@ -82,9 +82,10 @@ def place_inside(folder, roots: dict) -> tuple[str, str] | None:
This compares text only. A path that is outside those folders is never
looked up on disk, and one on another machine is refused from its text."""
text = str(folder or "").strip().strip('"').replace("\\", "/")
if not looks_full(text) or text.startswith("//"):
# A "~" path is not expanded: only a path written out in full can match.
if not looks_full(text) or text.startswith("//") or text.startswith("~"):
return None
full = os.path.normpath(os.path.expanduser(text))
full = os.path.normpath(text)
for source, root in roots.items():
for base in {os.path.normpath(str(root)), os.path.realpath(str(root))}:
if full == base:
+45 -12
View File
@@ -6,18 +6,26 @@ that are wanted: they are copied into the output folder under the names the
node would have given them. Everything here works from names this module
made itself; the only thing a caller sends is the run's token and which
pictures to keep.
What a run holds (its settings, its count, what was kept) stays in this
process's memory, never in a file. ComfyUI's temp folder takes uploads, so a
list read back from there could be anyone's. The held pictures themselves
are named from the token, their number and one of the node's own formats,
and must still be in the held folder when they are copied.
"""
from __future__ import annotations
from collections import OrderedDict
from datetime import datetime
import json
from pathlib import Path
import re
import secrets
import shutil
import threading
from ._image_save_helpers import (
FORMAT_EXTENSIONS,
IMAGE_SAVE_LOCK,
existing_action,
name_stem,
@@ -34,6 +42,14 @@ from ._image_save_helpers import (
HELD_FOLDER = "ausboss_held"
_TOKEN = re.compile(r"^[0-9a-f]{16}$")
GONE = "These pictures are no longer held. Run the workflow again."
# The held pictures' formats: the extensions Save Image writes, nothing else.
HELD_EXTENSIONS = frozenset(FORMAT_EXTENSIONS.values())
# A run holds at most this many pictures, and the server remembers this many
# runs; the oldest is forgotten first and then says GONE.
MAX_HELD_PICTURES = 10000
MAX_HELD_RUNS = 256
_RUNS: "OrderedDict[str, dict]" = OrderedDict()
_RUNS_LOCK = threading.Lock()
def plan_destinations(settings: dict, count: int, now: datetime, root: Path, output_root: Path, picks=None):
@@ -88,15 +104,31 @@ def settle_destinations(planned, has_caption: bool, output_root: Path) -> list[s
def _held_name(token: str, index: int, extension: str) -> str:
if not _TOKEN.match(token) or extension not in HELD_EXTENSIONS or not 0 <= index < MAX_HELD_PICTURES:
raise ValueError("Save Image: that is not a picture it is holding.")
return f"{token}_{index:03d}.{extension}"
def _held_source(folder: Path, token: str, index: int, extension: str) -> Path:
"""A held picture's file, which must still sit directly in the held folder."""
source = folder / _held_name(token, index, extension)
if not source.is_file() or source.is_symlink() or source.resolve().parent != folder.resolve():
raise LookupError(GONE)
return source
def hold_pictures(temp_root, frames, settings: dict, encode) -> tuple[str, list[dict]]:
"""Write a run's pictures to the temp folder and remember how to name them.
`encode(path, frame)` writes one picture in the run's format. Returns
the run's token and the entries the node shows them from.
"""
frames = list(frames)
if len(frames) > MAX_HELD_PICTURES:
raise ValueError(
f"Save Image: {len(frames)} pictures are too many to hold (at most {MAX_HELD_PICTURES}). "
"Turn Auto save on to save them straight away."
)
folder = Path(temp_root) / HELD_FOLDER
folder.mkdir(parents=True, exist_ok=True)
token = secrets.token_hex(8)
@@ -105,8 +137,10 @@ def hold_pictures(temp_root, frames, settings: dict, encode) -> tuple[str, list[
name = _held_name(token, index, settings["extension"])
encode(folder / name, frame)
previews.append({"filename": name, "subfolder": HELD_FOLDER, "type": "temp"})
manifest = dict(settings, count=len(previews), kept={})
(folder / f"{token}.json").write_text(json.dumps(manifest), encoding="utf-8")
with _RUNS_LOCK:
_RUNS[token] = dict(settings, count=len(previews), kept={})
while len(_RUNS) > MAX_HELD_RUNS:
_RUNS.popitem(last=False)
return token, previews
@@ -119,16 +153,18 @@ def keep_pictures(temp_root, output_root, token, picks=None, now: datetime | Non
if not isinstance(token, str) or not _TOKEN.match(token):
raise ValueError("Save Image: that is not a run it is holding.")
folder = Path(temp_root) / HELD_FOLDER
manifest_path = folder / f"{token}.json"
if not manifest_path.is_file():
with _RUNS_LOCK:
manifest = _RUNS.get(token)
if manifest is None:
raise LookupError(GONE)
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
count = int(manifest["count"])
kept = {int(index): str(path) for index, path in dict(manifest.get("kept") or {}).items()}
kept = dict(manifest["kept"])
if picks is None:
wanted = list(range(count))
else:
if len(picks) > MAX_HELD_PICTURES:
raise ValueError("Save Image: that picture is not in this run.")
wanted = []
for pick in picks:
if isinstance(pick, bool) or not isinstance(pick, int) or not 0 <= pick < count:
@@ -151,17 +187,14 @@ def keep_pictures(temp_root, output_root, token, picks=None, now: datetime | Non
if action == "skip":
skipped.append(index)
continue
source = folder / _held_name(token, index, manifest["extension"])
if not source.is_file():
raise LookupError(GONE)
source = _held_source(folder, token, index, manifest["extension"])
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, path)
if has_caption:
sidecar_path(path).write_text(caption, encoding="utf-8")
kept[index] = path.resolve().relative_to(resolved_root).as_posix()
saved.append(index)
manifest["kept"] = {str(index): path for index, path in kept.items()}
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
manifest["kept"] = kept
return {
"count": count,
"saved": [{"index": index, "path": kept[index]} for index in saved],
+2 -5
View File
@@ -61,11 +61,8 @@ def list_lama_models() -> list[str]:
def resolve_lama_model(model_name: str) -> Path:
register_lama_model_folder()
if folder_paths is None:
path = Path(model_name).expanduser().resolve()
if path.is_file():
return path
else:
# Only a name from ComfyUI's lama model folder: a typed path is never opened.
if folder_paths is not None:
resolved = folder_paths.get_full_path(MODEL_FOLDER, model_name)
if resolved:
return Path(resolved).resolve()
+19 -11
View File
@@ -480,17 +480,25 @@ def transform_tensor_batch_chunked(
return output, mask, geometry
def stable_file_fingerprint(path: str | os.PathLike[str], inputs: dict[str, object]) -> str:
normalized_path = str(Path(path).resolve()).casefold()
try:
stat = os.stat(path)
file_state: dict[str, object] = {
"path": normalized_path,
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
}
except OSError:
file_state = {"path": normalized_path, "missing": True}
def stable_file_fingerprint(path: Path | None, inputs: dict[str, object]) -> str:
"""A key that changes when the inputs or the file do.
`path` is what resolve_input_path or resolve_video_path returned, or
None when they refused the value. Only such a path is ever looked at on
disk: a refused value is a string, and a string is only hashed, so a
whole path or a network share typed into a widget is never opened."""
if isinstance(path, Path):
try:
stat = os.stat(path)
file_state: dict[str, object] = {
"path": str(path).casefold(),
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
}
except OSError:
file_state = {"path": str(path).casefold(), "missing": True}
else:
file_state = {"unresolved": True}
payload = {"file": file_state, "inputs": inputs}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
+1 -1
View File
@@ -168,7 +168,7 @@ class AusBossImageCropRotatePad:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
# Every widget value is already part of ComfyUI's cache key, so a
# changed transform or budget re-runs the node without this; the
+5 -7
View File
@@ -15,9 +15,8 @@ class AusBossLoadAudio:
"Loads a sound file and hands on only the part you pick. The node shows the "
"sound as a wave, so you can see where the loud parts are. Drag the two "
"handles to set where it starts and stops, and press play to hear just that "
"part. Set Max length to the longest sound the next step takes: anything "
"longer shows in red as cut off, so you see exactly what comes out before "
"you run anything."
"part. Type a Duration to get a sound of an exact length, such as the "
"length of the video you are making."
)
SEARCH_ALIASES = [
"load audio",
@@ -49,7 +48,7 @@ class AusBossLoadAudio:
"min": 0.0,
"max": 86400.0,
"step": 0.01,
"tooltip": "Where the sound starts. Drag the wave's IN handle or type a time.",
"tooltip": "Where the sound starts. Drag the wave's left handle or type a Start.",
},
),
"end_seconds": (
@@ -59,7 +58,7 @@ class AusBossLoadAudio:
"min": 0.0,
"max": 86400.0,
"step": 0.01,
"tooltip": "Where the sound stops. 0 plays to the end. Drag the OUT handle or type a time.",
"tooltip": "Where the sound stops. 0 plays to the end. The face sets a Duration instead.",
},
),
},
@@ -72,8 +71,7 @@ class AusBossLoadAudio:
"max": 86400.0,
"step": 0.1,
"tooltip": (
"The longest the sound may be. Anything past it is cut off and shows "
"in red. 0 means no limit."
"How long the sound is: the Duration box. 0 runs to the end of the file."
),
},
),
+1 -1
View File
@@ -253,7 +253,7 @@ class AusBossLoadImage:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
return stable_file_fingerprint(path, {"image": image, **values})
+1 -1
View File
@@ -403,7 +403,7 @@ class AusBossLoadImagePad:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
return stable_file_fingerprint(path, {"image": image, **values})
+8 -10
View File
@@ -18,12 +18,12 @@ class AusBossLoadVideo:
CATEGORY = "🆎 AusBoss/Video"
DESCRIPTION = (
"Loads a video as a BHWC frame batch plus its audio, trimmed to an "
"optional start/end window selected on the preview timeline, with frame count, "
"optional window set with Start, Duration and Ends at under the player, with frame count, "
"fps, size, and duration outputs ready for downstream wiring, plus a lazy "
"core VIDEO output for nodes that consume whole videos. every_nth thins "
"the batch and max_frames caps it, so long clips load without filling "
"memory. single_frame flips the loader into a frame picker that "
"returns just the frame at the IN time as a one-image batch."
"returns just the frame at the start time as a one-image batch."
)
SEARCH_ALIASES = [
"load video",
@@ -53,8 +53,7 @@ class AusBossLoadVideo:
"max": 86400.0,
"step": 0.01,
"tooltip": (
"Skip everything before this time. Drag the preview's IN "
"handle or type an exact value below the player."
"Skip everything before this time. It is the Start box under the player."
),
},
),
@@ -66,8 +65,7 @@ class AusBossLoadVideo:
"max": 86400.0,
"step": 0.01,
"tooltip": (
"Stop at this time; 0 plays to the end. Drag the preview's "
"OUT handle or type an exact value below the player."
"Stop at this time; 0 plays to the end. The face sets a Duration instead."
),
},
),
@@ -115,8 +113,8 @@ class AusBossLoadVideo:
"max": 100000,
"step": 1,
"tooltip": (
"Stop after this many kept frames; 0 loads the "
"whole trim window. Caps memory on long clips — "
"Stop after this many kept frames: the Duration box. 0 loads the "
"whole window. Caps memory on long clips — "
"the decode ends early instead of loading and "
"discarding."
),
@@ -127,8 +125,8 @@ class AusBossLoadVideo:
{
"default": False,
"tooltip": (
"Load only the frame at the IN time as a "
"one-image batch. The preview's trim strip "
"Load only the frame at the start time as a "
"one-image batch. The timing card "
"becomes a frame picker (the FRAME button "
"toggles this), and end_seconds, every_nth, "
"and max_frames are ignored."
+3 -2
View File
@@ -43,7 +43,7 @@ class AusBossVideoCropRotatePad:
required = {
"video": (
list_input_videos(),
{"tooltip": "Choose a video in ComfyUI's input folder or use the upload button."},
{"video_upload": True, "tooltip": "Choose a video in ComfyUI's input folder or use the upload button."},
),
"source_mode": (
["input folder", "local path"],
@@ -152,7 +152,7 @@ class AusBossVideoCropRotatePad:
try:
path = resolve_video_path(source_mode, video, local_path)
except Exception:
path = local_path if source_mode == "local path" else video
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
resize = {name: values.get(name) for name in resize_inputs()}
return stable_file_fingerprint(
@@ -160,6 +160,7 @@ class AusBossVideoCropRotatePad:
{
"video": video,
"source_mode": source_mode,
"local_path": local_path,
"seek_mode": seek_mode,
"frame_index": int(frame_index),
"frame_time": round(float(frame_time), 6),
+10 -9
View File
@@ -49,8 +49,8 @@ class AusBossVideoCropRotatePadClip:
"mask of the generated area (rotation corners and padding), the audio "
"for the same window, the frame count, fps, size, and duration, and a "
"stitcher so Stitch Inpaint can paste the source frames back over the "
"generated clip. Drag IN and OUT to trim, or turn Length on to set "
"the clip by a number of output frames from IN."
"generated clip. Set the clip with Start, Duration and Ends at, or drag "
"its two handles on the timeline."
)
SEARCH_ALIASES = [
"video crop",
@@ -68,7 +68,7 @@ class AusBossVideoCropRotatePadClip:
required = {
"video": (
list_input_videos(),
{"tooltip": "Choose a video in ComfyUI's input folder or use the upload button."},
{"video_upload": True, "tooltip": "Choose a video in ComfyUI's input folder or use the upload button."},
),
"source_mode": (
["input folder", "local path"],
@@ -218,25 +218,25 @@ class AusBossVideoCropRotatePadClip:
}),
"start_frame": ("INT", {
"forceInput": True, "min": 0,
"tooltip": "Zero-based source start frame; overrides and locks timeline IN. "
"tooltip": "Zero-based source start frame; overrides and locks Start. "
"Uses the source frame-rate grid.",
}),
"end_frame": ("INT", {
"forceInput": True, "min": 0,
"tooltip": "Exclusive source end frame; 0 means source end. Overrides and "
"locks timeline OUT. Uses the source frame-rate grid.",
"locks Ends at. Uses the source frame-rate grid.",
}),
"frame_load_cap": ("INT", {
"forceInput": True, "min": 0,
"tooltip": "Maximum returned frames after rate conversion and Every nth, "
"before Frames for. Overrides and locks Length; 0 means unlimited.",
"before Frames for. Overrides and locks Duration; 0 means unlimited.",
}),
"fixed_frames": ("INT", {
"default": 0, "min": 0, "max": 100000,
"tooltip": "Exact output frames after rate conversion and Every nth; 0 = off. "
"Connected, it sets the length from IN. Overrides OUT/end_frame, Length, "
"Connected, it sets the length from Start. Overrides Ends at/end_frame, Duration, "
"frame_load_cap and Frames for. Duration = frames / output fps; 120 frames at 24 fps = 5 seconds. "
"The source must be long enough. A linked IN anchors the window.",
"The source must be long enough. A linked Start anchors the window.",
}),
"last_seconds": ("FLOAT", {
"forceInput": True, "min": 0,
@@ -395,7 +395,7 @@ class AusBossVideoCropRotatePadClip:
try:
path = resolve_video_path(source_mode, video, local_path)
except Exception:
path = local_path if source_mode == "local path" else video
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
resize = {name: values.get(name) for name in resize_inputs()}
return stable_file_fingerprint(
@@ -403,6 +403,7 @@ class AusBossVideoCropRotatePadClip:
{
"video": video,
"source_mode": source_mode,
"local_path": local_path,
"start_seconds": round(float(start_seconds), 6),
"end_seconds": round(float(end_seconds), 6),
"every_nth": max(1, int(every_nth)),
+1 -1
View File
@@ -3,7 +3,7 @@ name = "ausboss-nodes"
# Manager/registry search matches against this text, so it names the actual
# nodes instead of describing the collection abstractly.
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes with compact controls: Image and Video Crop + Rotate + Pad (frame or clip), Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, and Step Preview. Example workflows for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
version = "2.25.2"
version = "2.26.2"
# comfy-cli serializes this to JSON verbatim, so `file` publishes the literal
# string {"file": "LICENSE"} to the registry listing. `text` puts a readable
# name there instead. Both forms are supported; the LICENSE file is unchanged.
+71
View File
@@ -0,0 +1,71 @@
import test from "node:test";
import assert from "node:assert/strict";
import { appFields, createAppModeSync, workflowMode } from "../js/shared/app_mode.mjs";
import { hideWidget, isWidgetHidden } from "../js/shared/widget_visibility.mjs";
function graph() {
const nodes = new Map();
for (const [id, names] of [["256", ["image", "upload"]], ["160", ["script"]]]) {
const node = { id, dirty: 0, widgets: names.map((name) => ({ name, value: "" })) };
for (const widget of node.widgets) hideWidget(widget);
nodes.set(id, node);
}
const find = (nodeId, name) => {
const node = nodes.get(nodeId);
const widget = node?.widgets.find((entry) => entry.name === name);
return widget ? { node, widget } : null;
};
return { nodes, find, changed: (node) => { node.dirty += 1; } };
}
const linearData = { inputs: [["256", "image", { description: "One clear photo." }], [160, "script"], ["999", "gone"]], outputs: ["145"] };
test("fields read both saved shapes and skip broken entries", () => {
assert.deepEqual(appFields(linearData), [
{ nodeId: "256", widget: "image" }, { nodeId: "160", widget: "script" }, { nodeId: "999", widget: "gone" },
]);
assert.deepEqual(appFields({ inputs: [null, ["1"], [{}, "x"]] }), []);
assert.deepEqual(appFields(undefined), []);
});
test("the mode falls back from the live mode to the saved one", () => {
assert.equal(workflowMode({ activeMode: null, initialMode: "app" }), "app");
assert.equal(workflowMode({ activeMode: "graph", initialMode: "app" }), "graph");
assert.equal(workflowMode(undefined), "graph");
});
test("App mode shows only the listed widgets, the graph hides them again", () => {
const g = graph();
const sync = createAppModeSync(g);
const image = g.find("256", "image").widget;
const upload = g.find("256", "upload").widget;
assert.equal(sync("app", linearData), 2);
assert.equal(isWidgetHidden(image), false);
assert.equal(image.options.hidden, false); // written, so the frontend hears it
assert.equal(isWidgetHidden(upload), true); // not on the form, left alone
assert.equal(g.nodes.get("256").dirty, 1);
sync("graph", linearData);
assert.equal(isWidgetHidden(image), true);
assert.equal(image.options.hidden, true);
assert.equal(isWidgetHidden(g.find("160", "script").widget), true);
});
test("a widget a card hides again while in App mode is shown again", () => {
const g = graph();
const sync = createAppModeSync(g);
sync("app", linearData);
const image = g.find("256", "image").widget;
hideWidget(image); // the card's load-time re-hide
sync("app", linearData);
assert.equal(isWidgetHidden(image), false);
});
test("builder mode and the graph leave card widgets hidden", () => {
const g = graph();
const sync = createAppModeSync(g);
for (const mode of ["graph", "builder:inputs"]) {
assert.equal(sync(mode, linearData), 0);
assert.equal(isWidgetHidden(g.find("256", "image").widget), true);
}
});
+2 -1
View File
@@ -262,7 +262,8 @@ test("the fields on a node face pass app shortcuts on", () => {
// cursor was in a Text node, a number box or the Seed box (reported on the
// Text node). A new field on a node face uses keepKeyInField too.
const js = join(dirname(fileURLToPath(import.meta.url)), "..", "js");
const fields = ["shared/widget_card.mjs", "shared/scrub_input.mjs", "seed/index.js", "save_image/index.js", "load_video/index.js", "lora_loader/index.js"];
// Load Video's typed IN/OUT went; its timing boxes are scrub inputs now.
const fields = ["shared/widget_card.mjs", "shared/scrub_input.mjs", "seed/index.js", "save_image/index.js", "lora_loader/index.js"];
for (const file of fields) {
const source = readFileSync(join(js, file), "utf-8");
assert.match(source, /keepKeyInField\(event\)/, `${file}: its field stops every key again`);
+36 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { clipOutputRate, inputNumber } from '../js/shared/clip_rate.mjs';
import { clipOutputRate, inputNumber, linkOrigin } from '../js/shared/clip_rate.mjs';
function linked(type='PrimitiveFloat', value=24) {
const source={type,widgets:[{name:'value',value}]};
return {inputs:[{name:'force_rate',link:1}],graph:{links:{1:{origin_id:2,origin_slot:0}},getNodeById:()=>source}};
@@ -38,3 +38,38 @@ test('reads linked fixed frames from AusBoss numeric cards without evaluating ca
node.inputs[0].link=null;
assert.equal(inputNumber(node,'fixed_frames',0),0);
});
test('a rate typed inside a subgraph counts as typed (Person Swap: Pick the model files -> video fps 24)', () => {
const literal = { id: 222, type: 'AUSBOSS_NODES_Integer', mode: 0, inputs: [{ name: 'value', link: null }], widgets: [{ name: 'value', value: 24 }] };
const inner = { links: new Map([[391, { origin_id: 222, origin_slot: 0 }]]), outputs: [{}, {}, { linkIds: [391] }], getNodeById: (id) => (id === 222 ? literal : null) };
const box = { id: 146, mode: 0, type: 'subgraph-id', subgraph: inner, isSubgraphNode: () => true };
const clip = { inputs: [{ name: 'force_rate', link: 7 }], graph: { links: { 7: { origin_id: 146, origin_slot: 2 } }, getNodeById: (id) => (id === 146 ? box : null) } };
assert.equal(inputNumber(clip, 'force_rate', 0), 24);
assert.equal(clipOutputRate(clip, 60, 1), 24);
// A calculation inside the subgraph stays unknown.
literal.type = 'AUSBOSS_NODES_MathExpression';
assert.equal(inputNumber(clip, 'force_rate', 0), null);
});
test('an older Primitive node and a Reroute both carry a typed number', () => {
const primitive = { id: 5, type: 'PrimitiveNode', mode: 0, widgets: [{ name: 'max_seconds', value: 7.5 }] };
const reroute = { id: 6, type: 'Reroute', mode: 0, inputs: [{ link: 2 }] };
const graph = { links: { 1: { origin_id: 6, origin_slot: 0 }, 2: { origin_id: 5, origin_slot: 0 } }, getNodeById: (id) => ({ 5: primitive, 6: reroute })[id] ?? null };
const audio = { inputs: [{ name: 'max_seconds', widget: { name: 'max_seconds' }, link: 1 }], graph };
assert.equal(inputNumber(audio, 'max_seconds', 0), 7.5);
assert.deepEqual(linkOrigin(audio, 'max_seconds'), { node: primitive, slot: 0 });
// Not linked: the caller's own value. Bypassed: unknown.
assert.equal(linkOrigin({ inputs: [{ name: 'max_seconds', link: null }] }, 'max_seconds'), undefined);
primitive.mode = 4;
assert.equal(inputNumber(audio, 'max_seconds', 0), null);
});
test('Layout Boxes reads a size from inside a subgraph', async () => {
const { wiredNumber } = await import('../js/shared/layout_boxes.mjs');
const latent = { id: 9, type: 'EmptyLatentImage', mode: 0, outputs: [{ name: 'LATENT' }], widgets: [{ name: 'width', value: 1024 }] };
const sizes = { id: 8, type: 'AUSBOSS_NODES_Integer', mode: 0, outputs: [{ name: 'int' }], inputs: [{ name: 'value', link: null }], widgets: [{ name: 'value', value: 832 }] };
const inner = { links: new Map([[50, { origin_id: 8, origin_slot: 0 }]]), outputs: [{ linkIds: [50] }], getNodeById: (id) => ({ 8: sizes, 9: latent })[id] ?? null };
const box = { id: 3, mode: 0, type: 'subgraph-id', subgraph: inner, isSubgraphNode: () => true };
const node = { inputs: [{ name: 'width', link: 4 }], graph: { links: { 4: { origin_id: 3, origin_slot: 0 } }, getNodeById: (id) => (id === 3 ? box : null) } };
assert.equal(wiredNumber(node, 'width'), 832);
});
+14
View File
@@ -114,3 +114,17 @@ test('Length row replaces the whole number+unit, preserves its value, and restor
source.mode=0;sync({...values,video_job:'keep going'});assert.equal(scrub.root.style.display,'');
assert.equal(node.widgets[0].value,12);assert.equal(node.inputs[0].link,8);
});
test('H3 makes 5 + 17n frames, rounding a clip down (Python video_frames)', async () => {
const { h3VideoFrames, clipLengthWords } = await import('../js/shared/h3_duration.mjs');
assert.equal(h3VideoFrames(48), 39);
assert.equal(h3VideoFrames(39), 39);
assert.equal(h3VideoFrames(56), 56);
assert.equal(h3VideoFrames(10), 22);
assert.equal(h3VideoFrames(1000), 360 - ((360 - 5) % 17));
const words = clipLengthWords({ frames: 48, startSeconds: 1, endSeconds: 3, roomFrames: 74 });
assert.equal(words.title, "H3 makes 39 of the clip's 48 frames · 1.63 s");
assert.match(words.note, /Stops at 2\.63 s.*1\.63 s or 2\.33 s/);
assert.equal(clipLengthWords({ frames: 39, startSeconds: 0, endSeconds: 1.625 }).warn, false);
assert.equal(clipLengthWords(null), null);
});
+29 -6
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import { grabZone, outputSummary, outputWindow, wavePeaks } from "../js/load_audio/audio_window.mjs";
import { grabZone, outputWindow, pickWrites, typedPick, wavePeaks } from "../js/load_audio/audio_window.mjs";
test("the face shows what the node hands on", () => {
// Mirrors audio_window in nodes/_audio_trim_helpers.py.
@@ -13,11 +13,34 @@ test("the face shows what the node hands on", () => {
assert.equal(outputWindow(10, "x", null, NaN).length, 10);
});
test("the line between IN and OUT says how long and what is cut", () => {
assert.equal(outputSummary(outputWindow(40, 8, 30, 15)), "15.0 s · cut 7.0 s");
assert.equal(outputSummary(outputWindow(200, 0, 0, 0)), "3:20.0");
assert.equal(outputSummary(outputWindow(40, 8, 30, 0), { maxFromLink: true }), "22.0 s · max wired");
assert.equal(outputSummary(outputWindow(0, 0, 0)), "");
test("a pick is stored as a Start and a Duration", () => {
// 2 s to 5 s of a 12 s file: Start 2, Duration 3, no end.
assert.deepEqual(pickWrites(12, 2, 5), { start: 2, end: 0, max: 3 });
// To the end of the file: no Duration, so a longer file later still runs to its end.
assert.deepEqual(pickWrites(12, 2, 12), { start: 2, end: 0, max: 0 });
// Hundredths, as the boxes show them; the Duration is the difference of the two.
assert.deepEqual(pickWrites(12, 1.234, 3.606), { start: 1.23, end: 0, max: 2.38 });
// A linked Duration cannot be written: the pick is a start and an end.
assert.deepEqual(pickWrites(12, 2, 5, { maxLinked: true }), { start: 2, end: 5 });
// A linked end leaves only the start to write.
assert.deepEqual(pickWrites(12, 2, 5, { endLinked: true }), { start: 2 });
// What it stores comes out as the same pick.
const stored = pickWrites(12, 2, 5);
assert.equal(outputWindow(12, stored.start, stored.end, stored.max).keepEnd, 5);
});
test("typing in a box: Start keeps the Duration, the other two keep the start", () => {
const window = outputWindow(12, 2, 0, 3); // 2 s to 5 s
assert.deepEqual(typedPick("start", 4, window, 12), { start: 4, end: 7 });
assert.deepEqual(typedPick("start", 11, window, 12), { start: 11, end: 12 }, "less of it is left near the end");
assert.deepEqual(typedPick("duration", 6, window, 12), { start: 2, end: 8 });
assert.deepEqual(typedPick("end", 9, window, 12), { start: 2, end: 9 });
assert.deepEqual(typedPick("end", 1, window, 12), { start: 2, end: 2.1 }, "an end before the start is held just after it");
// 0 or an empty Duration, and an empty Ends at, run to the end of the file.
assert.deepEqual(typedPick("duration", 0, window, 12), { start: 2, end: 12 });
assert.deepEqual(typedPick("duration", null, window, 12), { start: 2, end: 12 });
assert.deepEqual(typedPick("end", null, window, 12), { start: 2, end: 12 });
assert.deepEqual(typedPick("start", null, window, 12), { start: 0, end: 3 }, "an empty Start is the beginning");
});
test("a press grabs the nearest handle, the middle, or jumps", () => {
+112
View File
@@ -0,0 +1,112 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
FILE_WIDGET_PREFIX,
coreLoraList,
fileChoices,
isFileWidget,
rowsNeedingFiles,
syncFileWidgets,
} from "../js/shared/lora_file_widgets.mjs";
// A node the way LiteGraph hands it over: addWidget appends and returns.
function fakeNode() {
return {
widgets: [{ name: "loras", type: "customtext", value: "[]" }],
addWidget(type, name, value, callback, options) {
const widget = { type, name, value, callback, options };
this.widgets.push(widget);
return widget;
},
};
}
const row = (id, name, extra = {}) => ({ id, name, strength: 1, strength_clip: 1, enabled: true, ...extra });
const choices = (widget) => widget.options.values(widget);
test("only rows the server would load need a file", () => {
const rows = [
row("a", "pika.safetensors"),
row("b", ""),
row("c", "off.safetensors", { enabled: false }),
row("d", "group_off.safetensors", { group: "g", group_off: true }),
row("e", "zero.safetensors", { strength: 0, strength_clip: 0 }),
row("f", "clip_only.safetensors", { strength: 0, strength_clip: 0.5 }),
];
assert.deepEqual(rowsNeedingFiles(rows).map((item) => item.id), ["a", "f"]);
});
test("a file the loader would find anyway is not missing", () => {
const installed = ["minimax-h3/pika.safetensors", "style.safetensors"];
assert.ok(fileChoices("minimax-h3/pika.safetensors", installed).includes("minimax-h3/pika.safetensors"));
// saved as a bare name, installed in a subfolder: the loader finds it
assert.ok(fileChoices("pika.safetensors", installed).includes("pika.safetensors"));
assert.ok(fileChoices("STYLE.safetensors", installed).includes("STYLE.safetensors"));
assert.ok(!fileChoices("gone.safetensors", installed).includes("gone.safetensors"));
// no list to ask: never a false alarm
assert.deepEqual(fileChoices("gone.safetensors", null), ["gone.safetensors"]);
});
test("the install's list comes from ComfyUI's own LoRA loader", () => {
assert.deepEqual(coreLoraList({ input: { required: { lora_name: [["a.safetensors"], { tooltip: "x" }] } } }), ["a.safetensors"]);
assert.deepEqual(coreLoraList({ input: { required: { lora_name: ["COMBO", { options: ["b.safetensors"] }] } } }), ["b.safetensors"]);
assert.equal(coreLoraList(undefined), null);
assert.equal(coreLoraList({ input: { required: {} } }), null);
});
test("one hidden list per needed row, out of the save and the prompt", () => {
const node = fakeNode();
const hidden = [];
const changed = syncFileWidgets(node, [row("a", "pika.safetensors"), row("b", "")], {
installed: () => [],
hide: (widget) => hidden.push(widget),
});
assert.equal(changed, true);
const files = node.widgets.filter(isFileWidget);
assert.equal(files.length, 1);
const [widget] = files;
assert.equal(widget.type, "combo");
assert.equal(widget.name, `${FILE_WIDGET_PREFIX}1`);
assert.equal(widget.value, "pika.safetensors");
assert.equal(widget.serialize, false);
assert.equal(widget.options.serialize, false);
assert.deepEqual(hidden, [widget]);
// ComfyUI's check: a value that is not among the choices is a missing model
assert.ok(!choices(widget).includes(widget.value));
// the loras text keeps its place in front
assert.equal(node.widgets[0].name, "loras");
});
test("the lists follow the rows: renamed, added, removed", () => {
const node = fakeNode();
const options = { installed: () => ["here.safetensors"], hide: () => {} };
syncFileWidgets(node, [row("a", "one.safetensors"), row("b", "two.safetensors")], options);
const first = node.widgets.filter(isFileWidget)[0];
assert.equal(syncFileWidgets(node, [row("a", "here.safetensors"), row("b", "two.safetensors")], options), false);
assert.equal(node.widgets.filter(isFileWidget)[0], first, "the same widget is reused");
assert.equal(first.value, "here.safetensors");
assert.ok(choices(first).includes("here.safetensors"));
assert.equal(syncFileWidgets(node, [row("b", "two.safetensors")], options), true);
assert.deepEqual(node.widgets.filter(isFileWidget).map((widget) => [widget.value, widget.ausbossRowId]), [["two.safetensors", "b"]]);
syncFileWidgets(node, [], options);
assert.equal(node.widgets.filter(isFileWidget).length, 0);
assert.deepEqual(node.widgets.map((widget) => widget.name), ["loras"]);
});
test("a replacement put in the list goes to its row", () => {
const node = fakeNode();
const picks = [];
syncFileWidgets(node, [row("a", "one.safetensors"), row("b", "gone.safetensors")], {
installed: () => ["new.safetensors"],
hide: () => {},
onPick: (rowId, name) => picks.push([rowId, name]),
});
const widget = node.widgets.filter(isFileWidget)[1];
// what ComfyUI's Issues panel does: set the value, then call back
widget.value = "new.safetensors";
widget.callback("new.safetensors");
// a call back with the row's own file is no change
node.widgets.filter(isFileWidget)[0].callback("one.safetensors");
assert.deepEqual(picks, [["b", "new.safetensors"]]);
});
+29
View File
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { outlineOf } from "../js/shared/outline.mjs";
// A frameless tile draws a card inside a transparent node. Snap into line and
// Line up must use the card people see, not the node's wider bounds.
const canvas = {
canvas: { getBoundingClientRect: () => ({ left: 10, top: 20 }) },
ds: { scale: 2, offset: [5, 5] },
};
const card = (rect) => ({ isConnected: true, getBoundingClientRect: () => rect });
test("a tile's outline is its visible card", () => {
const node = {
boundingRect: [100, 100, 380, 80],
ausbossOutlineElement: card({ left: 10 + 2 * (114 + 5), top: 20 + 2 * (114 + 5), width: 704, height: 100 }),
};
assert.deepEqual(outlineOf(node, canvas), { x: 114, y: 114, w: 352, h: 50 });
});
test("a collapsed or unshown tile falls back to the node's bounds", () => {
const bounds = { x: 100, y: 100, w: 380, h: 80 };
const shown = card({ left: 0, top: 0, width: 50, height: 50 });
assert.deepEqual(outlineOf({ boundingRect: [100, 100, 380, 80], flags: { collapsed: true }, ausbossOutlineElement: shown }, canvas), bounds);
const hidden = card({ left: 0, top: 0, width: 0, height: 0 });
assert.deepEqual(outlineOf({ boundingRect: [100, 100, 380, 80], ausbossOutlineElement: hidden }, canvas), bounds);
assert.deepEqual(outlineOf({ boundingRect: [100, 100, 380, 80] }, canvas), bounds);
});
+108
View File
@@ -0,0 +1,108 @@
"""A loader's change check never opens a value it refused.
ComfyUI calls a node's IS_CHANGED with the prompt's widget values before it
runs anything, and /prompt needs no login. The picture and video loaders
first hand the value to their resolver, which takes only a file named below
ComfyUI's input, output or temp folder. When the resolver refuses it, the
value is hashed as text and nothing else: on Windows, merely looking up a
network path ("//host/share/x.png") contacts that host and hands it the
server's login.
"""
from __future__ import annotations
import os
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._transform_engine import stable_file_fingerprint # noqa: E402
from nodes.node_image_crop_rotate_pad import AusBossImageCropRotatePad # noqa: E402
from nodes.node_load_image import AusBossLoadImage # noqa: E402
from nodes.node_load_image_pad import AusBossLoadImagePad # noqa: E402
from nodes.node_video_crop_rotate_pad import AusBossVideoCropRotatePad # noqa: E402
from nodes.node_video_crop_rotate_pad_clip import AusBossVideoCropRotatePadClip # noqa: E402
REFUSED = [
"//evil-host/share/photo.png",
"\\\\evil-host\\share\\photo.png",
"/evil-host/etc/photo.png",
"../../evil-host/photo.png",
]
class DiskWatch:
"""Records every stat and resolve of a path that names the evil host."""
def __init__(self):
self.touched = []
def __enter__(self):
real_stat, real_resolve = os.stat, Path.resolve
watch = self
def stat(path, *args, **kwargs):
if "evil-host" in str(path):
watch.touched.append(("stat", str(path)))
return real_stat(path, *args, **kwargs)
def resolve(self, *args, **kwargs):
if "evil-host" in str(self):
watch.touched.append(("resolve", str(self)))
return real_resolve(self, *args, **kwargs)
self._patches = [patch("os.stat", stat), patch.object(Path, "resolve", resolve)]
for item in self._patches:
item.start()
return self
def __exit__(self, *exc):
for item in reversed(self._patches):
item.stop()
class ChangeCheckTests(unittest.TestCase):
def assert_off_disk(self, call):
for value in REFUSED:
with self.subTest(value=value), DiskWatch() as watch:
first = call(value)
self.assertEqual(watch.touched, [])
# The text still counts: another refused value is another key.
self.assertNotEqual(first, call(value + "x"))
def test_picture_loaders(self):
for node in (AusBossLoadImage, AusBossLoadImagePad, AusBossImageCropRotatePad):
with self.subTest(node=node.__name__):
self.assert_off_disk(lambda value, node=node: node.IS_CHANGED(image=value))
def test_video_crop_nodes(self):
for node in (AusBossVideoCropRotatePad, AusBossVideoCropRotatePadClip):
for mode in ("input folder", "local path"):
with self.subTest(node=node.__name__, mode=mode):
self.assert_off_disk(
lambda value, node=node, mode=mode: node.IS_CHANGED(
video=value if mode == "input folder" else "",
source_mode=mode,
local_path=value if mode == "local path" else "",
seek_mode="frame index",
frame_index=0,
frame_time=0.0,
**({"start_seconds": 0.0, "end_seconds": 0.0} if node is AusBossVideoCropRotatePadClip else {}),
)
)
def test_the_fingerprint_opens_only_a_resolved_path(self):
with DiskWatch() as watch:
stable_file_fingerprint("//evil-host/share/photo.png", {})
stable_file_fingerprint(None, {})
self.assertEqual(watch.touched, [])
if __name__ == "__main__":
unittest.main()
+40
View File
@@ -7,6 +7,7 @@ import re
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
@@ -244,6 +245,45 @@ class VersionedServingTests(unittest.TestCase):
for path, (_status, body, _headers) in self.fetch(paths).items():
self.assertNotIn("?v=tok", body, path)
def test_an_address_never_reaches_the_disk(self):
# The request is unauthenticated: its address is only looked up in
# the list of scripts made at startup, never joined to a folder and
# resolved. On Windows, resolving "//host/share" contacts that host.
web = self.web
touched = []
async def handled(request):
return web.Response(text="from the handler", content_type="text/javascript")
async def run():
middleware = make_revalidate_middleware("ausboss-nodes", self.js, "tok")
real_resolve, real_stat = Path.resolve, os.stat
def resolve(path, *args, **kwargs):
if "evil-host" in str(path):
touched.append(str(path))
return real_resolve(path, *args, **kwargs)
def stat(path, *args, **kwargs):
if "evil-host" in str(path):
touched.append(str(path))
return real_stat(path, *args, **kwargs)
with patch.object(Path, "resolve", resolve), patch("os.stat", stat):
for path in [
"/extensions/ausboss-nodes//evil-host/share/x.mjs",
"/extensions/ausboss-nodes/%2F%2Fevil-host/share/x.mjs",
"/extensions/ausboss-nodes/%5C%5Cevil-host%5Cshare%5Cx.mjs",
"/extensions/ausboss-nodes/../../evil-host/x.mjs",
"/extensions/ausboss-nodes/%2e%2e/%2e%2e/evil-host/x.js",
"/extensions/ausboss-nodes/C:/evil-host/x.mjs",
]:
response = await middleware(self.make_request("GET", path), handled)
self.assertEqual(response.text, "from the handler", path)
asyncio.run(run())
self.assertEqual(touched, [])
def test_without_a_tag_the_files_are_served_as_before(self):
path = "/extensions/ausboss-nodes/shared/b.mjs"
status, body, headers = self.fetch([path], token=None)[path]
+5
View File
@@ -149,6 +149,11 @@ class ListingTests(FolderCase):
self.assertEqual(place_inside(str(self.root) + "/", roots), ("input", ""))
self.assertEqual(place_inside(str(roots["output"] / "set"), roots), ("output", "set"))
self.assertEqual(place_inside(f'"{self.root / "people"}"', roots), ("input", "people"), "quotes from a copied path")
# A "~" path is never expanded into a real one, and no node code does that.
self.assertIsNone(place_inside("~/ComfyUI/input/people", roots))
nodes_dir = Path(__file__).resolve().parents[1] / "nodes"
for source in nodes_dir.glob("*.py"):
self.assertNotIn("expanduser", source.read_text(encoding="utf-8"), source.name)
def test_a_whole_path_anywhere_else_is_not_a_place(self):
roots = {"input": self.root, "output": Path(self.temp.name) / "output"}
+64 -3
View File
@@ -1,17 +1,20 @@
from __future__ import annotations
from datetime import datetime
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._image_hold_helpers import GONE, HELD_FOLDER, hold_pictures, keep_pictures
from nodes import _image_hold_helpers # noqa: E402
from nodes._image_hold_helpers import GONE, HELD_FOLDER, hold_pictures, keep_pictures # noqa: E402
NOW = datetime(2026, 11, 10, 9, 30, 0)
@@ -99,12 +102,70 @@ class HoldTests(unittest.TestCase):
def test_a_folder_outside_the_output_folder_is_refused_at_the_click_too(self):
token, _ = self.hold(count=1)
manifest = self.temp / HELD_FOLDER / f"{token}.json"
manifest.write_text(manifest.read_text().replace('"output_dir": ""', '"output_dir": "../elsewhere"'))
_image_hold_helpers._RUNS[token]["output_dir"] = "../elsewhere"
with self.assertRaises(ValueError):
self.keep(token)
self.assertFalse((Path(self.box.name) / "elsewhere").exists())
def test_a_run_planted_in_the_temp_folder_is_not_a_run(self):
# ComfyUI's temp folder takes uploads, so a file there can be
# anyone's. A planted list naming a server file must copy nothing.
secret = Path(self.box.name) / "secret.txt"
secret.write_text("server secret")
held = self.temp / HELD_FOLDER
held.mkdir(exist_ok=True)
token = "a" * 16
planted = dict(
settings(extension="png/../../../secret.txt", output_dir="x/y"), count=1, kept={},
)
(held / f"{token}.json").write_text(json.dumps(planted))
(held / f"{token}_000.png").mkdir() # an upload's subfolder makes the ".." walk work
with self.assertRaises(LookupError):
self.keep(token)
self.assertEqual(list(self.output.rglob("*")), [])
def test_a_held_picture_is_named_only_from_the_token_number_and_format(self):
token, previews = self.hold(count=1)
for extension in ["png/../../x", "txt", "", "PNG"]:
with self.assertRaises(ValueError):
_image_hold_helpers._held_name(token, 0, extension)
_image_hold_helpers._RUNS[token]["extension"] = "png/../../../secret.txt"
with self.assertRaises(ValueError):
self.keep(token)
self.assertEqual(list(self.output.iterdir()), [])
def test_a_picture_swapped_for_a_link_is_not_copied(self):
token, previews = self.hold(count=1)
secret = Path(self.box.name) / "secret.txt"
secret.write_text("server secret")
picture = self.temp / HELD_FOLDER / previews[0]["filename"]
picture.unlink()
try:
picture.symlink_to(secret)
except (OSError, NotImplementedError):
self.skipTest("no symlinks here")
with self.assertRaises(LookupError):
self.keep(token)
self.assertEqual(list(self.output.iterdir()), [])
def test_counts_are_capped(self):
with patch.object(_image_hold_helpers, "MAX_HELD_PICTURES", 4):
with self.assertRaises(ValueError):
self.hold(count=5)
token, _ = self.hold(count=2)
with self.assertRaises(ValueError):
self.keep(token, [0] * 5)
self.assertEqual(list(self.output.iterdir()), [])
def test_old_runs_are_forgotten_first(self):
with patch.object(_image_hold_helpers, "MAX_HELD_RUNS", 2):
oldest, _ = self.hold(count=1)
self.hold(count=1)
newest, _ = self.hold(count=1)
with self.assertRaises(LookupError):
self.keep(oldest)
self.assertEqual(len(self.keep(newest)["saved"]), 1)
if __name__ == "__main__":
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
"""Every video list a node offers from the input folder takes uploads.
The flag (`video_upload`) is what gives the field an Upload button in
ComfyUI's App mode and in Nodes 2.0. Without it the clip field in an App
mode form was a bare list with nothing to upload a clip with. Read from the
source, so ComfyUI does not have to be importable.
"""
from __future__ import annotations
import ast
from pathlib import Path
import unittest
NODES = Path(__file__).resolve().parent.parent / "nodes"
def video_lists():
for path in sorted(NODES.glob("node_*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Tuple) or not node.elts:
continue
first = node.elts[0]
if isinstance(first, ast.Call) and getattr(first.func, "id", "") == "list_input_videos":
options = node.elts[1] if len(node.elts) > 1 and isinstance(node.elts[1], ast.Dict) else None
flags = {}
if options is not None:
for key, value in zip(options.keys, options.values):
if isinstance(key, ast.Constant) and isinstance(value, ast.Constant):
flags[key.value] = value.value
yield path.name, node.lineno, flags
class VideoUploadFlag(unittest.TestCase):
def test_every_input_video_list_takes_uploads(self):
found = list(video_lists())
self.assertGreaterEqual(len(found), 3, "expected Load Video and both video crop nodes")
missing = [f"{name}:{line}" for name, line, flags in found if flags.get("video_upload") is not True]
self.assertEqual(missing, [], "video lists without video_upload: True")
if __name__ == "__main__":
unittest.main()
+24 -1
View File
@@ -43,6 +43,7 @@ function fixture({ size = [300, 80], floor = [210, 94], scale = 1 } = {}) {
querySelector() { return this; }
setAttribute() {}
setPointerCapture() {}
closest() { return null; }
remove() { this.removed = true; }
}
const root = new Element();
@@ -56,7 +57,7 @@ function fixture({ size = [300, 80], floor = [210, 94], scale = 1 } = {}) {
};
const source = readFileSync(new URL("../js/shared/tile_face.mjs", import.meta.url), "utf8")
.replace(/^import .*;\n/, "").replaceAll("export ", "");
const context = vm.createContext({ app, AbortController, document: { createElement: () => new Element() } });
const context = vm.createContext({ app, AbortController, CustomEvent, document: { createElement: () => new Element() } });
vm.runInContext(source, context);
context.setTileFace(node, root, true);
const grip = root.children[0];
@@ -103,3 +104,25 @@ test("keyboard resize supports fine steps, respects pinning and removes its hand
f.disable();
assert.equal(f.grip.removed, true);
});
test("a tile drag names its card for snapping and reports each move once placed", () => {
const f = fixture();
assert.equal(f.node.ausbossOutlineElement, f.root, "Snap into line measures the card, not the transparent node");
let stopped = 0;
const reports = [];
f.root.addEventListener("ausboss-tile-move", (event) => reports.push([...f.node.pos, event.detail.clientX]));
const send = (type, values = {}) => {
const event = new Event(type, { cancelable: true });
Object.assign(event, { button: 0, pointerId: 1, isPrimary: true, clientX: 0, clientY: 0, ...values });
if (type === "pointermove") event.stopPropagation = () => stopped++;
f.root.dispatchEvent(event);
};
send("pointerdown", { clientX: 10, clientY: 10 });
send("pointermove", { clientX: 60, clientY: 30 });
assert.deepEqual([...f.node.pos], [70, 50]);
assert.equal(stopped, 1, "the move stays with the tile, or Nodes 2.0 pans the canvas with it");
assert.deepEqual(reports, [[70, 50, 60]], "Snap into line hears the move after the tile is placed");
send("pointerup");
f.disable();
assert.equal(f.node.ausbossOutlineElement, undefined);
});
+16
View File
@@ -315,3 +315,19 @@ test("a wired 49-frame selection stops at IN 48 on the 97-frame pier clip", () =
assert.equal(clipLengthPlan(info, { ...values, resampled: true, outputFps: 12 }).latestStart, 0);
assert.equal(clipLengthPlan(info, { ...values, wired: "fixed_frames", outputFps: 24 }).latestStart, 48);
});
test('a linked 24 fps rate on a 60 fps clip: 48 frames from 1 s end at 3 s', () => {
const info = clipInfo({ fps: 60, frame_count: 247, duration: 247 / 60 });
const values = { start: 1, end: 0, everyNth: 1, frameSnap: 'free', maxFrames: 48, fixedFrames: 0, wired: null, wiredFrames: null, outputFps: 24, resampled: true };
const plan = clipLengthPlan(info, values);
assert.equal(plan.frames, 48);
assert.equal(plan.endSeconds, 3);
assert.equal(plan.last, 177);
assert.equal(plan.latestStart, 129);
// A 240-frame Length (10 s) only caps a 4.1 s clip: the source ends first.
const capped = clipLengthPlan(info, { ...values, maxFrames: 240 });
assert.equal(capped.truncated, true);
assert.equal(capped.frames, 75);
// Still unknown without a rate.
assert.equal(clipLengthPlan(info, { ...values, outputFps: null }).last, null);
});
+11
View File
@@ -106,3 +106,14 @@ test("hideInputsInDef never throws on frozen definitions", () => {
const frozenAll = Object.freeze({ input: Object.freeze({ required: Object.freeze({ seed: Object.freeze(["INT", Object.freeze({})]) }) }) });
assert.equal(hideInputsInDef(frozenAll, ["seed"]), 0);
});
test("show leaves no paint hooks behind that the widget never had", () => {
// Left as own `undefined` properties, the frontend took the widget for a
// custom-drawn one and App mode drew an empty row for it.
const widget = makeWidget();
hideWidget(widget);
showWidget(widget);
for (const key of ["computeSize", "computeLayoutSize", "draw"]) {
assert.equal(Object.prototype.hasOwnProperty.call(widget, key), false, key);
}
});
+13
View File
@@ -13,6 +13,7 @@ import {
groupModels,
hostLabel,
matchInstalled,
onlyCopy,
noteFit,
noteIsEmpty,
noteShowsTileFace,
@@ -332,3 +333,15 @@ test("note panels stand down the frontend image preview", () => {
assert.match(source, /import \{ suppressCoreImagePreview \} from "\.\.\/shared\/core_preview\.mjs";/, "the note imports the pack's preview suppression");
assert.match(source, /suppressCoreImagePreview\(node\);/, "building a note panel stands the core image preview down");
});
test("onlyCopy picks a file without asking only when there is one copy", () => {
const files = ["minimax-h3/model.safetensors", "a/lora.safetensors", "b/lora.safetensors", "vae.safetensors", "a\\Win.safetensors"];
assert.equal(onlyCopy("model.safetensors", files), "minimax-h3/model.safetensors");
assert.equal(onlyCopy("MODEL.safetensors", files), "minimax-h3/model.safetensors");
assert.equal(onlyCopy("lora.safetensors", files), null); // two copies: the user picks
assert.equal(onlyCopy("b/lora.safetensors", files), "b/lora.safetensors"); // the exact path wins
assert.equal(onlyCopy("vae.safetensors", files), "vae.safetensors");
assert.equal(onlyCopy("win.safetensors", files), "a/Win.safetensors");
assert.equal(onlyCopy("missing.safetensors", files), null);
assert.equal(onlyCopy("model.safetensors", []), null);
});