Compare commits

..

12 Commits

Author SHA1 Message Date
Connor Byrne
109fa9249f test(fixture): expose poll{Left,Top,Right,Bottom}Edge and poll{Width,Height}
Move the bounding-box edge accessors from local helpers in resize.spec
into the fixture so resize tests can read 'expect.poll(node.pollWidth)'
instead of repeating the inline 'async () => (await node.boundingBox()).X'
shape. The opposite-edge anchoring test now references node-bound poll
helpers directly and the per-test edge-of factories disappear from the
spec.

Addresses review feedback:
https://github.com/Comfy-Org/ComfyUI_frontend/pull/11408#discussion_r3107737141
2026-05-04 13:35:47 -07:00
bymyself
a29c36f3ec test(fixture): extract expectAnchoredAt for drift assertions
Wraps the polled bounding-box x/y assertions that drift tests duplicate
on each axis. Drift test now reads as 'select, anchor, resize, anchor'
instead of repeated polling boilerplate.

Addresses review feedback:
https://github.com/Comfy-Org/ComfyUI_frontend/pull/11408#discussion_r3184280358
2026-05-04 13:32:13 -07:00
bymyself
80735dac10 test: drive drift test through fixture's resizeFromCorner
Replaces the bespoke select-then-mouse-drag plumbing with the existing
fixture helpers (setupResizableNode + resizeFromCorner). Drops the
hand-computed corner offset and the raw page.mouse sequence so the
drift test follows the same shape as the parameterized cases.

Addresses review feedback:
https://github.com/Comfy-Org/ComfyUI_frontend/pull/11408#discussion_r3184276374
2026-05-04 13:31:21 -07:00
bymyself
3682ae2ac0 test(fixture): add selectAndGetBox helper to VueNodeFixture
Encapsulates the click-header-then-grab-bounding-box pattern that
geometry-sensitive tests need. Removes the inline header click and
bounding-box null check from setupResizableNode.

Addresses review feedback:
https://github.com/Comfy-Org/ComfyUI_frontend/pull/11408#discussion_r3184278489
2026-05-04 13:31:00 -07:00
bymyself
213bf7b4cb test: include SE in parameterized corner resize sweeps
Drop the SE filter and its 'Exercise every non-SE corner' explanation;
SE belongs in the same parameterized loops as the other three corners.

Addresses review feedback:
https://github.com/Comfy-Org/ComfyUI_frontend/pull/11408#discussion_r3184283386
2026-05-04 13:30:27 -07:00
jaeone94
d03013372d Merge branch 'main' into glary/resize-corner-e2e-tests 2026-05-02 15:51:08 +09:00
jaeone94
2fceb9b68a Merge branch 'main' into glary/resize-corner-e2e-tests 2026-04-29 22:21:50 +09:00
jaeone94
7c88b22ad3 test: address resize review feedback
- Replace English aria-label lookup with a data-corner attribute on the
  handle div; drop RESIZE_HANDLE_ARIA_LABELS_EN and its main.json
  import so resizeHandleConfig stays locale-independent
- Tighten NE clamp test: poll actual clamped height, then drive a second
  overdrag and assert height stays at the same lower bound (idempotent
  clamp). Rename test to match what it verifies; rename the inner box
  to expandedBox to avoid shadowing the setup fixture's box
- Restore Comfy.Minimap.Visible in afterEach so the override does not
  leak into other specs sharing the user-data-dir
- Normalize canvas state with canvasOps.resetView() in beforeEach so
  anchor assertions stay subpixel-stable regardless of prior pan/zoom
- Guard setupResizableNode with toHaveCount(1) so the helper fails
  loudly if the default workflow ever gains a duplicate title
- Add handle.hover() before the drag mouse sequence; Playwright's
  actionability checks now verify the handle is hit-testable
- Extract edge-coordinate pollers (leftEdgeOf / rightEdgeOf /
  topEdgeOf / bottomEdgeOf) to replace nested ternaries inside
  expect.poll callbacks
- Tag the suite with @canvas @node per the Playwright guidance
- Reword the parameterization comment to stop leaking the production
  switch statement as test rationale
- Drop the aria-label mirror test; add a completeness test that asserts
  RESIZE_HANDLES defines exactly one entry per CompassCorners
- JSDoc on hasWestEdge/hasNorthEdge and the fixture's resize helpers
2026-04-21 21:08:40 +09:00
jaeone94
f5a1c724e6 refactor: share resize corner helpers across production and E2E
- Expose hasWestEdge, hasNorthEdge, and RESIZE_HANDLE_ARIA_LABELS_EN
  from resizeHandleConfig so useNodeResize and the VueNodeFixture
  consume a single source per corner; resolve English labels from
  main.json instead of hardcoding a duplicate map in tests
- Replace activeCorner.includes('W'|'N') substring checks in
  useNodeResize with the new helpers
- Drop nextFrame from resizeFromCorner; call sites rely on expect.poll
- Disable Comfy.Minimap.Visible in the resize spec's beforeEach so the
  minimap overlay does not hijack handle pointer events mid-drag and
  trigger forwardPanEvent on the LGraphCanvas
- Target KSampler (center-positioned with open canvas around it) for
  corner-resize cases; pre-expand via SE before NE clamp so there is
  room to shrink below minContentHeight
- Replace the redundant runtime corner-existence guard with the
  exhaustive CompassCorners union; extract setupResizableNode to drop
  repeated header-click + boundingBox scaffolding
- Unit tests cover the new helpers and verify aria-label resolution
  stays in sync with the handles' i18nKey values
2026-04-21 20:40:59 +09:00
Glary-Bot
c77bccefea test: add nextFrame after resize, tighten min-size assertions
- resizeFromCorner() now waits one frame after mouse up for layout
  settlement, preventing intermittent failures
- SW width clamp asserts >= MIN_NODE_WIDTH instead of > 0
- NE height clamp asserts < original height (actual shrinkage)
2026-04-19 08:15:54 +00:00
Glary-Bot
77c69cf931 test: add upfront guard against silent corner removal
Fail loudly if RESIZE_HANDLES drops a corner, preventing the
parameterized tests from silently losing coverage.
2026-04-19 08:06:00 +00:00
Glary-Bot
c84fa6ac39 test: add E2E coverage for NE, SW, NW corner node resizing
Adds parameterized Playwright tests covering all non-SE resize
corners, derived from the production RESIZE_HANDLES config.

- Add resizeFromCorner() and getResizeHandle() to VueNodeFixture
  using locator-based aria-label handle discovery
- Corner resize direction tests (NE, SW, NW)
- Opposite edge anchoring tests
- Minimum size enforcement tests (SW width clamp, NE height clamp)
2026-04-19 08:00:04 +00:00
44 changed files with 580 additions and 2152 deletions

View File

@@ -1,58 +0,0 @@
# Comfy
> Comfy is the AI creation engine for visual professionals who demand control over every model, every parameter, and every output. Built around ComfyUI — the open-source node-graph runtime with 60,000+ community nodes and thousands of shared workflows — Comfy ships as a free local app, a managed cloud, an API, and an enterprise platform.
The Comfy ecosystem spans four surfaces:
- **ComfyUI (local)** — the open-source node-graph runtime that runs models on your own hardware.
- **Comfy Cloud** — managed ComfyUI in the browser, with hosted models and storage.
- **Comfy API** — a REST API for triggering workflows from your own apps and pipelines.
- **Comfy Enterprise** — single-tenant deployments, BYO keys, data ownership, and orchestration for teams.
Studios building with Comfy include Series Entertainment, Moment Factory, Open Story Movement, and Ubisoft (La Forge). Use cases concentrate in VFX & animation, advertising & creative studios, gaming, and eCommerce/fashion.
## Product
- [Homepage](https://comfy.org/): Overview of Comfy and the four product surfaces (Local, Cloud, API, Enterprise).
- [Download Comfy (Local)](https://comfy.org/download/): Free desktop app for macOS, Windows, and Linux — runs ComfyUI on your own GPU.
- [Comfy Cloud](https://comfy.org/cloud/): Managed ComfyUI in the browser with hosted models and storage; no local install required.
- [Comfy Cloud Pricing](https://comfy.org/cloud/pricing/): Plans and per-credit pricing for individuals and teams using Comfy Cloud.
- [Comfy API](https://comfy.org/api/): REST API for triggering ComfyUI workflows programmatically from external apps.
- [Comfy Enterprise](https://comfy.org/cloud/enterprise/): Single-tenant ComfyUI deployments with BYO keys, orchestration, and data-ownership guarantees.
## Workflows and Gallery
- [Workflow Gallery](https://comfy.org/gallery/): Curated showcase of ComfyUI outputs — images, video, and 3D — produced by the community.
- [Community Workflows](https://www.comfy.org/workflows/): Browseable library of community-shared ComfyUI workflows you can load and remix.
## Customers and Case Studies
- [Customer Stories](https://comfy.org/customers/): Index of named customers and how they use ComfyUI in production.
- [Series Entertainment](https://comfy.org/customers/series-entertainment/): How Series Entertainment rebuilt game and video production around ComfyUI.
- [Moment Factory](https://comfy.org/customers/moment-factory/): Architectural-scale 3D projection mapping reimagined with ComfyUI at Moment Factory.
- [Ubisoft — Chord](https://comfy.org/customers/ubisoft-chord/): Ubisoft La Forge open-sourcing the Chord model and its ComfyUI integration.
- [Open Story Movement](https://comfy.org/customers/open-story-movement/): How an open-source movement around AI storytelling builds on ComfyUI.
## Developers and Documentation
- [ComfyUI Docs](https://docs.comfy.org/): Official documentation for installing, configuring, and extending ComfyUI.
- [ComfyUI on GitHub](https://github.com/comfyanonymous/ComfyUI): Source repository for the open-source ComfyUI runtime.
- [Comfy-Org on GitHub](https://github.com/Comfy-Org): Organization-wide repositories — frontend, registry, manager, docs, and tooling.
- [Comfy Registry](https://registry.comfy.org/): Public registry of ComfyUI custom nodes and extensions, with versioning and search.
## Company
- [About Comfy](https://comfy.org/about/): Company background, mission, and the team behind ComfyUI.
- [Careers](https://comfy.org/careers/): Open roles across engineering, design, product, and go-to-market.
- [Contact](https://comfy.org/contact/): Sales, partnership, and general contact form.
- [Blog](https://blog.comfy.org/): Product announcements, technical deep-dives, and customer stories.
- [Privacy Policy](https://comfy.org/privacy-policy/): How Comfy collects, uses, and protects personal information.
- [Terms of Service](https://comfy.org/terms-of-service/): Terms governing use of ComfyUI and related Comfy services.
## Optional
- [简体中文 / Chinese homepage](https://comfy.org/zh-CN/): Simplified Chinese localization of the main site.
- [Series Entertainment — long-form case study](https://comfy.org/cloud/enterprise-case-studies/how-series-entertainment-rebuilt-game-and-video-production-with-comfyui): Extended write-up of the Series Entertainment deployment.
- [Moment Factory — long-form case study](https://comfy.org/cloud/enterprise-case-studies/comfyui-at-architectural-scale-how-moment-factory-reimagined-3d-projection-mapping): Extended write-up of Moment Factory's projection-mapping pipeline.
- [Ubisoft Chord announcement (blog)](https://blog.comfy.org/p/ubisoft-open-sources-the-chord-model): Original blog post announcing Ubisoft's open-source Chord model.
- [Open-source storytelling (blog)](https://blog.comfy.org/p/how-open-source-is-fueling-the-open): Blog post on how open source is fueling the Open Story Movement.

View File

@@ -1,8 +1,6 @@
<script setup lang="ts">
import type { Locale } from '../../i18n/translations'
import { externalLinks } from '../../config/routes'
import { t } from '../../i18n/translations'
import BrandButton from '../common/BrandButton.vue'
const { locale = 'en' } = defineProps<{ locale?: Locale }>()
</script>
@@ -34,15 +32,6 @@ const { locale = 'en' } = defineProps<{ locale?: Locale }>()
>
{{ t('hero.subtitle', locale) }}
</p>
<BrandButton
:href="externalLinks.workflows"
variant="outline"
size="lg"
class="mt-8 w-full p-4 uppercase lg:w-auto lg:min-w-60"
>
{{ t('hero.runFirstWorkflow', locale) }}
</BrandButton>
</div>
</section>
</template>

View File

@@ -52,15 +52,6 @@ export const customerStories: CustomerStory[] = [
detailPrefix: 'customers.detail.ubisoft-chord',
readMoreHref:
'https://blog.comfy.org/p/ubisoft-open-sources-the-chord-model'
},
{
slug: 'groove-jones',
image:
'https://media.comfy.org/website/customers/groove-jones/crocs-nfl-dicks-sporting-goods-fooh.webp',
category: 'customers.story.groove-jones.category',
title: 'customers.story.groove-jones.title',
body: 'customers.story.groove-jones.body',
detailPrefix: 'customers.detail.groove-jones'
}
]

View File

@@ -11,10 +11,6 @@ const translations = {
'zh-CN':
'Comfy 是面向专业视觉人士的 AI 创作引擎。您可以精确掌控每个模型、每个参数和每个输出。'
},
'hero.runFirstWorkflow': {
en: 'Run your first workflow',
'zh-CN': '运行你的第一个工作流'
},
// ProductShowcaseSection
'showcase.subtitle1': {
@@ -2247,20 +2243,6 @@ const translations = {
'zh-CN':
'育碧 La Forge 开源了 CHORD PBR 材质估算模型及 ComfyUI 自定义节点,为 AAA 游戏制作实现了端到端的纹理生成工作流。'
},
'customers.story.groove-jones.category': {
en: 'CASE STUDY',
'zh-CN': '案例研究'
},
'customers.story.groove-jones.title': {
en: "How Groove Jones Delivered a Holiday FOOH Campaign for Dick's Sporting Goods with Comfy",
'zh-CN':
"Groove Jones 如何借助 Comfy 为 Dick's Sporting Goods 打造节日 FOOH 营销"
},
'customers.story.groove-jones.body': {
en: 'Groove Jones, a Dallas-based creative studio, used Comfy to deliver a hyper-realistic FOOH holiday campaign for the Crocs x NFL collection on a fast-approaching deadline.',
'zh-CN':
'达拉斯创意工作室 Groove Jones 借助 Comfy在紧迫的节日档期内为 Crocs x NFL 联名系列交付了超写实的 FOOH 营销内容。'
},
'customers.story.readMore': {
en: 'READ MORE ON THIS TOPIC',
'zh-CN': '阅读更多相关内容'
@@ -3294,227 +3276,6 @@ const translations = {
'zh-CN': 'ComfyUI 博客'
},
// Customer Detail: Groove Jones
// Topic 1: Intro
'customers.detail.groove-jones.topic-1.label': {
en: 'INTRO',
'zh-CN': '简介'
},
'customers.detail.groove-jones.topic-1.block.0': {
en: 'Groove Jones, a Dallas-based creative studio, builds AI-driven campaigns and immersive experiences for major brands where photoreal polish, creative ambition, and social-ready speed all have to land together. As their work expanded across AI Video, AR, VR, and WebGL for clients like Crocs, the NFL, and Dick\u2019s Sporting Goods, they faced a recurring challenge: delivering feature-film-quality VFX on commercial timelines and budgets.',
'zh-CN':
'位于达拉斯的创意工作室 Groove Jones为众多大牌客户打造由 AI 驱动的营销活动和沉浸式体验,需要同时兼顾照片级的精细度、创意野心,以及适配社交媒体的交付速度。随着他们为 Crocs、NFL 和 Dick\u2019s Sporting Goods 等客户的工作扩展到 AI 视频、AR、VR 和 WebGL他们反复遇到同一个挑战用商业项目的工期和预算交付电影级的 VFX 质量。'
},
'customers.detail.groove-jones.topic-1.block.1': {
en: 'For the Crocs x NFL collection holiday launch, that challenge came to a head. The brief called for hyper-realistic video of giant NFL-licensed Crocs parachuting into real Dick\u2019s Sporting Goods parking lots, across multiple locations, delivered on a fast-approaching holiday deadline. A live-action shoot plus a traditional CG pipeline was off the table.',
'zh-CN':
'在 Crocs x NFL 联名系列的节日上市项目中这个挑战被推到了极致。Brief 要求制作超写实视频:巨型 NFL 授权 Crocs 鞋款跳伞落入多个真实的 Dick\u2019s Sporting Goods 停车场,并要在紧迫的节日档期前交付。实地拍摄加传统 CG 流水线的方案,已经完全行不通。'
},
// Topic 2: The Output
'customers.detail.groove-jones.topic-2.label': {
en: 'THE OUTPUT',
'zh-CN': '交付成果'
},
'customers.detail.groove-jones.topic-2.title': {
en: 'The Output Groove Jones Achieved Using Comfy',
'zh-CN': 'Groove Jones 借助 Comfy 实现的交付成果'
},
'customers.detail.groove-jones.topic-2.block.0': {
en: 'A full FOOH (faux out-of-home) social campaign delivered on a tight holiday deadline\nHyper-realistic videos of giant NFL-licensed Crocs parachuting onto Dick\u2019s Sporting Goods parking lots\nVertical 9:16 deliverables at 2K for Instagram Reels, TikTok, and YouTube Shorts\nSame-day iteration on client notes instead of week-long asset updates\nWinner, Aaron Awards 2024: Best AI Workflow for Production',
'zh-CN':
'在紧迫的节日档期内交付完整的 FOOH虚构户外广告社媒营销活动\n超写实视频巨型 NFL 授权 Crocs 鞋款跳伞落入 Dick\u2019s Sporting Goods 停车场\n面向 Instagram Reels、TikTok、YouTube Shorts 的 9:16 竖屏 2K 交付物\n客户反馈当天迭代不再需要数周的资产更新周期\n荣获 2024 年 Aaron Awards最佳 AI 制作工作流奖'
},
// Topic 3: The Problem
'customers.detail.groove-jones.topic-3.label': {
en: 'THE PROBLEM',
'zh-CN': '挑战'
},
'customers.detail.groove-jones.topic-3.title': {
en: 'The Problem Groove Jones Was Trying to Solve',
'zh-CN': 'Groove Jones 试图解决的问题'
},
'customers.detail.groove-jones.topic-3.block.0': {
en: 'A traditional pipeline for this creative meant a live-action shoot at multiple store locations plus a full CG build: high-res modeling of every team\u2019s clog, look development, lighting, rendering, compositing, and a new render every time the client wanted a variation. It also meant a large crew (modelers, texture artists, lighting artists, compositors) and a schedule measured in months. Neither the budget nor the holiday window supported that path.',
'zh-CN':
'按照传统流水线做这个创意,意味着要在多家门店实地拍摄,加上完整的 CG 制作每支球队鞋款的高精建模、look development、灯光、渲染、合成客户每次想要新变体都要重新渲染。这也意味着庞大的团队建模师、纹理师、灯光师、合成师以及以"月"为单位的工期。无论是预算还是节日档期,都无法支撑这条路径。'
},
// Topic 4: How Comfy Solved the Problem
'customers.detail.groove-jones.topic-4.label': {
en: 'HOW COMFY SOLVED THE PROBLEM',
'zh-CN': 'Comfy 如何解决问题'
},
'customers.detail.groove-jones.topic-4.title': {
en: 'How Groove Jones Used Comfy to Solve the Problem',
'zh-CN': 'Groove Jones 如何用 Comfy 解决问题'
},
'customers.detail.groove-jones.topic-4.block.0': {
en: 'Groove Jones\u2019s Senior Creative Technologist, Doug Hogan, rebuilt the production process around Comfy\u2019s node-based workflow system, using their proprietary GrooveTech GenVFX pipeline. Custom LoRAs handled brand accuracy, a single Comfy graph orchestrated multiple generative models, and Nuke handled final polish. For a team with feature-film and commercial roots, the environment was immediately familiar.',
'zh-CN':
'Groove Jones 的高级创意技术总监 Doug Hogan 围绕 Comfy 的节点式工作流系统重新搭建了制作流程,并基于他们自研的 GrooveTech GenVFX 流水线展开。自定义 LoRA 负责保证品牌一致性,一张 Comfy 图编排多个生成模型Nuke 负责最终精修。对于有电影和广告制作背景的团队,这套环境上手没有任何门槛。'
},
'customers.detail.groove-jones.topic-4.block.1.text': {
en: 'Comfy felt very similar to working inside a traditional CG and compositing pipeline. Node-based logic, clear data flow, modular builds. It felt natural to our artists already.',
'zh-CN':
'Comfy 用起来非常像传统 CG 和合成流水线:节点逻辑、清晰的数据流、模块化构建。我们的艺术家用起来毫无违和感。'
},
'customers.detail.groove-jones.topic-4.block.1.name': {
en: 'Doug Hogan | Senior Creative Technologist @ Groove Jones',
'zh-CN': 'Doug Hogan | Groove Jones 高级创意技术总监'
},
// Topic 5: Brand-Trained LoRAs
'customers.detail.groove-jones.topic-5.label': {
en: 'BRAND-TRAINED LORAS',
'zh-CN': '品牌定制 LORA'
},
'customers.detail.groove-jones.topic-5.title': {
en: 'Brand-Trained LoRAs for Hero Assets',
'zh-CN': '为主视觉资产定制的品牌 LoRA'
},
'customers.detail.groove-jones.topic-5.block.0': {
en: 'Groove Jones trained custom LoRAs on the Crocs NFL Team Clogs and on Dick\u2019s Sporting Goods storefronts, so every generation came out anchored in brand-accurate references. Real team colorways, real product silhouettes, and real store exteriors stayed consistent across shots without per-frame correction, replacing what would normally take weeks of manual look development.',
'zh-CN':
'Groove Jones 基于 Crocs NFL 球队联名鞋款和 Dick\u2019s Sporting Goods 门店外景训练了定制 LoRA让每一次生成都能锚定品牌精准的参考素材。真实的球队配色、产品轮廓和门店外观在不同镜头之间保持一致不需要逐帧修正——而这通常意味着数周的 look development 工作量。'
},
'customers.detail.groove-jones.topic-5.block.1.src': {
en: 'https://media.comfy.org/website/customers/groove-jones/nfl-crocs-team-lineup.webp',
'zh-CN':
'https://media.comfy.org/website/customers/groove-jones/nfl-crocs-team-lineup.webp'
},
'customers.detail.groove-jones.topic-5.block.1.alt': {
en: 'Grid of brand-accurate NFL team Crocs generated via custom LoRAs',
'zh-CN': '通过定制 LoRA 生成的多支 NFL 球队联名 Crocs 网格'
},
'customers.detail.groove-jones.topic-5.block.1.caption': {
en: 'Brand-accurate NFL team colorways generated through custom LoRAs.',
'zh-CN': '通过定制 LoRA 生成的、与品牌精准一致的 NFL 球队配色。'
},
// Topic 6: Multi-Model Orchestration
'customers.detail.groove-jones.topic-6.label': {
en: 'MULTI-MODEL ORCHESTRATION',
'zh-CN': '多模型编排'
},
'customers.detail.groove-jones.topic-6.title': {
en: 'Multi-Model Orchestration in a Single Graph',
'zh-CN': '单张图内的多模型编排'
},
'customers.detail.groove-jones.topic-6.block.0': {
en: 'The creative required different generative models at different stages: Flux for key-frame still development, Gemini Flash 2.5 (Nano Banana) for fast ideation and variants, and Veo 3.1 plus Moonvalley\u2019s Marey for final video generation. Comfy routed between all four inside one graph, so outputs from one model fed directly into the next without ever leaving the environment.',
'zh-CN':
'这个创意在不同阶段需要不同的生成模型Flux 用于关键帧静帧开发Gemini Flash 2.5Nano Banana用于快速构思和变体生成Veo 3.1 加上 Moonvalley 的 Marey 用于最终的视频生成。Comfy 在一张图里就把这四个模型串起来,前一个模型的输出直接喂给下一个模型,全程无需切换环境。'
},
'customers.detail.groove-jones.topic-6.block.1.text': {
en: 'The Comfy community develops at an almost exponential curve, and we were able to leverage their existing nodes and tools to solve very specific production challenges instead of reinventing the wheel ourselves.',
'zh-CN':
'Comfy 社区几乎是指数级增长的,我们可以直接利用社区已有的节点和工具去解决非常具体的制作问题,而不必自己重新造轮子。'
},
'customers.detail.groove-jones.topic-6.block.1.name': {
en: 'Dale Carman | Co-founder @ Groove Jones',
'zh-CN': 'Dale Carman | Groove Jones 联合创始人'
},
// Topic 7: The Pipeline
'customers.detail.groove-jones.topic-7.label': {
en: 'THE PIPELINE',
'zh-CN': '流水线'
},
'customers.detail.groove-jones.topic-7.title': {
en: 'Storyboards to Previz to Final Shot in One Pipeline',
'zh-CN': '从故事板到 Previz 再到成片,全部在一条流水线内'
},
'customers.detail.groove-jones.topic-7.block.0': {
en: 'The workflow opened with traditional storyboards for narrative approval, then moved into CGI blocking to lock composition, camera framing, and story beats. Comfy drove generation from there: the shoe drop, the parking lot reactions, the crowd coverage, and the environmental conversions that turned static summer storefronts into snow-covered holiday scenes, all inside the same graph.',
'zh-CN':
'工作流从传统故事板开始用于叙事确认,再进入 CGI blocking锁定构图、镜头取景和叙事节奏。从这里开始 Comfy 接管生成:鞋款空投、停车场反应镜头、人群覆盖、把夏季静态门店外景转换成被雪覆盖的节日场景——全部在同一张图里完成。'
},
'customers.detail.groove-jones.topic-7.block.1.src': {
en: 'https://media.comfy.org/website/customers/groove-jones/nfl-crocs-dicks-storyboards.webp',
'zh-CN':
'https://media.comfy.org/website/customers/groove-jones/nfl-crocs-dicks-storyboards.webp'
},
'customers.detail.groove-jones.topic-7.block.1.alt': {
en: 'Storyboard grid for the Crocs x NFL holiday campaign',
'zh-CN': 'Crocs x NFL 节日营销的故事板网格'
},
'customers.detail.groove-jones.topic-7.block.1.caption': {
en: 'Grayscale storyboards used to lock narrative beats before generation.',
'zh-CN': '在生成之前用于锁定叙事节奏的灰度故事板。'
},
'customers.detail.groove-jones.topic-7.block.2.src': {
en: 'https://media.comfy.org/website/customers/groove-jones/nfl-crocs-fooh-sequence.webp',
'zh-CN':
'https://media.comfy.org/website/customers/groove-jones/nfl-crocs-fooh-sequence.webp'
},
'customers.detail.groove-jones.topic-7.block.2.alt': {
en: 'Composition progression from blocking to mid-render to final shot',
'zh-CN': '从 blocking 到中间渲染再到最终镜头的构图演进'
},
'customers.detail.groove-jones.topic-7.block.2.caption': {
en: 'Composition progression: wireframe blocking, mid-render, and final shot.',
'zh-CN': '构图演进:线框 blocking、中间渲染、最终成片。'
},
// Topic 8: Version Control
'customers.detail.groove-jones.topic-8.label': {
en: 'VERSION CONTROL',
'zh-CN': '版本管理'
},
'customers.detail.groove-jones.topic-8.title': {
en: 'Workflow Files as Version Control',
'zh-CN': '把工作流文件当作版本管理'
},
'customers.detail.groove-jones.topic-8.block.0': {
en: 'Every variant of every shot lived as a Comfy workflow file, which doubled as version control. When notes came in requesting a different team colorway, store exterior, or time of day, the team duplicated a branch instead of rebuilding, which made same-day iteration possible. GPU usage and API credit burn were trackable inside the same environment as the work itself, giving Production real-time visibility into compute cost per iteration.',
'zh-CN':
'每个镜头的每个变体都以 Comfy 工作流文件的形式存在,文件本身就是版本管理。当客户反馈要求换一支球队配色、换一个门店外景或者换一个时间段时,团队只需复制一个分支,而不是重建——这才让"当天迭代"成为可能。GPU 使用量和 API 额度消耗也都能在同一个环境里追踪到,让制作部门实时看到每次迭代的算力成本。'
},
// Topic 9: Finishing in Nuke
'customers.detail.groove-jones.topic-9.label': {
en: 'FINISHING IN NUKE',
'zh-CN': 'Nuke 终修'
},
'customers.detail.groove-jones.topic-9.title': {
en: 'Finishing in Nuke',
'zh-CN': '在 Nuke 中完成终修'
},
'customers.detail.groove-jones.topic-9.block.0': {
en: 'Generated shots moved into Nuke for final compositing: falling snow, camera shake, crowd ambience, holiday audio, and 2K mastering in 9:16 for Instagram Reels, TikTok, and YouTube Shorts. Because Comfy handled generation cleanly, Nuke focused on polish and motion enhancement rather than patching generative artifacts.',
'zh-CN':
'生成的镜头进入 Nuke 完成最终合成:飘雪、镜头抖动、人群环境音、节日氛围音效,以及面向 Instagram Reels、TikTok、YouTube Shorts 的 9:16 2K 母带。由于 Comfy 把生成环节处理得很干净Nuke 可以专注于精修和动态增强,而不是去修补生成模型留下的瑕疵。'
},
// Topic 10: The Takeaway
'customers.detail.groove-jones.topic-10.label': {
en: 'THE TAKEAWAY',
'zh-CN': '总结'
},
'customers.detail.groove-jones.topic-10.title': {
en: 'Conclusion',
'zh-CN': '结语'
},
'customers.detail.groove-jones.topic-10.block.0': {
en: 'By building the FOOH pipeline inside Comfy, Groove Jones turned a brief that would have required an expensive live-action shoot plus months of CG into a fast, iterative, single-environment workflow the client could direct in real time. The project recently won the Aaron Award for Best AI Workflow for Production.',
'zh-CN':
'通过在 Comfy 中搭建整套 FOOH 流水线Groove Jones 把一个原本需要昂贵实地拍摄加数月 CG 制作的项目,变成了一套高速迭代、单一环境、客户可以实时指挥的工作流。该项目近期还荣获 Aaron Award 的"最佳 AI 制作工作流"奖。'
},
'customers.detail.groove-jones.topic-10.block.1.text': {
en: 'At Groove Jones, we care deeply about delivering work that makes people say WOW! But we also care about delivering on time and on budget. VFX projects used to operate at razor thin margins. Comfy solved that for us.',
'zh-CN':
'在 Groove Jones我们非常在意交付让人说"WOW"的作品但我们同样在意按时按预算交付。VFX 项目以前的利润率薄得像刀刃Comfy 帮我们彻底解决了这个问题。'
},
'customers.detail.groove-jones.topic-10.block.1.name': {
en: 'Dale Carman | Co-founder @ Groove Jones',
'zh-CN': 'Dale Carman | Groove Jones 联合创始人'
},
'customers.detail.groove-jones.topic-10.block.2.label': {
en: 'GROOVE JONES CONTRIBUTORS',
'zh-CN': 'GROOVE JONES 贡献者'
},
'customers.detail.groove-jones.topic-10.block.2.name': {
en: 'TBD',
'zh-CN': '待补充'
},
'customers.detail.groove-jones.topic-10.block.2.role': {
en: 'TBD',
'zh-CN': '待补充'
},
// Contact FormSection
'contact.form.badge': {
en: 'CONTACT SALES',

View File

@@ -1,8 +1,16 @@
import { expect } from '@playwright/test'
import type { Locator } from '@playwright/test'
import type { CompassCorners } from '@/lib/litegraph/src/interfaces'
import { TitleEditor } from '@e2e/fixtures/components/TitleEditor'
import { TestIds } from '@e2e/fixtures/selectors'
interface BoxOrigin {
readonly x: number
readonly y: number
}
/** DOM-centric helper for a single Vue-rendered node on the canvas. */
export class VueNodeFixture {
public readonly header: Locator
@@ -46,4 +54,100 @@ export class VueNodeFixture {
boundingBox(): ReturnType<Locator['boundingBox']> {
return this.locator.boundingBox()
}
/**
* Click the node header to select it, then return its bounding box.
* Throws if the node is not laid out (no bounding box) — resize and other
* geometry-sensitive tests cannot proceed without coordinates.
*/
async selectAndGetBox(): Promise<{
x: number
y: number
width: number
height: number
}> {
await this.header.click()
const box = await this.boundingBox()
if (!box) {
throw new Error('Node bounding box not found after select')
}
return box
}
/**
* Assert this node's top-left origin stays within `precision` decimal
* places of `expected`. Wraps the polled bounding-box pattern that drift
* tests repeat for both axes.
*/
async expectAnchoredAt(
expected: BoxOrigin,
{ precision = 1 }: { precision?: number } = {}
): Promise<void> {
await expect.poll(this.pollLeftEdge).toBeCloseTo(expected.x, precision)
await expect.poll(this.pollTopEdge).toBeCloseTo(expected.y, precision)
}
/** Poll the node's left/x edge for use with `expect.poll`. */
pollLeftEdge = async (): Promise<number | null> =>
(await this.boundingBox())?.x ?? null
/** Poll the node's top/y edge for use with `expect.poll`. */
pollTopEdge = async (): Promise<number | null> =>
(await this.boundingBox())?.y ?? null
/** Poll the node's right edge (x + width) for use with `expect.poll`. */
pollRightEdge = async (): Promise<number | null> => {
const b = await this.boundingBox()
return b ? b.x + b.width : null
}
/** Poll the node's bottom edge (y + height) for use with `expect.poll`. */
pollBottomEdge = async (): Promise<number | null> => {
const b = await this.boundingBox()
return b ? b.y + b.height : null
}
/** Poll the node's width for use with `expect.poll`. */
pollWidth = async (): Promise<number | null> =>
(await this.boundingBox())?.width ?? null
/** Poll the node's height for use with `expect.poll`. */
pollHeight = async (): Promise<number | null> =>
(await this.boundingBox())?.height ?? null
/** Locator for the resize handle at the given corner, scoped to this node. */
getResizeHandle(corner: CompassCorners): Locator {
return this.root.locator(`[data-corner="${corner}"]`)
}
/**
* Drag the resize handle at `corner` by (deltaX, deltaY) viewport pixels.
* Uses `hover()` to land the pointer on the handle with Playwright's
* actionability checks before starting the mouse sequence, which protects
* against occluding overlays and subpixel hit-test misses.
*/
async resizeFromCorner(
corner: CompassCorners,
deltaX: number,
deltaY: number
): Promise<void> {
const handle = this.getResizeHandle(corner)
await handle.hover()
const box = await handle.boundingBox()
if (!box) {
throw new Error(
`Resize handle for corner "${corner}" has no bounding box`
)
}
const page = this.locator.page()
const startX = box.x + box.width / 2
const startY = box.y + box.height / 2
await page.mouse.move(startX, startY)
await page.mouse.down()
await page.mouse.move(startX + deltaX, startY + deltaY, {
steps: 5
})
await page.mouse.up()
}
}

View File

@@ -1,56 +1,165 @@
import type { ComfyPage } from '@e2e/fixtures/ComfyPage'
import {
comfyExpect as expect,
comfyPageFixture as test
} from '@e2e/fixtures/ComfyPage'
import { MIN_NODE_WIDTH } from '@/renderer/core/layout/transform/graphRenderTransform'
import {
RESIZE_HANDLES,
hasNorthEdge,
hasWestEdge
} from '@/renderer/extensions/vueNodes/interactions/resize/resizeHandleConfig'
test.describe('Vue Node Resizing', { tag: '@vue-nodes' }, () => {
test('should resize node without position drift after selecting', async ({
comfyPage
}) => {
// Get a Vue node fixture
const node = await comfyPage.vueNodes.getFixtureByTitle('Load Checkpoint')
const initialBox = await node.boundingBox()
if (!initialBox) throw new Error('Node bounding box not found')
async function setupResizableNode(comfyPage: ComfyPage, title: string) {
await expect(comfyPage.vueNodes.getNodeByTitle(title)).toHaveCount(1)
const node = await comfyPage.vueNodes.getFixtureByTitle(title)
const box = await node.selectAndGetBox()
return { node, box }
}
// Select the node first (this was causing the bug)
await node.header.click()
test.describe(
'Vue Node Resizing',
{ tag: ['@vue-nodes', '@canvas', '@node'] },
() => {
let originalMinimapVisible: boolean | undefined
// Get position after selection
const selectedBox = await node.boundingBox()
if (!selectedBox)
throw new Error('Node bounding box not found after select')
// Minimap overlays the canvas and intercepts pointer events that land in
// its hit area during resize drags, so disable it for this suite. Capture
// and restore the prior value to avoid leaking the override to other specs
// that run on the same user-data-dir.
test.beforeEach(async ({ comfyPage }) => {
originalMinimapVisible = await comfyPage.settings.getSetting<boolean>(
'Comfy.Minimap.Visible'
)
await comfyPage.settings.setSetting('Comfy.Minimap.Visible', false)
await comfyPage.canvasOps.resetView()
})
// Verify position unchanged after selection
await expect
.poll(async () => (await node.boundingBox())?.x)
.toBeCloseTo(initialBox.x, 1)
await expect
.poll(async () => (await node.boundingBox())?.y)
.toBeCloseTo(initialBox.y, 1)
test.afterEach(async ({ comfyPage }) => {
if (originalMinimapVisible !== undefined) {
await comfyPage.settings.setSetting(
'Comfy.Minimap.Visible',
originalMinimapVisible
)
}
})
// Now resize from bottom-right corner
const resizeStartX = selectedBox.x + selectedBox.width - 5
const resizeStartY = selectedBox.y + selectedBox.height - 5
test('should resize node without position drift after selecting', async ({
comfyPage
}) => {
const { node, box: initialBox } = await setupResizableNode(
comfyPage,
'Load Checkpoint'
)
await comfyPage.page.mouse.move(resizeStartX, resizeStartY)
await comfyPage.page.mouse.down()
await comfyPage.page.mouse.move(resizeStartX + 50, resizeStartY + 30)
await comfyPage.page.mouse.up()
await node.expectAnchoredAt(initialBox)
// Position should NOT have changed (the bug was position drift)
await expect
.poll(async () => (await node.boundingBox())?.x)
.toBeCloseTo(initialBox.x, 1)
await expect
.poll(async () => (await node.boundingBox())?.y)
.toBeCloseTo(initialBox.y, 1)
await node.resizeFromCorner('SE', 50, 30)
// Size should have increased
await expect
.poll(async () => (await node.boundingBox())?.width)
.toBeGreaterThan(initialBox.width)
await expect
.poll(async () => (await node.boundingBox())?.height)
.toBeGreaterThan(initialBox.height)
})
})
await node.expectAnchoredAt(initialBox)
await expect.poll(node.pollWidth).toBeGreaterThan(initialBox.width)
await expect.poll(node.pollHeight).toBeGreaterThan(initialBox.height)
})
const cornerCases = RESIZE_HANDLES.map((h) => ({
corner: h.corner,
dragX: hasWestEdge(h.corner) ? -50 : 50,
dragY: hasNorthEdge(h.corner) ? -40 : 40
}))
test.describe('corner resize directions', () => {
cornerCases.forEach(({ corner, dragX, dragY }) => {
test(`${corner}: size increases and correct edges shift`, async ({
comfyPage
}) => {
const { node, box } = await setupResizableNode(comfyPage, 'KSampler')
await node.resizeFromCorner(corner, dragX, dragY)
await expect.poll(node.pollWidth).toBeGreaterThan(box.width)
await expect.poll(node.pollHeight).toBeGreaterThan(box.height)
if (hasWestEdge(corner)) {
await expect.poll(node.pollLeftEdge).toBeLessThan(box.x)
} else {
await expect.poll(node.pollLeftEdge).toBeCloseTo(box.x, 0)
}
if (hasNorthEdge(corner)) {
await expect.poll(node.pollTopEdge).toBeLessThan(box.y)
} else {
await expect.poll(node.pollTopEdge).toBeCloseTo(box.y, 0)
}
})
})
})
test.describe('opposite edge anchoring', () => {
cornerCases.forEach(({ corner, dragX, dragY }) => {
test(`${corner} resize keeps opposite corner fixed`, async ({
comfyPage
}) => {
const { node, box } = await setupResizableNode(comfyPage, 'KSampler')
const pollAnchorX = hasWestEdge(corner)
? node.pollRightEdge
: node.pollLeftEdge
const pollAnchorY = hasNorthEdge(corner)
? node.pollBottomEdge
: node.pollTopEdge
const anchorX = hasWestEdge(corner) ? box.x + box.width : box.x
const anchorY = hasNorthEdge(corner) ? box.y + box.height : box.y
await node.resizeFromCorner(corner, dragX, dragY)
await expect.poll(pollAnchorX).toBeCloseTo(anchorX, 0)
await expect.poll(pollAnchorY).toBeCloseTo(anchorY, 0)
})
})
})
test.describe('minimum size enforcement', () => {
test('SW resize clamps width, keeping right edge fixed', async ({
comfyPage
}) => {
const { node, box } = await setupResizableNode(comfyPage, 'KSampler')
const rightEdge = box.x + box.width
await node.resizeFromCorner('SW', box.width + 100, 0)
await expect.poll(node.pollRightEdge).toBeCloseTo(rightEdge, 0)
await expect.poll(node.pollWidth).toBeGreaterThanOrEqual(MIN_NODE_WIDTH)
})
test('NE resize clamps height at its lower bound', async ({
comfyPage
}) => {
const { node } = await setupResizableNode(comfyPage, 'KSampler')
// Default nodes render at content-minimum height; grow from SE so NE
// has room to shrink back down to the clamp.
await node.resizeFromCorner('SE', 0, 200)
const expandedBox = await node.boundingBox()
if (!expandedBox)
throw new Error('Node bounding box not found after SE grow')
const bottomEdge = expandedBox.y + expandedBox.height
// Overdrag once to hit the clamp, then again to prove further dragging
// does not shrink past the minimum (idempotent clamp).
await node.resizeFromCorner('NE', 0, expandedBox.height + 100)
const clampedHeight = (await node.boundingBox())?.height
if (clampedHeight === undefined)
throw new Error('Node bounding box not found after NE clamp')
expect(clampedHeight).toBeLessThan(expandedBox.height)
await node.resizeFromCorner('NE', 0, 200)
await expect.poll(node.pollHeight).toBeCloseTo(clampedHeight, 0)
await expect.poll(node.pollBottomEdge).toBeCloseTo(bottomEdge, 0)
})
})
}
)

View File

@@ -1,177 +0,0 @@
#!/usr/bin/env python3
"""
Generate test fixture files for metadata parser tests.
Each fixture embeds the same workflow and prompt JSON, matching the
format the ComfyUI backend uses to write metadata.
Prerequisites:
source ~/ComfyUI/.venv/bin/activate
python3 scripts/generate-embedded-metadata-test-files.py
Output: src/scripts/metadata/__fixtures__/
"""
import json
import os
import struct
import subprocess
import av
from PIL import Image
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FIXTURES_DIR = os.path.join(REPO_ROOT, 'src', 'scripts', 'metadata', '__fixtures__')
WORKFLOW = {
'nodes': [
{
'id': 1,
'type': 'KSampler',
'pos': [100, 100],
'size': [200, 200],
}
]
}
PROMPT = {'1': {'class_type': 'KSampler', 'inputs': {}}}
WORKFLOW_JSON = json.dumps(WORKFLOW, separators=(',', ':'))
PROMPT_JSON = json.dumps(PROMPT, separators=(',', ':'))
def out(name: str) -> str:
return os.path.join(FIXTURES_DIR, name)
def report(name: str):
size = os.path.getsize(out(name))
print(f' {name} ({size} bytes)')
def make_1x1_image() -> Image.Image:
return Image.new('RGB', (1, 1), (255, 0, 0))
def build_exif_bytes() -> bytes:
"""Build EXIF bytes matching the backend's tag assignments.
Backend: 0x010F (Make) = "workflow:<json>", 0x0110 (Model) = "prompt:<json>"
"""
img = make_1x1_image()
exif = img.getexif()
exif[0x010F] = f'workflow:{WORKFLOW_JSON}'
exif[0x0110] = f'prompt:{PROMPT_JSON}'
return exif.tobytes()
def inject_exif_prefix_in_webp(path: str):
"""Prepend Exif\\0\\0 to the EXIF chunk in a WEBP file.
PIL always strips this prefix, so we re-inject it to test that code path.
"""
data = bytearray(open(path, 'rb').read())
off = 12
while off < len(data):
chunk_type = data[off:off + 4]
chunk_len = struct.unpack_from('<I', data, off + 4)[0]
if chunk_type == b'EXIF':
prefix = b'Exif\x00\x00'
data[off + 8:off + 8] = prefix
struct.pack_into('<I', data, off + 4, chunk_len + len(prefix))
riff_size = struct.unpack_from('<I', data, 4)[0]
struct.pack_into('<I', data, 4, riff_size + len(prefix))
break
off += 8 + chunk_len + (chunk_len % 2)
with open(path, 'wb') as f:
f.write(data)
def generate_av_fixture(
name: str,
fmt: str,
codec: str,
rate: int = 44100,
options: dict | None = None,
):
"""Generate an audio fixture via PyAV container.metadata[], matching the backend."""
path = out(name)
container = av.open(path, mode='w', format=fmt, options=options or {})
stream = container.add_stream(codec, rate=rate)
stream.layout = 'mono'
container.metadata['prompt'] = PROMPT_JSON
container.metadata['workflow'] = WORKFLOW_JSON
sample_fmt = stream.codec_context.codec.audio_formats[0].name
samples = stream.codec_context.frame_size or 1024
frame = av.AudioFrame(format=sample_fmt, layout='mono', samples=samples)
frame.rate = rate
frame.pts = 0
for packet in stream.encode(frame):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
container.close()
report(name)
def generate_webp():
img = make_1x1_image()
exif = build_exif_bytes()
img.save(out('with_metadata.webp'), 'WEBP', exif=exif)
report('with_metadata.webp')
img.save(out('with_metadata_exif_prefix.webp'), 'WEBP', exif=exif)
inject_exif_prefix_in_webp(out('with_metadata_exif_prefix.webp'))
report('with_metadata_exif_prefix.webp')
def generate_avif():
img = make_1x1_image()
exif = build_exif_bytes()
img.save(out('with_metadata.avif'), 'AVIF', exif=exif)
report('with_metadata.avif')
def generate_flac():
generate_av_fixture('with_metadata.flac', 'flac', 'flac')
def generate_opus():
generate_av_fixture('with_metadata.opus', 'opus', 'libopus', rate=48000)
def generate_mp3():
generate_av_fixture('with_metadata.mp3', 'mp3', 'libmp3lame')
def generate_mp4():
"""Generate MP4 via ffmpeg CLI with QuickTime keys/ilst metadata."""
path = out('with_metadata.mp4')
subprocess.run([
'ffmpeg', '-y', '-loglevel', 'error',
'-f', 'lavfi', '-i', 'anullsrc=r=44100:cl=mono',
'-t', '0.01', '-c:a', 'aac', '-b:a', '32k',
'-movflags', 'use_metadata_tags',
'-metadata', f'prompt={PROMPT_JSON}',
'-metadata', f'workflow={WORKFLOW_JSON}',
path,
], check=True)
report('with_metadata.mp4')
def generate_webm():
generate_av_fixture('with_metadata.webm', 'webm', 'libvorbis')
if __name__ == '__main__':
print('Generating fixtures...')
generate_webp()
generate_avif()
generate_flac()
generate_opus()
generate_mp3()
generate_mp4()
generate_webm()
print('Done.')

View File

@@ -5,7 +5,6 @@ import { ref } from 'vue'
import { useCoreCommands } from '@/composables/useCoreCommands'
import { useExternalLink } from '@/composables/useExternalLink'
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
import { useSettingStore } from '@/platform/settings/settingStore'
import { api } from '@/scripts/api'
import { app } from '@/scripts/app'
@@ -36,34 +35,17 @@ vi.mock('@/scripts/app', () => {
const mockCanvas = {
subgraph: undefined,
selectedItems: new Set(),
selected_nodes: null as Record<string, unknown> | null,
copyToClipboard: vi.fn(),
pasteFromClipboard: vi.fn(),
selectItems: vi.fn(),
ds: mockDs,
deleteSelected: vi.fn(),
setDirty: vi.fn(),
fitViewToSelectionAnimated: vi.fn(),
empty: false,
state: {
readOnly: false,
selectionChanged: false
},
graph: {
add: vi.fn(),
convertToSubgraph: vi.fn(),
rootGraph: {}
},
select: vi.fn(),
canvas: {
dispatchEvent: vi.fn()
},
setGraph: vi.fn()
setDirty: vi.fn()
}
return {
app: {
clean: vi.fn(() => {
// Simulate app.clean() calling graph.clear() only when not in subgraph
if (!mockCanvas.subgraph) {
mockGraphClear()
}
@@ -72,11 +54,8 @@ vi.mock('@/scripts/app', () => {
refreshComboInNodes: vi.fn().mockResolvedValue(undefined),
canvas: mockCanvas,
rootGraph: {
clear: mockGraphClear,
_nodes: []
},
queuePrompt: vi.fn(),
ui: { loadFile: vi.fn() }
clear: mockGraphClear
}
}
}
})
@@ -84,9 +63,7 @@ vi.mock('@/scripts/app', () => {
vi.mock('@/scripts/api', () => ({
api: {
dispatchCustomEvent: vi.fn(),
apiURL: vi.fn(() => 'http://localhost:8188'),
interrupt: vi.fn(),
freeMemory: vi.fn()
apiURL: vi.fn(() => 'http://localhost:8188')
}
}))
@@ -124,15 +101,11 @@ vi.mock('@/services/litegraphService', () => ({
}))
}))
const mockTelemetry = vi.hoisted(() => ({
trackWorkflowCreated: vi.fn(),
trackRunButton: vi.fn(),
trackWorkflowExecution: vi.fn(),
trackHelpResourceClicked: vi.fn(),
trackEnterLinear: vi.fn()
}))
const mockTrackHelpResourceClicked = vi.hoisted(() => vi.fn())
vi.mock('@/platform/telemetry', () => ({
useTelemetry: vi.fn(() => mockTelemetry)
useTelemetry: vi.fn(() => ({
trackHelpResourceClicked: mockTrackHelpResourceClicked
}))
}))
const mockShowAbout = vi.hoisted(() => vi.fn())
@@ -148,18 +121,12 @@ vi.mock('@/stores/executionStore', () => ({
useExecutionStore: vi.fn(() => ({}))
}))
const mockToastStore = vi.hoisted(() => ({
add: vi.fn()
}))
vi.mock('@/platform/updates/common/toastStore', () => ({
useToastStore: vi.fn(() => mockToastStore)
vi.mock('@/stores/toastStore', () => ({
useToastStore: vi.fn(() => ({}))
}))
const mockChangeTracker = vi.hoisted(() => ({
captureCanvasState: vi.fn(),
checkState: vi.fn(),
undo: vi.fn(),
redo: vi.fn()
captureCanvasState: vi.fn()
}))
const mockWorkflowStore = vi.hoisted(() => ({
activeWorkflow: {
@@ -174,29 +141,22 @@ vi.mock('@/stores/subgraphStore', () => ({
useSubgraphStore: vi.fn(() => ({}))
}))
const mockCanvasStore = vi.hoisted(() => ({
getCanvas: vi.fn(),
canvas: null as unknown,
linearMode: false,
updateSelectedItems: vi.fn()
}))
vi.mock('@/renderer/core/canvas/canvasStore', () => ({
useCanvasStore: vi.fn(() => mockCanvasStore),
useCanvasStore: vi.fn(() => ({
getCanvas: () => app.canvas,
canvas: app.canvas
})),
useTitleEditorStore: vi.fn(() => ({
titleEditorTarget: null
}))
}))
vi.mock('@/stores/workspace/colorPaletteStore', () => ({
useColorPaletteStore: vi.fn(() => ({
completedActivePalette: { id: 'dark-default', light_theme: false }
}))
useColorPaletteStore: vi.fn(() => ({}))
}))
vi.mock('@/composables/auth/useAuthActions', () => ({
useAuthActions: vi.fn(() => ({
logout: vi.fn()
}))
useAuthActions: vi.fn(() => ({}))
}))
vi.mock('@/platform/cloud/subscription/composables/useSubscription', () => ({
@@ -206,73 +166,13 @@ vi.mock('@/platform/cloud/subscription/composables/useSubscription', () => ({
}))
}))
const mockIsActiveSubscription = vi.hoisted(() => ({ value: true }))
const mockShowSubscriptionDialog = vi.hoisted(() => vi.fn())
vi.mock('@/composables/billing/useBillingContext', () => ({
useBillingContext: vi.fn(() => ({
isActiveSubscription: mockIsActiveSubscription,
showSubscriptionDialog: mockShowSubscriptionDialog
isActiveSubscription: { value: true },
showSubscriptionDialog: vi.fn()
}))
}))
vi.mock('@/composables/auth/useCurrentUser', () => ({
useCurrentUser: vi.fn(() => ({
userEmail: ref(''),
resolvedUserInfo: ref(null)
}))
}))
const mockSelectedItems = vi.hoisted(() => ({
getSelectedNodes: vi.fn((): unknown[] => []),
toggleSelectedNodesMode: vi.fn()
}))
vi.mock('@/composables/canvas/useSelectedLiteGraphItems', () => ({
useSelectedLiteGraphItems: vi.fn(() => mockSelectedItems)
}))
vi.mock('@/composables/graph/useSubgraphOperations', () => ({
useSubgraphOperations: vi.fn(() => ({
unpackSubgraph: vi.fn()
}))
}))
vi.mock('@/composables/useExternalLink', () => ({
useExternalLink: vi.fn(() => ({
staticUrls: {
githubIssues: 'https://github.com/issues',
discord: 'https://discord.gg/test',
forum: 'https://forum.test.com'
},
buildDocsUrl: vi.fn(() => 'https://docs.test.com')
}))
}))
vi.mock('@/composables/useModelSelectorDialog', () => ({
useModelSelectorDialog: vi.fn(() => ({
show: vi.fn()
}))
}))
vi.mock('@/composables/useWorkflowTemplateSelectorDialog', () => ({
useWorkflowTemplateSelectorDialog: vi.fn(() => ({
show: vi.fn()
}))
}))
vi.mock('@/platform/assets/composables/useAssetBrowserDialog', () => ({
useAssetBrowserDialog: vi.fn(() => ({
browse: vi.fn()
}))
}))
vi.mock('@/platform/assets/utils/createModelNodeFromAsset', () => ({
createModelNodeFromAsset: vi.fn()
}))
vi.mock('@/platform/support/config', () => ({
buildSupportUrl: vi.fn(() => 'https://support.test.com')
}))
describe('useCoreCommands', () => {
const createMockNode = (id: number, comfyClass: string): LGraphNode => {
const baseNode = createMockLGraphNode({ id })
@@ -286,9 +186,13 @@ describe('useCoreCommands', () => {
const createMockSubgraph = () => {
const mockNodes = [
// Mock input node
createMockNode(1, 'SubgraphInputNode'),
// Mock output node
createMockNode(2, 'SubgraphOutputNode'),
// Mock user node
createMockNode(3, 'SomeUserNode'),
// Another mock user node
createMockNode(4, 'AnotherUserNode')
]
@@ -357,38 +261,31 @@ describe('useCoreCommands', () => {
} satisfies ReturnType<typeof useSettingStore>
}
function findCommand(id: string) {
const cmd = useCoreCommands().find((c) => c.id === id)
if (!cmd) throw new Error(`Command '${id}' not found`)
return cmd
}
beforeEach(() => {
vi.clearAllMocks()
// Set up Pinia
setActivePinia(createPinia())
// Reset app state
app.canvas.subgraph = undefined
app.canvas.selectedItems = new Set()
app.canvas.state.readOnly = false
app.canvas.state.selectionChanged = false
Object.defineProperty(app.canvas, 'empty', { value: false, writable: true })
mockCanvasStore.linearMode = false
mockCanvasStore.getCanvas.mockReturnValue(app.canvas)
mockIsActiveSubscription.value = true
// Mock settings store
vi.mocked(useSettingStore).mockReturnValue(createMockSettingStore(false))
vi.stubGlobal('confirm', vi.fn().mockReturnValue(true))
vi.stubGlobal(
'open',
vi.fn().mockReturnValue({ focus: vi.fn(), closed: false })
)
// Mock global confirm
global.confirm = vi.fn().mockReturnValue(true)
})
describe('ClearWorkflow command', () => {
it('should clear main graph when not in subgraph', async () => {
await findCommand('Comfy.ClearWorkflow').function()
const commands = useCoreCommands()
const clearCommand = commands.find(
(cmd) => cmd.id === 'Comfy.ClearWorkflow'
)!
// Execute the command
await clearCommand.function()
expect(app.clean).toHaveBeenCalled()
expect(app.rootGraph.clear).toHaveBeenCalled()
@@ -396,29 +293,46 @@ describe('useCoreCommands', () => {
})
it('should preserve input/output nodes when clearing subgraph', async () => {
// Set up subgraph context
app.canvas.subgraph = mockSubgraph
await findCommand('Comfy.ClearWorkflow').function()
const commands = useCoreCommands()
const clearCommand = commands.find(
(cmd) => cmd.id === 'Comfy.ClearWorkflow'
)!
// Execute the command
await clearCommand.function()
expect(app.clean).toHaveBeenCalled()
expect(app.rootGraph.clear).not.toHaveBeenCalled()
// Should only remove user nodes, not input/output nodes
const subgraph = app.canvas.subgraph!
expect(subgraph.remove).toHaveBeenCalledTimes(2)
expect(subgraph.remove).toHaveBeenCalledWith(subgraph.nodes[2])
expect(subgraph.remove).toHaveBeenCalledWith(subgraph.nodes[3])
expect(subgraph.remove).not.toHaveBeenCalledWith(subgraph.nodes[0])
expect(subgraph.remove).not.toHaveBeenCalledWith(subgraph.nodes[1])
expect(subgraph.remove).toHaveBeenCalledWith(subgraph.nodes[2]) // user1
expect(subgraph.remove).toHaveBeenCalledWith(subgraph.nodes[3]) // user2
expect(subgraph.remove).not.toHaveBeenCalledWith(subgraph.nodes[0]) // input1
expect(subgraph.remove).not.toHaveBeenCalledWith(subgraph.nodes[1]) // output1
expect(api.dispatchCustomEvent).toHaveBeenCalledWith('graphCleared')
})
it('should respect confirmation setting', async () => {
// Mock confirmation required
vi.mocked(useSettingStore).mockReturnValue(createMockSettingStore(true))
vi.stubGlobal('confirm', vi.fn().mockReturnValue(false))
await findCommand('Comfy.ClearWorkflow').function()
global.confirm = vi.fn().mockReturnValue(false) // User cancels
const commands = useCoreCommands()
const clearCommand = commands.find(
(cmd) => cmd.id === 'Comfy.ClearWorkflow'
)!
// Execute the command
await clearCommand.function()
// Should not clear anything when user cancels
expect(app.clean).not.toHaveBeenCalled()
expect(app.rootGraph.clear).not.toHaveBeenCalled()
expect(api.dispatchCustomEvent).not.toHaveBeenCalled()
@@ -426,6 +340,17 @@ describe('useCoreCommands', () => {
})
describe('Canvas clipboard commands', () => {
function findCommand(id: string) {
return useCoreCommands().find((cmd) => cmd.id === id)!
}
beforeEach(() => {
app.canvas.selectedItems = new Set()
vi.mocked(app.canvas.copyToClipboard).mockClear()
vi.mocked(app.canvas.pasteFromClipboard).mockClear()
vi.mocked(app.canvas.selectItems).mockClear()
})
it('should copy selected items when selection exists', async () => {
app.canvas.selectedItems = new Set([
{}
@@ -448,541 +373,14 @@ describe('useCoreCommands', () => {
expect(app.canvas.pasteFromClipboard).toHaveBeenCalledWith()
})
it('should paste with connect option', async () => {
await findCommand('Comfy.Canvas.PasteFromClipboardWithConnect').function()
expect(app.canvas.pasteFromClipboard).toHaveBeenCalledWith({
connectInputs: true
})
})
it('should select all items', async () => {
await findCommand('Comfy.Canvas.SelectAll').function()
// No arguments means "select all items on canvas"
expect(app.canvas.selectItems).toHaveBeenCalledWith()
})
})
describe('Undo/Redo commands', () => {
it('Undo should call changeTracker.undo', async () => {
await findCommand('Comfy.Undo').function()
expect(mockChangeTracker.undo).toHaveBeenCalled()
})
it('Redo should call changeTracker.redo', async () => {
await findCommand('Comfy.Redo').function()
expect(mockChangeTracker.redo).toHaveBeenCalled()
})
})
describe('Zoom commands', () => {
it('ZoomIn should increase scale and mark dirty', async () => {
await findCommand('Comfy.Canvas.ZoomIn').function()
expect(app.canvas.ds.changeScale).toHaveBeenCalled()
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('ZoomOut should decrease scale and mark dirty', async () => {
await findCommand('Comfy.Canvas.ZoomOut').function()
expect(app.canvas.ds.changeScale).toHaveBeenCalled()
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('ToggleLock should toggle readOnly state', async () => {
app.canvas.state.readOnly = false
await findCommand('Comfy.Canvas.ToggleLock').function()
expect(app.canvas.state.readOnly).toBe(true)
await findCommand('Comfy.Canvas.ToggleLock').function()
expect(app.canvas.state.readOnly).toBe(false)
})
it('Lock should set readOnly to true', async () => {
await findCommand('Comfy.Canvas.Lock').function()
expect(app.canvas.state.readOnly).toBe(true)
})
it('Unlock should set readOnly to false', async () => {
app.canvas.state.readOnly = true
await findCommand('Comfy.Canvas.Unlock').function()
expect(app.canvas.state.readOnly).toBe(false)
})
})
describe('Canvas delete command', () => {
it('should delete selected items when selection exists', async () => {
app.canvas.selectedItems = new Set([
{}
]) as typeof app.canvas.selectedItems
await findCommand('Comfy.Canvas.DeleteSelectedItems').function()
expect(app.canvas.deleteSelected).toHaveBeenCalled()
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('should dispatch no-items-selected event when nothing selected', async () => {
app.canvas.selectedItems = new Set()
await findCommand('Comfy.Canvas.DeleteSelectedItems').function()
expect(app.canvas.canvas.dispatchEvent).toHaveBeenCalledWith(
expect.objectContaining({ type: 'litegraph:no-items-selected' })
)
expect(app.canvas.deleteSelected).not.toHaveBeenCalled()
})
})
describe('ToggleLinkVisibility command', () => {
it('should hide links when currently visible', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(LiteGraph.SPLINE_LINK)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.Canvas.ToggleLinkVisibility').function()
expect(mockStore.set).toHaveBeenCalledWith(
'Comfy.LinkRenderMode',
LiteGraph.HIDDEN_LINK
)
})
it('should restore links when currently hidden', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(LiteGraph.HIDDEN_LINK)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.Canvas.ToggleLinkVisibility').function()
const lastSetCall = vi.mocked(mockStore.set).mock.calls.at(-1)
expect(lastSetCall?.[0]).toBe('Comfy.LinkRenderMode')
expect(lastSetCall?.[1]).not.toBe(LiteGraph.HIDDEN_LINK)
})
})
describe('ToggleMinimap command', () => {
it('should toggle minimap visibility setting', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(false)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.Canvas.ToggleMinimap').function()
expect(mockStore.set).toHaveBeenCalledWith('Comfy.Minimap.Visible', true)
})
})
describe('QueuePrompt commands', () => {
it('should show subscription dialog when not subscribed', async () => {
mockIsActiveSubscription.value = false
await findCommand('Comfy.QueuePrompt').function()
expect(mockShowSubscriptionDialog).toHaveBeenCalled()
expect(app.queuePrompt).not.toHaveBeenCalled()
mockIsActiveSubscription.value = true
})
it('should queue prompt when subscribed', async () => {
await findCommand('Comfy.QueuePrompt').function()
expect(app.queuePrompt).toHaveBeenCalledWith(0, 1)
expect(mockTelemetry.trackRunButton).toHaveBeenCalled()
expect(mockTelemetry.trackWorkflowExecution).toHaveBeenCalled()
})
it('should queue prompt at front', async () => {
await findCommand('Comfy.QueuePromptFront').function()
expect(app.queuePrompt).toHaveBeenCalledWith(-1, 1)
})
})
describe('QueueSelectedOutputNodes command', () => {
it('should show error toast when no output nodes selected', async () => {
await findCommand('Comfy.QueueSelectedOutputNodes').function()
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'error' })
)
expect(app.queuePrompt).not.toHaveBeenCalled()
})
})
describe('MoveSelectedNodes commands', () => {
function setupMoveTest() {
const mockNode = createMockLGraphNode({ id: 1 })
mockNode.pos = [100, 200] as [number, number]
mockSelectedItems.getSelectedNodes.mockReturnValue([mockNode])
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(10)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
return mockNode
}
it('should move nodes up by grid size', async () => {
const mockNode = setupMoveTest()
await findCommand('Comfy.Canvas.MoveSelectedNodes.Up').function()
expect(mockNode.pos).toEqual([100, 190])
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('should move nodes down by grid size', async () => {
const mockNode = setupMoveTest()
await findCommand('Comfy.Canvas.MoveSelectedNodes.Down').function()
expect(mockNode.pos).toEqual([100, 210])
})
it('should move nodes left by grid size', async () => {
const mockNode = setupMoveTest()
await findCommand('Comfy.Canvas.MoveSelectedNodes.Left').function()
expect(mockNode.pos).toEqual([90, 200])
})
it('should move nodes right by grid size', async () => {
const mockNode = setupMoveTest()
await findCommand('Comfy.Canvas.MoveSelectedNodes.Right').function()
expect(mockNode.pos).toEqual([110, 200])
})
it('should not move when no nodes selected', async () => {
mockSelectedItems.getSelectedNodes.mockReturnValue([])
await findCommand('Comfy.Canvas.MoveSelectedNodes.Up').function()
expect(app.canvas.setDirty).not.toHaveBeenCalled()
})
})
describe('ToggleLinear command', () => {
it('should toggle linear mode and track telemetry when entering', async () => {
mockCanvasStore.linearMode = false
await findCommand('Comfy.ToggleLinear').function()
expect(mockCanvasStore.linearMode).toBe(true)
expect(mockTelemetry.trackEnterLinear).toHaveBeenCalledWith({
source: 'keybind'
})
})
it('should use provided source metadata', async () => {
mockCanvasStore.linearMode = false
await findCommand('Comfy.ToggleLinear').function({
source: 'menu'
})
expect(mockTelemetry.trackEnterLinear).toHaveBeenCalledWith({
source: 'menu'
})
})
})
describe('ToggleQPOV2 command', () => {
it('should toggle queue panel v2 setting', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(false)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.ToggleQPOV2').function()
expect(mockStore.set).toHaveBeenCalledWith('Comfy.Queue.QPOV2', true)
})
})
describe('Memory commands', () => {
it('UnloadModels should show error when setting is disabled', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(false)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.Memory.UnloadModels').function()
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'error' })
)
expect(api.freeMemory).not.toHaveBeenCalled()
})
it('UnloadModels should call api.freeMemory when setting is enabled', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(true)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.Memory.UnloadModels').function()
expect(api.freeMemory).toHaveBeenCalledWith({
freeExecutionCache: false
})
})
it('UnloadModelsAndExecutionCache should call api.freeMemory with cache flag', async () => {
const mockStore = createMockSettingStore(false)
mockStore.get = vi.fn().mockReturnValue(true)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.Memory.UnloadModelsAndExecutionCache').function()
expect(api.freeMemory).toHaveBeenCalledWith({
freeExecutionCache: true
})
})
})
describe('FitView command', () => {
it('should show error toast when canvas is empty', async () => {
Object.defineProperty(app.canvas, 'empty', {
value: true,
writable: true
})
await findCommand('Comfy.Canvas.FitView').function()
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'error' })
)
expect(app.canvas.fitViewToSelectionAnimated).not.toHaveBeenCalled()
})
it('should fit view when canvas has content', async () => {
Object.defineProperty(app.canvas, 'empty', {
value: false,
writable: true
})
await findCommand('Comfy.Canvas.FitView').function()
expect(app.canvas.fitViewToSelectionAnimated).toHaveBeenCalled()
})
})
describe('Interrupt command', () => {
it('should call api.interrupt and show toast', async () => {
await findCommand('Comfy.Interrupt').function()
expect(api.interrupt).toHaveBeenCalled()
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'info' })
)
})
})
describe('OpenWorkflow command', () => {
it('should call app.ui.loadFile', async () => {
await findCommand('Comfy.OpenWorkflow').function()
expect(app.ui.loadFile).toHaveBeenCalled()
})
})
describe('RefreshNodeDefinitions command', () => {
it('should call app.refreshComboInNodes', async () => {
await findCommand('Comfy.RefreshNodeDefinitions').function()
expect(app.refreshComboInNodes).toHaveBeenCalled()
})
})
describe('OpenClipspace command', () => {
it('should call app.openClipspace', async () => {
await findCommand('Comfy.OpenClipspace').function()
expect(app.openClipspace).toHaveBeenCalled()
})
})
describe('ToggleTheme command', () => {
it('should switch from dark to light theme', async () => {
const mockStore = createMockSettingStore(false)
vi.mocked(useSettingStore).mockReturnValue(mockStore)
await findCommand('Comfy.ToggleTheme').function()
expect(mockStore.set).toHaveBeenCalledWith(
'Comfy.ColorPalette',
expect.any(String)
)
})
})
describe('ToggleSelectedNodes commands', () => {
it('Mute should toggle selected nodes mode and mark dirty', async () => {
await findCommand('Comfy.Canvas.ToggleSelectedNodes.Mute').function()
expect(mockSelectedItems.toggleSelectedNodesMode).toHaveBeenCalled()
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('Bypass should toggle selected nodes mode and mark dirty', async () => {
await findCommand('Comfy.Canvas.ToggleSelectedNodes.Bypass').function()
expect(mockSelectedItems.toggleSelectedNodesMode).toHaveBeenCalled()
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('Pin should toggle pin state on each selected node', async () => {
const mockNode = createMockLGraphNode({ id: 1 })
Object.defineProperty(mockNode, 'pinned', {
value: false,
writable: true
})
mockNode.pin = vi.fn()
mockSelectedItems.getSelectedNodes.mockReturnValue([mockNode])
await findCommand('Comfy.Canvas.ToggleSelectedNodes.Pin').function()
expect(mockNode.pin).toHaveBeenCalledWith(true)
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('Collapse should collapse each selected node', async () => {
const mockNode = createMockLGraphNode({ id: 1 })
mockNode.collapse = vi.fn()
mockSelectedItems.getSelectedNodes.mockReturnValue([mockNode])
await findCommand('Comfy.Canvas.ToggleSelectedNodes.Collapse').function()
expect(mockNode.collapse).toHaveBeenCalled()
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
it('Resize should compute and set optimal size', async () => {
const mockNode = createMockLGraphNode({ id: 1 })
mockNode.computeSize = vi.fn().mockReturnValue([200, 100])
mockNode.setSize = vi.fn()
mockSelectedItems.getSelectedNodes.mockReturnValue([mockNode])
await findCommand('Comfy.Canvas.Resize').function()
expect(mockNode.computeSize).toHaveBeenCalled()
expect(mockNode.setSize).toHaveBeenCalledWith([200, 100])
expect(app.canvas.setDirty).toHaveBeenCalledWith(true, true)
})
})
describe('Help commands', () => {
it('OpenComfyUIIssues should open GitHub issues and track telemetry', async () => {
await findCommand('Comfy.Help.OpenComfyUIIssues').function()
expect(mockTelemetry.trackHelpResourceClicked).toHaveBeenCalledWith({
resource_type: 'github',
is_external: true,
source: 'menu'
})
expect(window.open).toHaveBeenCalledWith(
'https://github.com/issues',
'_blank'
)
})
it('OpenComfyUIDocs should open docs and track telemetry', async () => {
await findCommand('Comfy.Help.OpenComfyUIDocs').function()
expect(mockTelemetry.trackHelpResourceClicked).toHaveBeenCalledWith({
resource_type: 'docs',
is_external: true,
source: 'menu'
})
expect(window.open).toHaveBeenCalledWith(
'https://docs.test.com',
'_blank'
)
})
it('OpenComfyOrgDiscord should open Discord and track telemetry', async () => {
await findCommand('Comfy.Help.OpenComfyOrgDiscord').function()
expect(mockTelemetry.trackHelpResourceClicked).toHaveBeenCalledWith({
resource_type: 'discord',
is_external: true,
source: 'menu'
})
expect(window.open).toHaveBeenCalledWith(
'https://discord.gg/test',
'_blank'
)
})
it('OpenComfyUIForum should open forum and track telemetry', async () => {
await findCommand('Comfy.Help.OpenComfyUIForum').function()
expect(mockTelemetry.trackHelpResourceClicked).toHaveBeenCalledWith({
resource_type: 'help_feedback',
is_external: true,
source: 'menu'
})
expect(window.open).toHaveBeenCalledWith(
'https://forum.test.com',
'_blank'
)
})
})
describe('GroupSelectedNodes command', () => {
it('should show error toast when nothing selected', async () => {
app.canvas.selectedItems = new Set()
await findCommand('Comfy.Graph.GroupSelectedNodes').function()
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'error' })
)
})
})
describe('ConvertToSubgraph command', () => {
it('should show error toast when conversion fails', async () => {
app.canvas.graph!.convertToSubgraph = vi.fn().mockReturnValue(null)
await findCommand('Comfy.Graph.ConvertToSubgraph').function()
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'error' })
)
})
it('should select the new subgraph node on success', async () => {
const mockNode = createMockLGraphNode({ id: 1 })
app.canvas.graph!.convertToSubgraph = vi
.fn()
.mockReturnValue({ node: mockNode })
await findCommand('Comfy.Graph.ConvertToSubgraph').function()
expect(app.canvas.select).toHaveBeenCalledWith(mockNode)
expect(mockCanvasStore.updateSelectedItems).toHaveBeenCalled()
})
})
describe('ContactSupport command', () => {
it('should open support URL in new window', async () => {
await findCommand('Comfy.ContactSupport').function()
expect(window.open).toHaveBeenCalledWith(
'https://support.test.com',
'_blank',
'noopener,noreferrer'
)
})
})
describe('Subgraph metadata commands', () => {
beforeEach(() => {
mockSubgraph.extra = {}
@@ -1182,7 +580,7 @@ describe('useCoreCommands', () => {
it('Comfy.Help.OpenComfyUIIssues opens the GitHub issues URL and tracks telemetry', async () => {
await findCmd('Comfy.Help.OpenComfyUIIssues').function()
expect(mockTelemetry.trackHelpResourceClicked).toHaveBeenCalledWith(
expect(mockTrackHelpResourceClicked).toHaveBeenCalledWith(
expect.objectContaining({
resource_type: 'github',
is_external: true,
@@ -1195,7 +593,7 @@ describe('useCoreCommands', () => {
it('Comfy.Help.OpenComfyOrgDiscord opens the Discord URL and tracks telemetry', async () => {
await findCmd('Comfy.Help.OpenComfyOrgDiscord').function()
expect(mockTelemetry.trackHelpResourceClicked).toHaveBeenCalledWith(
expect(mockTrackHelpResourceClicked).toHaveBeenCalledWith(
expect.objectContaining({
resource_type: 'discord'
})

View File

@@ -102,16 +102,6 @@ function createMeshModel(name = 'TestModel'): THREE.Group {
return group
}
function createPointsModel(name = 'TestModel'): THREE.Group {
const geometry = new THREE.BufferGeometry()
const material = new THREE.PointsMaterial({ color: 0xff0000 })
const points = new THREE.Points(geometry, material)
const group = new THREE.Group()
group.name = name
group.add(points)
return group
}
describe('SceneModelManager', () => {
describe('constructor', () => {
it('initializes default state', () => {
@@ -321,20 +311,6 @@ describe('SceneModelManager', () => {
expect(geoDispose).toHaveBeenCalled()
expect(matDispose).toHaveBeenCalled()
})
it('disposes points geometry and materials', async () => {
const { manager } = createManager()
const model = createPointsModel()
const points = model.children[0] as THREE.Points
const geoDispose = vi.spyOn(points.geometry, 'dispose')
const matDispose = vi.spyOn(points.material as THREE.Material, 'dispose')
await manager.setupModel(model)
manager.clearModel()
expect(geoDispose).toHaveBeenCalled()
expect(matDispose).toHaveBeenCalled()
})
})
describe('reset', () => {

View File

@@ -328,7 +328,7 @@ export class SceneModelManager implements ModelManagerInterface {
this.scene.remove(obj)
obj.traverse((child) => {
if (child instanceof THREE.Mesh || child instanceof THREE.Points) {
if (child instanceof THREE.Mesh) {
child.geometry?.dispose()
if (Array.isArray(child.material)) {
child.material.forEach((material) => material.dispose())

View File

@@ -216,6 +216,7 @@
v-for="handle in RESIZE_HANDLES"
:key="handle.corner"
role="button"
:data-corner="handle.corner"
:aria-label="t(handle.i18nKey)"
:class="
cn(

View File

@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'
import type { CompassCorners } from '@/lib/litegraph/src/interfaces'
import { RESIZE_HANDLES, hasNorthEdge, hasWestEdge } from './resizeHandleConfig'
describe('hasWestEdge', () => {
it.each<[CompassCorners, boolean]>([
['NW', true],
['SW', true],
['NE', false],
['SE', false]
])('corner %s -> %s', (corner, expected) => {
expect(hasWestEdge(corner)).toBe(expected)
})
})
describe('hasNorthEdge', () => {
it.each<[CompassCorners, boolean]>([
['NW', true],
['NE', true],
['SW', false],
['SE', false]
])('corner %s -> %s', (corner, expected) => {
expect(hasNorthEdge(corner)).toBe(expected)
})
})
describe('RESIZE_HANDLES', () => {
it('defines exactly one entry per CompassCorners member', () => {
const expected = new Set<CompassCorners>(['NE', 'NW', 'SE', 'SW'])
const actual = new Set(RESIZE_HANDLES.map((handle) => handle.corner))
expect(actual).toEqual(expected)
expect(RESIZE_HANDLES).toHaveLength(expected.size)
})
})

View File

@@ -43,3 +43,11 @@ export const RESIZE_HANDLES: ResizeHandle[] = [
svgTransform: 'scale(-1, -1)'
}
] as const
/** True for corners on the left edge of a node (SW, NW) — these move the x-origin when dragged. */
export const hasWestEdge = (corner: CompassCorners): boolean =>
corner === 'SW' || corner === 'NW'
/** True for corners on the top edge of a node (NE, NW) — these move the y-origin when dragged. */
export const hasNorthEdge = (corner: CompassCorners): boolean =>
corner === 'NE' || corner === 'NW'

View File

@@ -8,6 +8,10 @@ import { MIN_NODE_WIDTH } from '@/renderer/core/layout/transform/graphRenderTran
import { useNodeSnap } from '@/renderer/extensions/vueNodes/composables/useNodeSnap'
import { useShiftKeySync } from '@/renderer/extensions/vueNodes/composables/useShiftKeySync'
import { useTransformState } from '@/renderer/core/layout/transform/useTransformState'
import {
hasNorthEdge,
hasWestEdge
} from '@/renderer/extensions/vueNodes/interactions/resize/resizeHandleConfig'
export interface ResizeCallbackPayload {
size: Size
@@ -128,20 +132,23 @@ export function useNodeResize(
break
}
const isWestCorner = hasWestEdge(activeCorner)
const isNorthCorner = hasNorthEdge(activeCorner)
// Apply snap-to-grid
if (shouldSnap(moveEvent)) {
// Snap position first for N/W corners, then compensate size
if (activeCorner.includes('N') || activeCorner.includes('W')) {
if (isNorthCorner || isWestCorner) {
const originalX = newX
const originalY = newY
const snapped = applySnapToPosition({ x: newX, y: newY })
newX = snapped.x
newY = snapped.y
if (activeCorner.includes('N')) {
if (isNorthCorner) {
newHeight += originalY - newY
}
if (activeCorner.includes('W')) {
if (isWestCorner) {
newWidth += originalX - newX
}
}
@@ -159,14 +166,14 @@ export function useNodeResize(
parseFloat(nodeElement.style.getPropertyValue('min-width') || '0') ||
MIN_NODE_WIDTH
if (newWidth < minWidth) {
if (activeCorner.includes('W')) {
if (isWestCorner) {
newX =
resizeStartPosition.value.x + resizeStartSize.value.width - minWidth
}
newWidth = minWidth
}
if (newHeight < minContentHeight) {
if (activeCorner.includes('N')) {
if (isNorthCorner) {
newY =
resizeStartPosition.value.y +
resizeStartSize.value.height -

View File

@@ -1,48 +0,0 @@
import { vi } from 'vitest'
export const EXPECTED_WORKFLOW = {
nodes: [{ id: 1, type: 'KSampler', pos: [100, 100], size: [200, 200] }]
}
export const EXPECTED_PROMPT = {
'1': { class_type: 'KSampler', inputs: {} }
}
type ReadMethod = 'readAsText' | 'readAsArrayBuffer'
export function mockFileReaderError(method: ReadMethod): void {
vi.spyOn(FileReader.prototype, method).mockImplementation(
function (this: FileReader) {
queueMicrotask(() =>
this.onerror?.(new ProgressEvent('error') as ProgressEvent<FileReader>)
)
}
)
}
export function mockFileReaderAbort(method: ReadMethod): void {
vi.spyOn(FileReader.prototype, method).mockImplementation(
function (this: FileReader) {
queueMicrotask(() =>
this.onabort?.(new ProgressEvent('abort') as ProgressEvent<FileReader>)
)
}
)
}
export function mockFileReaderResult(
method: ReadMethod,
result: string | ArrayBuffer | null
): void {
vi.spyOn(FileReader.prototype, method).mockImplementation(
function (this: FileReader) {
Object.defineProperty(this, 'result', {
value: result,
configurable: true
})
queueMicrotask(() =>
this.onload?.(new ProgressEvent('load') as ProgressEvent<FileReader>)
)
}
)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 552 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 272 B

View File

@@ -1,76 +1,7 @@
import fs from 'fs'
import path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
EXPECTED_PROMPT,
EXPECTED_WORKFLOW,
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getFromAvifFile } from './avif'
const fixturePath = path.resolve(__dirname, '__fixtures__/with_metadata.avif')
afterEach(() => vi.restoreAllMocks())
describe('AVIF metadata', () => {
it('extracts workflow and prompt from EXIF data in ISOBMFF boxes', async () => {
const bytes = fs.readFileSync(fixturePath)
const file = new File([bytes], 'test.avif', { type: 'image/avif' })
const result = await getFromAvifFile(file)
expect(JSON.parse(result.workflow)).toEqual(EXPECTED_WORKFLOW)
expect(JSON.parse(result.prompt)).toEqual(EXPECTED_PROMPT)
})
it('returns empty for non-AVIF data', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const file = new File([new Uint8Array(16)], 'fake.avif')
const result = await getFromAvifFile(file)
expect(result).toEqual({})
expect(console.error).toHaveBeenCalledWith('Not a valid AVIF file')
})
it('returns empty when AVIF has valid ftyp but corrupt internal boxes', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const buf = new Uint8Array(40)
const dv = new DataView(buf.buffer)
dv.setUint32(0, 16)
buf.set(new TextEncoder().encode('ftypavif'), 4)
dv.setUint32(16, 24)
buf.set(new TextEncoder().encode('meta'), 20)
const file = new File([buf], 'corrupt.avif', { type: 'image/avif' })
const result = await getFromAvifFile(file)
expect(result).toEqual({})
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Error parsing AVIF metadata'),
expect.anything()
)
})
describe('FileReader failure modes', () => {
const file = new File([new Uint8Array(16)], 'test.avif')
it('resolves empty when the FileReader fires error', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
mockFileReaderError('readAsArrayBuffer')
expect(await getFromAvifFile(file)).toEqual({})
})
it('resolves empty when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
expect(await getFromAvifFile(file)).toEqual({})
})
})
})
const setU32BE = (dv: DataView, off: number, val: number) =>
dv.setUint32(off, val, false)
const setU16BE = (dv: DataView, off: number, val: number) =>

View File

@@ -407,7 +407,6 @@ export function getFromAvifFile(file: File): Promise<Record<string, string>> {
console.error('FileReader: Error reading AVIF file:', err)
resolve({})
}
reader.onabort = () => resolve({})
reader.readAsArrayBuffer(file)
})
}

View File

@@ -1,49 +0,0 @@
import fs from 'fs'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
EXPECTED_PROMPT,
EXPECTED_WORKFLOW,
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getFromWebmFile } from './ebml'
const fixturePath = path.resolve(__dirname, '__fixtures__/with_metadata.webm')
describe('WebM/EBML metadata', () => {
it('extracts workflow and prompt from EBML SimpleTag elements', async () => {
const bytes = fs.readFileSync(fixturePath)
const file = new File([bytes], 'test.webm', { type: 'video/webm' })
const result = await getFromWebmFile(file)
expect(result.workflow).toEqual(EXPECTED_WORKFLOW)
expect(result.prompt).toEqual(EXPECTED_PROMPT)
})
it('returns empty for non-WebM data', async () => {
const file = new File([new Uint8Array(16)], 'fake.webm')
const result = await getFromWebmFile(file)
expect(result).toEqual({})
})
describe('FileReader failure modes', () => {
afterEach(() => vi.restoreAllMocks())
const file = new File([new Uint8Array(16)], 'test.webm')
it('resolves empty when the FileReader fires error', async () => {
mockFileReaderError('readAsArrayBuffer')
expect(await getFromWebmFile(file)).toEqual({})
})
it('resolves empty when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
expect(await getFromWebmFile(file)).toEqual({})
})
})
})

View File

@@ -353,7 +353,6 @@ export function getFromWebmFile(file: File): Promise<ComfyMetadata> {
const reader = new FileReader()
reader.onload = (event) => handleFileLoad(event, resolve)
reader.onerror = () => resolve({})
reader.onabort = () => resolve({})
reader.readAsArrayBuffer(file.slice(0, MAX_READ_BYTES))
})
}

View File

@@ -1,56 +0,0 @@
import fs from 'fs'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
EXPECTED_PROMPT,
EXPECTED_WORKFLOW,
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getFromFlacBuffer, getFromFlacFile } from './flac'
const fixturePath = path.resolve(__dirname, '__fixtures__/with_metadata.flac')
afterEach(() => vi.restoreAllMocks())
describe('FLAC metadata', () => {
it('extracts workflow and prompt from Vorbis comments', () => {
const bytes = fs.readFileSync(fixturePath)
const buffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength
)
const result = getFromFlacBuffer(buffer)
expect(result.workflow).toBe(JSON.stringify(EXPECTED_WORKFLOW))
expect(result.prompt).toBe(JSON.stringify(EXPECTED_PROMPT))
})
it('returns undefined for non-FLAC data', () => {
const buf = new ArrayBuffer(16)
const result = getFromFlacBuffer(buf)
expect(result).toBeUndefined()
})
describe('FileReader failure modes', () => {
const file = new File([new Uint8Array(16)], 'test.flac')
it('resolves empty when the FileReader fires error', async () => {
mockFileReaderError('readAsArrayBuffer')
const result = await getFromFlacFile(file)
expect(result).toEqual({})
})
it('resolves empty when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
const result = await getFromFlacFile(file)
expect(result).toEqual({})
})
})
})

View File

@@ -42,8 +42,6 @@ export function getFromFlacFile(file: File): Promise<Record<string, string>> {
const arrayBuffer = event.target.result as ArrayBuffer
r(getFromFlacBuffer(arrayBuffer))
}
reader.onerror = () => r({})
reader.onabort = () => r({})
reader.readAsArrayBuffer(file)
})
}

View File

@@ -1,11 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { ASCII, GltfSizeBytes } from '@/types/metadataTypes'
import {
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getGltfBinaryMetadata } from './gltf'
describe('GLTF binary metadata parser', () => {
@@ -164,20 +160,4 @@ describe('GLTF binary metadata parser', () => {
const metadata = await getGltfBinaryMetadata(invalidEmptyFile)
expect(metadata).toEqual({})
})
describe('FileReader failure modes', () => {
afterEach(() => vi.restoreAllMocks())
const file = new File([new Uint8Array(16)], 'test.glb')
it('resolves empty when the FileReader fires error', async () => {
mockFileReaderError('readAsArrayBuffer')
expect(await getGltfBinaryMetadata(file)).toEqual({})
})
it('resolves empty when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
expect(await getGltfBinaryMetadata(file)).toEqual({})
})
})
})

View File

@@ -165,7 +165,6 @@ export function getGltfBinaryMetadata(file: File): Promise<ComfyMetadata> {
}
}
reader.onerror = () => resolve({})
reader.onabort = () => resolve({})
reader.readAsArrayBuffer(file.slice(0, bytesToRead))
})
}

View File

@@ -1,52 +0,0 @@
import fs from 'fs'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
EXPECTED_PROMPT,
EXPECTED_WORKFLOW,
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getFromIsobmffFile } from './isobmff'
const fixturePath = path.resolve(__dirname, '__fixtures__/with_metadata.mp4')
describe('ISOBMFF (MP4) metadata', () => {
it('extracts workflow and prompt from QuickTime keys/ilst boxes', async () => {
const bytes = fs.readFileSync(fixturePath)
const file = new File([bytes], 'test.mp4', { type: 'video/mp4' })
const result = await getFromIsobmffFile(file)
expect(result.workflow).toEqual(EXPECTED_WORKFLOW)
expect(result.prompt).toEqual(EXPECTED_PROMPT)
})
it('returns empty for non-ISOBMFF data', async () => {
const file = new File([new Uint8Array(16)], 'fake.mp4', {
type: 'video/mp4'
})
const result = await getFromIsobmffFile(file)
expect(result).toEqual({})
})
describe('FileReader failure modes', () => {
afterEach(() => vi.restoreAllMocks())
const file = new File([new Uint8Array(16)], 'test.mp4')
it('resolves empty when the FileReader fires error', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
mockFileReaderError('readAsArrayBuffer')
expect(await getFromIsobmffFile(file)).toEqual({})
})
it('resolves empty when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
expect(await getFromIsobmffFile(file)).toEqual({})
})
})
})

View File

@@ -274,7 +274,6 @@ export function getFromIsobmffFile(file: File): Promise<ComfyMetadata> {
console.error('FileReader: Error reading ISOBMFF file:', err)
resolve({})
}
reader.onabort = () => resolve({})
reader.readAsArrayBuffer(file.slice(0, MAX_READ_BYTES))
})
}

View File

@@ -1,91 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
mockFileReaderAbort,
mockFileReaderError,
mockFileReaderResult
} from './__fixtures__/helpers'
import { getDataFromJSON } from './json'
function jsonFile(content: object): File {
return new File([JSON.stringify(content)], 'test.json', {
type: 'application/json'
})
}
describe('getDataFromJSON', () => {
it('detects API-format workflows by class_type on every value', async () => {
const apiData = {
'1': { class_type: 'KSampler', inputs: {} },
'2': { class_type: 'EmptyLatentImage', inputs: {} }
}
const result = await getDataFromJSON(jsonFile(apiData))
expect(result).toEqual({ prompt: apiData })
})
it('treats objects without universal class_type as a workflow', async () => {
const workflow = { nodes: [], links: [], version: 1 }
const result = await getDataFromJSON(jsonFile(workflow))
expect(result).toEqual({ workflow })
})
it('extracts templates when the root object has a templates key', async () => {
const templates = [{ name: 'basic' }]
const result = await getDataFromJSON(jsonFile({ templates }))
expect(result).toEqual({ templates })
})
it('returns undefined for non-JSON content', async () => {
const file = new File(['not valid json'], 'bad.json', {
type: 'application/json'
})
const result = await getDataFromJSON(file)
expect(result).toBeUndefined()
})
describe('FileReader failure modes', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('resolves undefined when the FileReader fires error', async () => {
mockFileReaderError('readAsText')
const result = await getDataFromJSON(jsonFile({ nodes: [] }))
expect(result).toBeUndefined()
})
it('resolves undefined when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsText')
const result = await getDataFromJSON(jsonFile({ nodes: [] }))
expect(result).toBeUndefined()
})
it('resolves undefined when reader.result is not a string', async () => {
mockFileReaderResult('readAsText', new ArrayBuffer(8))
const result = await getDataFromJSON(jsonFile({ nodes: [] }))
expect(result).toBeUndefined()
})
it('resolves undefined when reader.result is null', async () => {
mockFileReaderResult('readAsText', null)
const result = await getDataFromJSON(jsonFile({ nodes: [] }))
expect(result).toBeUndefined()
})
})
})

View File

@@ -6,28 +6,21 @@ export function getDataFromJSON(
return new Promise<Record<string, object> | undefined>((resolve) => {
const reader = new FileReader()
reader.onload = async () => {
try {
if (typeof reader.result !== 'string') {
resolve(undefined)
return
}
const jsonContent = JSON.parse(reader.result)
if (jsonContent?.templates) {
resolve({ templates: jsonContent.templates })
return
}
if (isApiJson(jsonContent)) {
resolve({ prompt: jsonContent })
return
}
resolve({ workflow: jsonContent })
} catch {
resolve(undefined)
const readerResult = reader.result as string
const jsonContent = JSON.parse(readerResult)
if (jsonContent?.templates) {
resolve({ templates: jsonContent.templates })
return
}
if (isApiJson(jsonContent)) {
resolve({ prompt: jsonContent })
return
}
resolve({ workflow: jsonContent })
return
}
reader.onerror = () => resolve(undefined)
reader.onabort = () => resolve(undefined)
reader.readAsText(file)
return
})
}

View File

@@ -1,106 +0,0 @@
import fs from 'fs'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
EXPECTED_PROMPT,
EXPECTED_WORKFLOW,
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getMp3Metadata } from './mp3'
const fixturePath = path.resolve(__dirname, '__fixtures__/with_metadata.mp3')
afterEach(() => vi.restoreAllMocks())
describe('MP3 metadata', () => {
it('extracts workflow and prompt from ID3 tags', async () => {
const bytes = fs.readFileSync(fixturePath)
const file = new File([bytes], 'test.mp3', { type: 'audio/mpeg' })
const result = await getMp3Metadata(file)
expect(result.workflow).toEqual(EXPECTED_WORKFLOW)
expect(result.prompt).toEqual(EXPECTED_PROMPT)
})
it('returns undefined fields when file has no embedded metadata', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const file = new File([new Uint8Array(16)], 'empty.mp3', {
type: 'audio/mpeg'
})
const result = await getMp3Metadata(file)
expect(result.workflow).toBeUndefined()
expect(result.prompt).toBeUndefined()
expect(console.error).toHaveBeenCalledWith('Invalid file signature.')
})
it('does not log an invalid signature for a valid MP3 sync header', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const buf = new Uint8Array(16)
buf[0] = 0xff
buf[1] = 0xfb
const file = new File([buf], 'valid.mp3', { type: 'audio/mpeg' })
await getMp3Metadata(file)
expect(errorSpy).not.toHaveBeenCalled()
})
it('does not log an invalid signature for a valid ID3v2 header', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const buf = new Uint8Array(16)
buf[0] = 0x49
buf[1] = 0x44
buf[2] = 0x33
const file = new File([buf], 'valid-id3.mp3', { type: 'audio/mpeg' })
await getMp3Metadata(file)
expect(errorSpy).not.toHaveBeenCalled()
})
it('extracts metadata that spans the 4096-byte page boundary', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const metadata =
`prompt\0${JSON.stringify(EXPECTED_PROMPT)}\0` +
`workflow\0${JSON.stringify(EXPECTED_WORKFLOW)}\0`
const metadataStart = 4090
const size = metadataStart + metadata.length + 4
const buf = new Uint8Array(size)
for (let i = 0; i < metadata.length; i++) {
buf[metadataStart + i] = metadata.charCodeAt(i)
}
buf[size - 2] = 0xff
buf[size - 1] = 0xfb
const file = new File([buf], 'large.mp3', { type: 'audio/mpeg' })
const result = await getMp3Metadata(file)
expect(result.workflow).toEqual(EXPECTED_WORKFLOW)
expect(result.prompt).toEqual(EXPECTED_PROMPT)
})
describe('FileReader failure modes', () => {
const file = new File([new Uint8Array(16)], 'test.mp3')
it('resolves undefined fields when the FileReader fires error', async () => {
mockFileReaderError('readAsArrayBuffer')
const result = await getMp3Metadata(file)
expect(result).toEqual({ prompt: undefined, workflow: undefined })
})
it('resolves undefined fields when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
const result = await getMp3Metadata(file)
expect(result).toEqual({ prompt: undefined, workflow: undefined })
})
})
})

View File

@@ -1,28 +1,21 @@
export async function getMp3Metadata(file: File) {
const reader = new FileReader()
const read_process = new Promise<ArrayBuffer | null>((r) => {
reader.onload = (event) => r((event?.target?.result as ArrayBuffer) ?? null)
reader.onerror = () => r(null)
reader.onabort = () => r(null)
})
const read_process = new Promise(
(r) => (reader.onload = (event) => r(event?.target?.result))
)
reader.readAsArrayBuffer(file)
const arrayBuffer = await read_process
if (!arrayBuffer) return { prompt: undefined, workflow: undefined }
const arrayBuffer = (await read_process) as ArrayBuffer
//https://stackoverflow.com/questions/7302439/how-can-i-determine-that-a-particular-file-is-in-fact-an-mp3-file#7302482
const sig_bytes = new Uint8Array(arrayBuffer, 0, 3)
if (
(sig_bytes[0] != 0xff || sig_bytes[1] != 0xfb) &&
(sig_bytes[0] != 0x49 || sig_bytes[1] != 0x44 || sig_bytes[2] != 0x33)
(sig_bytes[0] != 0xff && sig_bytes[1] != 0xfb) ||
(sig_bytes[0] != 0x49 && sig_bytes[1] != 0x44 && sig_bytes[2] != 0x33)
)
console.error('Invalid file signature.')
let header = ''
while (header.length < arrayBuffer.byteLength) {
const page = String.fromCharCode(
...new Uint8Array(
arrayBuffer,
header.length,
Math.min(4096, arrayBuffer.byteLength - header.length)
)
...new Uint8Array(arrayBuffer, header.length, header.length + 4096)
)
header += page
if (page.match('\u00ff\u00fb')) break

View File

@@ -1,74 +0,0 @@
import fs from 'fs'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
EXPECTED_PROMPT,
EXPECTED_WORKFLOW,
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getOggMetadata } from './ogg'
const fixturePath = path.resolve(__dirname, '__fixtures__/with_metadata.opus')
afterEach(() => vi.restoreAllMocks())
describe('OGG/Opus metadata', () => {
it('extracts workflow and prompt from an Opus file', async () => {
const bytes = fs.readFileSync(fixturePath)
const file = new File([bytes], 'test.opus', { type: 'audio/ogg' })
const result = await getOggMetadata(file)
expect(result.workflow).toEqual(EXPECTED_WORKFLOW)
expect(result.prompt).toEqual(EXPECTED_PROMPT)
})
it('returns undefined fields for non-OGG data', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const file = new File([new Uint8Array(16)], 'fake.ogg', {
type: 'audio/ogg'
})
const result = await getOggMetadata(file)
expect(result.workflow).toBeUndefined()
expect(result.prompt).toBeUndefined()
expect(console.error).toHaveBeenCalledWith('Invalid file signature.')
})
it('handles files larger than 4096 bytes without RangeError', async () => {
const size = 5000
const buf = new Uint8Array(size)
const oggs = new TextEncoder().encode('OggS\0')
buf.set(oggs, 0)
buf.set(oggs, 4500)
const file = new File([buf], 'large.ogg', { type: 'audio/ogg' })
const result = await getOggMetadata(file)
expect(result.workflow).toBeUndefined()
expect(result.prompt).toBeUndefined()
})
describe('FileReader failure modes', () => {
const file = new File([new Uint8Array(16)], 'test.ogg')
it('resolves undefined fields when the FileReader fires error', async () => {
mockFileReaderError('readAsArrayBuffer')
const result = await getOggMetadata(file)
expect(result).toEqual({ prompt: undefined, workflow: undefined })
})
it('resolves undefined fields when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
const result = await getOggMetadata(file)
expect(result).toEqual({ prompt: undefined, workflow: undefined })
})
})
})

View File

@@ -1,24 +1,17 @@
export async function getOggMetadata(file: File) {
const reader = new FileReader()
const read_process = new Promise<ArrayBuffer | null>((r) => {
reader.onload = (event) => r((event?.target?.result as ArrayBuffer) ?? null)
reader.onerror = () => r(null)
reader.onabort = () => r(null)
})
const read_process = new Promise(
(r) => (reader.onload = (event) => r(event?.target?.result))
)
reader.readAsArrayBuffer(file)
const arrayBuffer = await read_process
if (!arrayBuffer) return { prompt: undefined, workflow: undefined }
const arrayBuffer = (await read_process) as ArrayBuffer
const signature = String.fromCharCode(...new Uint8Array(arrayBuffer, 0, 4))
if (signature !== 'OggS') console.error('Invalid file signature.')
let oggs = 0
let header = ''
while (header.length < arrayBuffer.byteLength) {
const page = String.fromCharCode(
...new Uint8Array(
arrayBuffer,
header.length,
Math.min(4096, arrayBuffer.byteLength - header.length)
)
...new Uint8Array(arrayBuffer, header.length, header.length + 4096)
)
if (page.match('OggS\u0000')) oggs++
header += page

View File

@@ -1,19 +1,11 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import {
mockFileReaderAbort,
mockFileReaderError
} from './__fixtures__/helpers'
import { getFromPngBuffer, getFromPngFile } from './png'
afterEach(() => vi.restoreAllMocks())
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
import { getFromPngBuffer } from './png'
function createPngWithChunk(
chunkType: string,
keyword: string,
content: string | Uint8Array,
content: string,
options: {
compressionFlag?: number
compressionMethod?: number
@@ -28,11 +20,12 @@ function createPngWithChunk(
translatedKeyword = ''
} = options
const signature = new Uint8Array(PNG_SIGNATURE)
const signature = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
])
const typeBytes = new TextEncoder().encode(chunkType)
const keywordBytes = new TextEncoder().encode(keyword)
const contentBytes =
content instanceof Uint8Array ? content : new TextEncoder().encode(content)
const contentBytes = new TextEncoder().encode(content)
let chunkData: Uint8Array
if (chunkType === 'iTXt') {
@@ -73,11 +66,12 @@ function createPngWithChunk(
new DataView(lengthBytes.buffer).setUint32(0, chunkData.length, false)
const crc = new Uint8Array(4)
const iendType = new TextEncoder().encode('IEND')
const iendLength = new Uint8Array(4)
const iendCrc = new Uint8Array(4)
const total = signature.length + (4 + 4 + chunkData.length + 4) + (4 + 4 + 4)
const total = signature.length + 4 + 4 + chunkData.length + 4 + 4 + 4 + 0 + 4
const result = new Uint8Array(total)
let offset = 0
@@ -144,21 +138,6 @@ describe('getFromPngBuffer', () => {
expect(result['workflow']).toBe(workflow)
})
it('logs warning and skips iTXt chunk with unsupported compression method', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const buffer = createPngWithChunk('iTXt', 'workflow', 'data', {
compressionFlag: 1,
compressionMethod: 99
})
const result = await getFromPngBuffer(buffer)
expect(result['workflow']).toBeUndefined()
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining('Unsupported compression method 99')
)
})
it('parses compressed iTXt chunk', async () => {
const workflow = '{"nodes":[{"id":1,"type":"KSampler"}]}'
const contentBytes = new TextEncoder().encode(workflow)
@@ -184,49 +163,83 @@ describe('getFromPngBuffer', () => {
pos += chunk.length
}
const buffer = createPngWithChunk('iTXt', 'workflow', compressedBytes, {
compressionFlag: 1,
compressionMethod: 0
})
const buffer = createPngWithCompressedITXt(
'workflow',
compressedBytes,
'',
''
)
const result = await getFromPngBuffer(buffer)
expect(result['workflow']).toBe(workflow)
})
})
describe('getFromPngFile', () => {
it('reads metadata from a File object', async () => {
const workflow = '{"nodes":[]}'
const buffer = createPngWithChunk('tEXt', 'workflow', workflow)
const file = new File([buffer], 'test.png', { type: 'image/png' })
function createPngWithCompressedITXt(
keyword: string,
compressedContent: Uint8Array,
languageTag: string,
translatedKeyword: string
): ArrayBuffer {
const signature = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
])
const typeBytes = new TextEncoder().encode('iTXt')
const keywordBytes = new TextEncoder().encode(keyword)
const langBytes = new TextEncoder().encode(languageTag)
const transBytes = new TextEncoder().encode(translatedKeyword)
const result = await getFromPngFile(file)
const totalLength =
keywordBytes.length +
1 +
2 +
langBytes.length +
1 +
transBytes.length +
1 +
compressedContent.length
expect(result['workflow']).toBe(workflow)
})
const chunkData = new Uint8Array(totalLength)
let pos = 0
chunkData.set(keywordBytes, pos)
pos += keywordBytes.length
chunkData[pos++] = 0
chunkData[pos++] = 1
chunkData[pos++] = 0
chunkData.set(langBytes, pos)
pos += langBytes.length
chunkData[pos++] = 0
chunkData.set(transBytes, pos)
pos += transBytes.length
chunkData[pos++] = 0
chunkData.set(compressedContent, pos)
it('returns empty for an invalid PNG File', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const file = new File([new ArrayBuffer(8)], 'bad.png', {
type: 'image/png'
})
const lengthBytes = new Uint8Array(4)
new DataView(lengthBytes.buffer).setUint32(0, chunkData.length, false)
const result = await getFromPngFile(file)
const crc = new Uint8Array(4)
const iendType = new TextEncoder().encode('IEND')
const iendLength = new Uint8Array(4)
const iendCrc = new Uint8Array(4)
expect(result).toEqual({})
expect(console.error).toHaveBeenCalledWith('Not a valid PNG file')
})
const total = signature.length + 4 + 4 + chunkData.length + 4 + 4 + 4 + 0 + 4
const result = new Uint8Array(total)
describe('FileReader failure modes', () => {
const file = new File([new Uint8Array(16)], 'test.png')
let offset = 0
result.set(signature, offset)
offset += signature.length
result.set(lengthBytes, offset)
offset += 4
result.set(typeBytes, offset)
offset += 4
result.set(chunkData, offset)
offset += chunkData.length
result.set(crc, offset)
offset += 4
result.set(iendLength, offset)
offset += 4
result.set(iendType, offset)
offset += 4
result.set(iendCrc, offset)
it('rejects when the FileReader fires error', async () => {
mockFileReaderError('readAsArrayBuffer')
await expect(getFromPngFile(file)).rejects.toBeDefined()
})
it('rejects when the FileReader fires abort', async () => {
mockFileReaderAbort('readAsArrayBuffer')
await expect(getFromPngFile(file)).rejects.toThrow('FileReader aborted')
})
})
})
return result.buffer
}

View File

@@ -126,7 +126,6 @@ export async function getFromPngFile(
resolve(result)
}
reader.onerror = () => reject(reader.error)
reader.onabort = () => reject(new Error('FileReader aborted'))
reader.readAsArrayBuffer(file)
})
}

View File

@@ -1,42 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getSvgMetadata } from './svg'
function svgFile(content: string): File {
return new File([content], 'test.svg', { type: 'image/svg+xml' })
}
describe('getSvgMetadata', () => {
it('extracts workflow and prompt from CDATA in <metadata>', async () => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg">
<metadata><![CDATA[${JSON.stringify({
workflow: { nodes: [] },
prompt: { '1': {} }
})}]]></metadata>
<rect width="1" height="1"/>
</svg>`
const result = await getSvgMetadata(svgFile(svg))
expect(result).toEqual({
workflow: { nodes: [] },
prompt: { '1': {} }
})
})
it('returns empty when SVG has no metadata element', async () => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>'
const result = await getSvgMetadata(svgFile(svg))
expect(result).toEqual({})
})
it('returns empty when CDATA contains invalid JSON', async () => {
const svg = `<svg><metadata><![CDATA[not valid json]]></metadata></svg>`
const result = await getSvgMetadata(svgFile(svg))
expect(result).toEqual({})
})
})

View File

@@ -1,6 +1,4 @@
import fs from 'fs'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { getFromAvifFile } from './metadata/avif'
import { getFromFlacFile } from './metadata/flac'
@@ -23,183 +21,67 @@ vi.mock('./metadata/avif', () => ({
getFromAvifFile: vi.fn()
}))
afterEach(() => vi.restoreAllMocks())
function buildExifPayload(workflowJson: string): Uint8Array {
const fullStr = `workflow:${workflowJson}\0`
const strBytes = new TextEncoder().encode(fullStr)
const fixturesDir = path.resolve(__dirname, 'metadata/__fixtures__')
type AsciiIfdEntry = { tag: number; value: string }
function encodeAsciiIfd(entries: AsciiIfdEntry[]): Uint8Array {
const tableSize = 10 + 12 * entries.length
const strings = entries.map((e) => new TextEncoder().encode(`${e.value}\0`))
const totalStringBytes = strings.reduce((sum, s) => sum + s.length, 0)
const buf = new Uint8Array(tableSize + totalStringBytes)
const headerSize = 22
const buf = new Uint8Array(headerSize + strBytes.length)
const dv = new DataView(buf.buffer)
buf.set([0x49, 0x49], 0)
dv.setUint16(2, 0x002a, true)
dv.setUint32(4, 8, true)
dv.setUint16(8, entries.length, true)
let stringOffset = tableSize
for (let i = 0; i < entries.length; i++) {
const entryOffset = 10 + i * 12
dv.setUint16(entryOffset, entries[i].tag, true)
dv.setUint16(entryOffset + 2, 2, true)
dv.setUint32(entryOffset + 4, strings[i].length, true)
dv.setUint32(entryOffset + 8, stringOffset, true)
buf.set(strings[i], stringOffset)
stringOffset += strings[i].length
}
dv.setUint16(8, 1, true)
dv.setUint16(10, 0, true)
dv.setUint16(12, 2, true)
dv.setUint32(14, strBytes.length, true)
dv.setUint32(18, 22, true)
buf.set(strBytes, 22)
return buf
}
type WebpChunk = { type: string; payload: Uint8Array }
function buildWebp(precedingChunkLength: number, workflowJson: string): File {
const exifPayload = buildExifPayload(workflowJson)
const precedingPadded = precedingChunkLength + (precedingChunkLength % 2)
const totalSize = 12 + (8 + precedingPadded) + (8 + exifPayload.length)
function wrapInWebp(chunks: WebpChunk[]): File {
let payloadSize = 0
for (const c of chunks) {
payloadSize += 8 + c.payload.length + (c.payload.length % 2)
}
const totalSize = 12 + payloadSize
const buf = new Uint8Array(totalSize)
const dv = new DataView(buf.buffer)
const buffer = new Uint8Array(totalSize)
const dv = new DataView(buffer.buffer)
buf.set([0x52, 0x49, 0x46, 0x46], 0)
buffer.set([0x52, 0x49, 0x46, 0x46], 0)
dv.setUint32(4, totalSize - 8, true)
buf.set([0x57, 0x45, 0x42, 0x50], 8)
buffer.set([0x57, 0x45, 0x42, 0x50], 8)
let offset = 12
for (const c of chunks) {
for (let i = 0; i < 4; i++) {
buf[offset + i] = c.type.charCodeAt(i)
}
dv.setUint32(offset + 4, c.payload.length, true)
buf.set(c.payload, offset + 8)
offset += 8 + c.payload.length + (c.payload.length % 2)
}
buffer.set([0x56, 0x50, 0x38, 0x20], 12)
dv.setUint32(16, precedingChunkLength, true)
return new File([buf], 'test.webp', { type: 'image/webp' })
}
const exifStart = 20 + precedingPadded
buffer.set([0x45, 0x58, 0x49, 0x46], exifStart)
dv.setUint32(exifStart + 4, exifPayload.length, true)
buffer.set(exifPayload, exifStart + 8)
function exifChunk(
entries: AsciiIfdEntry[],
options: { withExifPrefix?: boolean } = {}
): WebpChunk {
const ifd = encodeAsciiIfd(entries)
if (!options.withExifPrefix) {
return { type: 'EXIF', payload: ifd }
}
const prefixed = new Uint8Array(6 + ifd.length)
prefixed.set(new TextEncoder().encode('Exif\0\0'), 0)
prefixed.set(ifd, 6)
return { type: 'EXIF', payload: prefixed }
return new File([buffer], 'test.webp', { type: 'image/webp' })
}
describe('getWebpMetadata', () => {
it('returns empty when the file is not a valid WEBP', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const file = new File([new Uint8Array(12)], 'fake.webp')
it('finds workflow when a preceding chunk has odd length (RIFF padding)', async () => {
const workflow = '{"nodes":[]}'
const file = buildWebp(3, workflow)
const metadata = await getWebpMetadata(file)
expect(metadata).toEqual({})
expect(console.error).toHaveBeenCalledWith('Not a valid WEBP file')
expect(metadata.workflow).toBe(workflow)
})
it('returns empty when a valid WEBP has no EXIF chunk', async () => {
const file = wrapInWebp([
{ type: 'VP8 ', payload: new Uint8Array([0, 0, 0, 0]) }
])
it('finds workflow when preceding chunk has even length (no padding)', async () => {
const workflow = '{"nodes":[1]}'
const file = buildWebp(4, workflow)
const metadata = await getWebpMetadata(file)
expect(metadata).toEqual({})
})
it('extracts workflow and prompt from EXIF without prefix', async () => {
const bytes = fs.readFileSync(path.join(fixturesDir, 'with_metadata.webp'))
const file = new File([bytes], 'test.webp', { type: 'image/webp' })
const metadata = await getWebpMetadata(file)
expect(metadata).toEqual({
workflow:
'{"nodes":[{"id":1,"type":"KSampler","pos":[100,100],"size":[200,200]}]}',
prompt: '{"1":{"class_type":"KSampler","inputs":{}}}'
})
})
it('extracts workflow and prompt from EXIF with Exif\\0\\0 prefix', async () => {
const bytes = fs.readFileSync(
path.join(fixturesDir, 'with_metadata_exif_prefix.webp')
)
const file = new File([bytes], 'test.webp', { type: 'image/webp' })
const metadata = await getWebpMetadata(file)
expect(metadata).toEqual({
workflow:
'{"nodes":[{"id":1,"type":"KSampler","pos":[100,100],"size":[200,200]}]}',
prompt: '{"1":{"class_type":"KSampler","inputs":{}}}'
})
})
it('walks past odd-length preceding chunks (RIFF padding)', async () => {
const file = wrapInWebp([
{ type: 'VP8 ', payload: new Uint8Array(3) },
exifChunk([{ tag: 0, value: 'workflow:{"a":1}' }])
])
const metadata = await getWebpMetadata(file)
expect(metadata).toEqual({ workflow: '{"a":1}' })
})
})
describe('getLatentMetadata', () => {
function buildSafetensors(headerObj: object): File {
const headerBytes = new TextEncoder().encode(JSON.stringify(headerObj))
const buf = new Uint8Array(8 + headerBytes.length)
const dv = new DataView(buf.buffer)
dv.setUint32(0, headerBytes.length, true)
dv.setUint32(4, 0, true)
buf.set(headerBytes, 8)
return new File([buf], 'test.safetensors')
}
it('extracts __metadata__ from a safetensors header', async () => {
const workflow =
'{"nodes":[{"id":1,"type":"KSampler","pos":[100,100],"size":[200,200]}]}'
const prompt = '{"1":{"class_type":"KSampler","inputs":{}}}'
const file = buildSafetensors({
__metadata__: { workflow, prompt },
'tensor.weight': { dtype: 'F32', shape: [1], data_offsets: [0, 4] }
})
const metadata = await getLatentMetadata(file)
expect(metadata).toEqual({ workflow, prompt })
})
it('returns undefined when the safetensors header has no __metadata__', async () => {
const file = buildSafetensors({
'tensor.weight': { dtype: 'F32', shape: [1], data_offsets: [0, 4] }
})
const metadata = await getLatentMetadata(file)
expect(metadata).toBeUndefined()
})
it('returns undefined for a truncated or malformed file', async () => {
const file = new File([new Uint8Array(4)], 'bad.safetensors')
const metadata = await getLatentMetadata(file)
expect(metadata).toBeUndefined()
expect(metadata.workflow).toBe(workflow)
})
})
@@ -234,3 +116,37 @@ describe('format-specific metadata wrappers', () => {
expect(result).toEqual({ workflow: '{"avif":1}' })
})
})
const buildSafetensors = (header: Record<string, unknown>): File => {
const headerJson = JSON.stringify(header)
const headerBytes = new TextEncoder().encode(headerJson)
const buf = new ArrayBuffer(8 + headerBytes.length)
const dv = new DataView(buf)
dv.setUint32(0, headerBytes.length, true)
dv.setUint32(4, 0, true)
new Uint8Array(buf, 8).set(headerBytes)
return new File([buf], 'x.safetensors')
}
describe('getLatentMetadata', () => {
it('returns the __metadata__ object from a safetensors header', async () => {
const file = buildSafetensors({
__metadata__: { workflow: '{"nodes":[]}', extra: 'value' },
'tensor.weight': { dtype: 'F32', shape: [1], data_offsets: [0, 4] }
})
const result = await getLatentMetadata(file)
expect(result).toEqual({ workflow: '{"nodes":[]}', extra: 'value' })
})
it('resolves undefined when header has no __metadata__ entry', async () => {
const file = buildSafetensors({
'tensor.weight': { dtype: 'F32', shape: [1], data_offsets: [0, 4] }
})
const result = await getLatentMetadata(file)
expect(result).toBeUndefined()
})
})

View File

@@ -105,17 +105,14 @@ export function getWebpMetadata(file: File) {
...webp.slice(offset, offset + 4)
)
if (chunk_type === 'EXIF') {
let exifOffset = offset + 8
let exifLength = chunk_length
if (
String.fromCharCode(...webp.slice(exifOffset, exifOffset + 6)) ==
String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) ==
'Exif\0\0'
) {
exifOffset += 6
exifLength -= 6
offset += 6
}
const data = parseExifData(
webp.slice(exifOffset, exifOffset + exifLength)
let data = parseExifData(
webp.slice(offset + 8, offset + 8 + chunk_length)
)
for (const key in data) {
const value = data[Number(key)]
@@ -134,38 +131,30 @@ export function getWebpMetadata(file: File) {
r(txt_chunks)
}
reader.onerror = () => r({})
reader.onabort = () => r({})
reader.readAsArrayBuffer(file)
})
}
export function getLatentMetadata(
file: File
): Promise<Record<string, string> | undefined> {
export function getLatentMetadata(file: File): Promise<Record<string, string>> {
return new Promise((r) => {
const reader = new FileReader()
reader.onload = (event) => {
try {
const safetensorsData = new Uint8Array(
event.target?.result as ArrayBuffer
const safetensorsData = new Uint8Array(
event.target?.result as ArrayBuffer
)
const dataView = new DataView(safetensorsData.buffer)
let header_size = dataView.getUint32(0, true)
let offset = 8
let header = JSON.parse(
new TextDecoder().decode(
safetensorsData.slice(offset, offset + header_size)
)
const dataView = new DataView(safetensorsData.buffer)
const headerSize = dataView.getUint32(0, true)
const offset = 8
const header = JSON.parse(
new TextDecoder().decode(
safetensorsData.slice(offset, offset + headerSize)
)
)
r(header.__metadata__)
} catch {
r(undefined)
}
)
r(header.__metadata__)
}
reader.onerror = () => r(undefined)
reader.onabort = () => r(undefined)
const slice = file.slice(0, 1024 * 1024 * 4)
var slice = file.slice(0, 1024 * 1024 * 4)
reader.readAsArrayBuffer(slice)
})
}