Compare commits

..

5 Commits

Author SHA1 Message Date
huang47
0c6b8a64e6 test: remove default-state and delegation-echo tests from useCurrentUser 2026-07-06 12:05:12 -07:00
huang47
b2ad43746d test: replace fromAny and vi.mock('vue-i18n') with lint-compliant equivalents
- authStore.test.ts: remove vi.mock('vue-i18n'), add vi.mock('@/i18n') for key passthrough; replace double-casts with fromPartial
- appModeStore.test.ts: remove fromAny import; replace LGraphNode casts with createMockLGraphNode; use fromPartial for workflow/widget mocks; restructure createWorkflowWithLinearData to avoid PartialDeep type conflict
- domWidgetStore.test.ts: replace Partial<LGraphNode> double-cast with createMockLGraphNode
2026-07-03 09:39:36 -07:00
huang47
817354af0c refactor: dedupe Firebase mock credential casts in authStore.test.ts
Isolated cleanup, no test-behavior change: extracts the repeated
{ user } as Partial<UserCredential> as UserCredential double-cast
into an asUserCredential() helper.
2026-07-02 14:30:46 -07:00
huang47
95257dbba7 test: keep authStore coverage additions free of unrelated refactor
Coverage-only commit: reverts the incidental asUserCredential() helper
extraction so this PR's diff carries no deletions beyond the one
necessary trailing comma. The helper returns as its own commit next.
2026-07-02 14:28:49 -07:00
huang47
08648920af test: cover session UI stores 2026-07-02 09:00:38 -07:00
63 changed files with 1939 additions and 2432 deletions

View File

@@ -70,39 +70,4 @@ test.describe('Customer story detail @smoke', () => {
'/customers/series-entertainment'
)
})
test('renders a Creative Campus story with its education blocks', async ({
page
}) => {
await page.goto('/customers/xindi-zhang')
await expect(
page.getByRole('heading', {
level: 1,
name: /The tool that expands my art/i
})
).toBeVisible()
const nav = page.getByRole('navigation', { name: 'Category filter' })
await expect(nav.getByRole('button', { name: 'INTRO' })).toBeVisible()
await expect(nav.getByRole('button', { name: 'AT A GLANCE' })).toBeVisible()
// At a glance block (AtAGlance component) with its spec rows.
await expect(
page.getByRole('heading', { name: 'At a glance' })
).toBeVisible()
await expect(page.getByText('Program', { exact: true })).toBeVisible()
// Workflow download button (Download component).
await expect(
page.getByRole('link', {
name: /Download Xindi's style transfer workflow/i
})
).toBeVisible()
// Shared education call to action (EducationCta component).
await expect(
page.getByRole('link', { name: /Explore the Education Program/i })
).toBeVisible()
})
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

View File

@@ -1,3 +1,3 @@
<svg width="20" height="32" viewBox="0 0 20 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20 32V0C20 5.39616 15.5172 9.78053 10 9.78053C4.48276 9.78053 0 5.416 0 0V32C0 26.6038 4.48276 22.2195 10 22.2195C15.5172 22.2195 20 26.6038 20 32Z" fill="#F2FF59"/>
<svg preserveAspectRatio="none" width="100%" height="100%" overflow="visible" style="display: block;" viewBox="0 0 20 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path id="Vector" d="M20 32V0C20 5.39616 15.5172 9.78053 10 9.78053C4.48276 9.78053 0 5.416 0 0V32C0 26.6038 4.48276 22.2195 10 22.2195C15.5172 22.2195 20 26.6038 20 32Z" fill="var(--fill-0, #F2FF59)"/>
</svg>

Before

Width:  |  Height:  |  Size: 279 B

After

Width:  |  Height:  |  Size: 380 B

View File

@@ -4,24 +4,16 @@ import { render } from 'astro:content'
import type { Locale } from '../../i18n/translations'
import type { CustomerStoryEntry } from '../../utils/customers'
import ArticleNav from './ArticleNav.vue'
import AtAGlance from './content/AtAGlance.astro'
import AuthorBio from './content/AuthorBio.astro'
import BulletList from './content/BulletList.astro'
import Contributors from './content/Contributors.astro'
import Download from './content/Download.astro'
import EducationCta from './content/EducationCta.astro'
import Embed from './content/Embed.astro'
import Figure from './content/Figure.astro'
import Heading from './content/Heading.astro'
import Heading4 from './content/Heading4.astro'
import Link from './content/Link.astro'
import ListItem from './content/ListItem.astro'
import Paragraph from './content/Paragraph.astro'
import Quote from './content/Quote.astro'
import ReadMore from './content/ReadMore.vue'
import Section from './content/Section.astro'
import Steps from './content/Steps.astro'
import Video from './content/Video.astro'
interface Props {
entry: CustomerStoryEntry
@@ -42,26 +34,18 @@ const categories = entry.data.sections.map((section) => ({
// components (Section, Figure, ...) are used directly inside the MDX body.
const contentComponents = {
p: Paragraph,
a: Link,
h3: Heading,
h4: Heading4,
ul: BulletList,
li: ListItem,
Section,
Figure,
Quote,
Contributors,
Steps,
AtAGlance,
AuthorBio,
Download,
EducationCta,
Embed,
Video
Steps
}
---
<section class="max-w-9xl mx-auto px-4 pt-8 pb-24 lg:px-20 lg:pt-24 lg:pb-40">
<section class="px-4 pt-8 pb-24 lg:px-20 lg:pt-24 lg:pb-40">
<div class="lg:flex lg:gap-16">
<aside class="hidden scrollbar-none lg:block lg:w-48 lg:shrink-0">
<div class="sticky top-32">

View File

@@ -1,29 +0,0 @@
---
interface Row {
label: string
value: string
}
interface Props {
rows: Row[]
}
const { rows } = Astro.props
---
<div
class="my-8 overflow-hidden rounded-2xl border border-white/10 bg-site-bg-soft"
>
<dl class="divide-y divide-white/10">
{
rows.map((row) => (
<div class="flex flex-col gap-1 p-5 sm:flex-row sm:gap-6">
<dt class="text-primary-comfy-yellow shrink-0 text-xs font-bold tracking-widest uppercase sm:w-44">
{row.label}
</dt>
<dd class="text-sm/relaxed text-primary-comfy-canvas">{row.value}</dd>
</div>
))
}
</dl>
</div>

View File

@@ -1,60 +0,0 @@
---
interface Author {
name?: string
role?: string
photo?: string
bio?: string
}
interface Props {
label?: string
people: Author[]
}
const { label, people } = Astro.props
const hasBioSlot = Astro.slots.has('default')
---
<div class="mt-12 border-t border-white/10 pt-8">
{
label && (
<span class="text-primary-comfy-yellow text-xs font-bold tracking-widest uppercase">
{label}
</span>
)
}
<div class="mt-4 space-y-8">
{
people.map((person) => (
<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:gap-6">
{person.photo && (
<img
src={person.photo}
alt={person.name ?? ''}
class="size-20 shrink-0 rounded-full object-cover"
/>
)}
<div>
{person.name && (
<p class="text-sm font-semibold text-primary-comfy-canvas">
{person.name}
{person.role && (
<span class="text-primary-warm-gray"> · {person.role}</span>
)}
</p>
)}
{person.bio ? (
<p class="mt-2 text-sm/relaxed text-primary-comfy-canvas italic">
{person.bio}
</p>
) : hasBioSlot ? (
<p class="mt-2 text-sm/relaxed text-primary-comfy-canvas italic">
<slot />
</p>
) : null}
</div>
</div>
))
}
</div>
</div>

View File

@@ -14,7 +14,7 @@ interface Props {
const { label, people } = Astro.props
---
<div class="mt-8 rounded-2xl bg-site-bg-soft p-6">
<div class="mt-8 rounded-2xl bg-(--site-bg-soft) p-6">
<span
class="text-primary-comfy-yellow text-xs font-bold tracking-widest uppercase"
>

View File

@@ -1,19 +0,0 @@
---
interface Props {
href: string
label: string
newTab?: boolean
}
const { href, label, newTab = false } = Astro.props
---
<a
href={href}
download={newTab ? undefined : true}
target={newTab ? '_blank' : undefined}
rel={newTab ? 'noopener noreferrer' : undefined}
class="text-primary-comfy-yellow my-4 inline-block text-sm font-semibold underline underline-offset-2 transition-opacity hover:opacity-80"
>
{label}
</a>

View File

@@ -1,15 +0,0 @@
---
import Link from './Link.astro'
---
<div
class="border-primary-comfy-yellow mt-12 rounded-2xl border-l-4 bg-site-bg-soft p-8"
>
<p class="text-base/relaxed text-primary-comfy-canvas">
<strong class="font-semibold">Teaching with ComfyUI?</strong> The Comfy Education
Program is live: educational pricing, classroom cloud accounts on one invoice,
<Link href="https://comfy.org/education">Explore the Education Program</Link> or
<Link href="https://tally.so/r/Xx97lL">apply to be a part of the Creative
Campus program</Link> if you're interested in exploring a deeper partnership with Comfy.
</p>
</div>

View File

@@ -1,22 +0,0 @@
---
interface Props {
src: string
title: string
}
const { src, title } = Astro.props
---
<div
class="my-8 aspect-video overflow-hidden rounded-2xl border border-white/10 bg-black"
>
<iframe
src={src}
title={title}
class="size-full"
loading="lazy"
allow="autoplay; fullscreen; picture-in-picture; clipboard-write"
referrerpolicy="strict-origin-when-cross-origin"
sandbox="allow-scripts allow-same-origin allow-presentation allow-popups"
></iframe>
</div>

View File

@@ -6,15 +6,14 @@ interface Props {
}
const { src, alt, caption } = Astro.props
const hasCaptionSlot = Astro.slots.has('default')
---
<figure class="my-8">
<img src={src} alt={alt} class="w-full rounded-2xl object-cover" />
{
(hasCaptionSlot || caption) && (
caption && (
<figcaption class="mt-3 text-xs text-primary-comfy-canvas">
{hasCaptionSlot ? <slot /> : caption}
{caption}
</figcaption>
)
}

View File

@@ -1,6 +0,0 @@
---
---
<h4 class="mt-6 mb-2 text-base font-semibold text-primary-comfy-canvas">
<slot />
</h4>

View File

@@ -1,15 +0,0 @@
---
interface Props {
href: string
}
const { href } = Astro.props
const isExternal = /^https?:\/\//.test(href)
---
<a
href={href}
target={isExternal ? '_blank' : undefined}
rel={isExternal ? 'noopener noreferrer' : undefined}
class="text-primary-comfy-yellow underline underline-offset-2 transition-opacity hover:opacity-80"
><slot /></a>

View File

@@ -1,20 +1,16 @@
---
interface Props {
name?: string
name: string
}
const { name } = Astro.props
---
<blockquote
class="border-primary-comfy-yellow my-8 rounded-2xl border-l-4 bg-site-bg-soft p-8"
class="border-primary-comfy-yellow my-8 rounded-2xl border-l-4 bg-(--site-bg-soft) p-8"
>
<p class="text-lg/relaxed font-light text-primary-comfy-canvas italic">
"<slot />"
</p>
{
name && (
<p class="text-primary-comfy-yellow mt-4 text-sm font-semibold">{name}</p>
)
}
<p class="text-primary-comfy-yellow mt-4 text-sm font-semibold">{name}</p>
</blockquote>

View File

@@ -1,22 +0,0 @@
---
import VideoPlayer from '../../common/VideoPlayer.vue'
interface Props {
src: string
poster?: string
caption?: string
}
const { src, poster, caption } = Astro.props
---
<figure class="my-8">
<VideoPlayer src={src} poster={poster} client:visible />
{
caption && (
<figcaption class="mt-3 text-xs text-primary-comfy-canvas">
{caption}
</figcaption>
)
}
</figure>

View File

@@ -63,12 +63,8 @@ function bodySectionIds(body: string): string[] {
const stories = loadStories()
it('finds customer stories in every locale', () => {
for (const locale of locales) {
const prefix = `${locale}/`
const inLocale = stories.filter((story) => story.file.startsWith(prefix))
expect(inLocale.length).toBeGreaterThan(0)
}
it('finds all ten customer stories', () => {
expect(stories).toHaveLength(10)
})
describe.for(stories)('$file', ({ frontmatter, body }) => {

View File

@@ -1,148 +0,0 @@
---
title: "Seeing the world in new ways: how Prof. Golan Levin teaches with ComfyUI at Carnegie Mellon University"
category: "CREATIVE CAMPUS SHOWCASE"
description: "\"For me, ComfyUI is not just about generative AI. It's an image-processing workstation for completely new kinds of work.\""
cover: "https://media.comfy.org/website/customers/golan-levin/cover.png"
order: 7
sections:
- id: topic-1
label: "INTRO"
- id: topic-2
label: "WHERE COMFYUI FITS"
- id: topic-3
label: "IMAGE SYNTHESIS"
- id: topic-4
label: "IMAGE ANALYSIS"
- id: topic-5
label: "THE CV LAB"
- id: topic-6
label: "AT A GLANCE"
- id: topic-7
label: "STUDENT WORK"
---
<Section id="topic-1">
<Figure src="https://media.comfy.org/website/customers/golan-levin/augmented-hand.jpg" alt="Golan Levin, Augmented Hand Series" caption="Golan Levin, Augmented Hand Series (2014), with Chris Sugrue and Kyle McDonald. Photo: Gerlinde de Geus, courtesy Cinekid." />
For many people, AI in the arts means image generation. But Levin has spent much of the past two decades teaching artists how computers can interpret, analyze, and measure the visual world. His own artworks have long explored machine perception through real-time computer vision systems, and since 2024 he has increasingly used ComfyUI to teach these principles.
For Levin, ComfyUI is less an image generator than an image-processing workbench. Students use it to assemble custom workflows for segmentation, tracking, depth estimation, and other forms of computational perception. The result is an environment where artists can experiment directly with research-grade machine learning tools and combine them into systems of their own design.
</Section>
<Section id="topic-2">
### Where does ComfyUI fit in what you're trying to do?
I'm training creative technologists and technologically literate artists. The typical student in my Creative Coding class is a true hybrid: an art or design undergraduate who is also studying computer science, human-computer interaction, or information science. They have strong visual abilities, strong cultural literacy, and strong algorithmic thinking skills, but my course may be the first time they've had the opportunity to bring those together.
To me, that means giving students tools they can understand, modify, and remix to make systems of their own design, rather than treating creative software as a fixed given. That's why I'm such a proponent of community-driven, open-source software development toolkits for the arts.
<Quote>ComfyUI is the first AI tool I've found with both a low floor and a high ceiling. It's incredibly powerful and flexible, in terms of allowing artists to design their own AI workflows with the latest cutting-edge algorithms. But it also leapfrogs the headaches of coping with quirky GitHub repos and obsolete Colab notebooks.</Quote>
### What were students stuck on before?
Students often found themselves caught between two worlds. On one side were commercial AI tools that produced impressive results but offered limited opportunities for customization. On the other side were research projects published by universities and laboratories, where the software was often difficult to install, poorly documented, or already out of date.
ComfyUI bridges that gap. It gives students access to state-of-the-art algorithms through an environment they can understand, modify, and extend. Instead of adapting their ideas to fit a tool's built-in workflow, they can build workflows that reflect their own interests and questions.
<Quote>My students are explorers. They're artists who can write code and want to build systems that haven't existed before.</Quote>
</Section>
<Section id="topic-3">
### The first exercise: a p5.js sketch driving image synthesis, inside ComfyUI
In one of Levin's introductory exercises — students' first exposure to the ComfyUI environment — they write a simple p5.js sketch directly inside ComfyUI, then use the shapes they draw, plus a text prompt, to guide a Stable Diffusion image synthesis. They document the pairs of images it produces: their JavaScript canvas drawing on the left, and the AI synthesis on the right. Having already spent a few weeks fighting to get nuance out of p5.js, they're tickled to get these results from simple shapes, and they learn a lot about how Stable Diffusion works.
<Figure src="https://media.comfy.org/website/customers/golan-levin/p5-landscape.png" alt="p5.js ellipses guiding a Stable Diffusion synthesis" caption={`Some wide ellipses drawn in p5.js (left) guiding a Stable Diffusion synthesis with the prompt "rolling hills, foggy day" (right).`} />
It runs on a node-based canvas that art students pick up quickly, because it works like tools they already know.
<Figure src="https://media.comfy.org/website/customers/golan-levin/p5-workflow.png" alt="Template ComfyUI workflow using the ComfyUI-p5js-node" caption="The template ComfyUI workflow students receive. It uses the custom ComfyUI-p5js-node by Ben Fox. From Levin's 60-212 course repo." />
*Try it yourself: [json file](https://media.comfy.org/website/customers/golan-levin/p5-in-comfy.json) (Comfy Local only)*
</Section>
<Section id="topic-4">
### Many artists start off by using ComfyUI for generative AI. You use it differently.
Maybe so. I'm interested in AI as a framework for expanded perception, so a lot of how I've used machine learning and computer vision over the past 25 years has been for image analysis, rather than image synthesis. Essentially, I use computer vision to understand video and images, and then use the information I extract to create new kinds of interactive experiences. In the classroom, I use ComfyUI to help teach students how to "see like a machine." So I have students use ComfyUI as a framework for analyzing images, not just generating them. For example, I ask them to take an input image and then use AI to compute new ones from it, such as a semantic segmentation ("which pixels belong to the elephant?") and a monocular depth estimate ("how far away is each pixel?"). Then the students build an interactive piece that interprets the original image, but using five channels of information instead of three: the usual red, green, and blue, plus depth, plus segmentation. In my demo project, the segmentation colors the elephant pink, and the background pixels change size based on how far away the AI thinks they are.
<Figure src="https://media.comfy.org/website/customers/golan-levin/depth-segmentation.png" alt="Semantic segmentation and monocular depth analysis in ComfyUI" caption={`An input image analyzed inside ComfyUI: semantic segmentation and monocular depth, feeding a five-channel "Custom Pixel" exercise. From Levin's 60-212 course repo.`} />
*Try it yourself: [demo project](https://editor.p5js.org/golan/sketches/-_cFmLtoP) · [lesson plan & workflow](https://github.com/golanlevin/60-212/tree/main/lectures/comfy/image_analysis#3-segment-the-image-with-ai)*
*Workflow files: download the [.json](https://media.comfy.org/website/customers/golan-levin/image-analysis-workflow.json), or the [.png with the workflow embedded in its metadata](https://media.comfy.org/website/customers/golan-levin/image-analysis-workflow.png) (drag it into ComfyUI to load the graph).*
<Quote>I want students to understand that AI is not only a tool for generating images. It's also a tool for perception, measurement, and analysis.</Quote>
The computer vision tools built for this are usually aimed at developers and enterprises. They assume an engineering workflow. I wanted my art students to get to segmentation, depth, and tracking inside an environment they already think in, without standing up a production pipeline first.
### What changed once ComfyUI was in the workflow?
Two things. First, it runs on a node-based canvas that many art students already understand from environments like TouchDesigner, Max/MSP, and Grasshopper — except it runs in a browser and it's for AI. As a result, students can focus on the ideas behind machine learning workflows instead of first learning an entirely new interaction paradigm. Second, it collapses the distance between a research lab and a classroom.
<Quote>There's a fast pipeline from the lab to your classroom. It's become commonplace for enthusiasts to convert AI research code into Comfy nodes, often within days of their release.</Quote>
One of the most remarkable things about the ComfyUI ecosystem is how quickly new research becomes accessible. A computer-vision paper might appear at CVPR or ICCV, and within days someone in the community has wrapped it as a reusable ComfyUI node. For educators, that dramatically shortens the distance between a research laboratory and a classroom. Instead of spending weeks reconstructing an experimental software environment, students can begin exploring the underlying ideas almost immediately.
The cloud matters for accessibility and equity, too. Most of my students don't have big GPU workstations, and I don't want their access to advanced tools to depend on the caliber of their personal hardware. Cloud platforms make it possible for everyone in a class to work in the same environment, with the same models, regardless of what laptop they happen to own.
</Section>
<Section id="topic-5">
### In your advanced Experimental Capture studio, you've turned ComfyUI into a computer-vision lab.
The goal of this course is to use technologies to help us see the world in new ways: the very fast, the very slow, the very small, the very large, and in spectra beyond human perception, like IR and UV. It's about cultivating the students' curiosity. But the limitation in this studio is hardware. We have one camera that can shoot 100,000 frames per second, one high-resolution thermal camera, and access to one electron microscope — but we've got 20 students. We can't always queue them all up for one exotic camera; it's a bottleneck.
<Quote>I need to give them tools they can use to see the world in new ways, that they can all run on their own hardware.</Quote>
ComfyUI allows students to use their own phones to ask questions they couldn't before. So they duct-tape their phone camera to a window, record the world going by, and then track things with the LocateAnything and SAM3 ComfyUI nodes, producing data files that distill what the camera saw. ComfyUI becomes a laboratory for computational observation, allowing students to ask questions of images and videos that would otherwise be difficult to formulate.
### You also wrap niche research libraries into ComfyUI nodes yourself.
One of the remarkable things about the ComfyUI ecosystem is the community that forms around it. There's a hero of mine on GitHub, Kijai, who keeps taking libraries from computer vision labs and turning them into ComfyUI nodes. He's made hundreds, probably doing more than anyone to turn lab-grade models into tools anyone can use. My students and I are starting to do this too. Niche is the right word. Right now I have my eye on a zoology lab that released a good library for tracking insect legs. The people who made it probably don't even know what ComfyUI is. But I want that algorithm for my students, and there's gotta be someone else out there who would love it too.
### What's the bigger pattern you see in your students?
My students are explorers. They see a new tool and immediately start wondering what else it could be connected to. They explore: I should be able to combine this thing with that other thing. That's the whole reason to give them a system they can build on, instead of a tool that tells them what they're allowed to do.
<Quote>We're educating students who want to invent new forms and experiences, not just reproduce existing ones.</Quote>
</Section>
<Section id="topic-6" title="At a glance">
<AtAGlance rows={[
{ label: "Courses", value: "Intermediate Studio: Creative Coding (60-212); Experimental Capture (co-taught with Nica Ross)" },
{ label: "Level", value: "Undergraduate (sophomore studio + advanced studio, ~20 students)" },
{ label: "Setup", value: "Cloud-hosted ComfyUI; runs on students' own laptops" },
{ label: "Core techniques", value: "p5.js-driven synthesis; semantic segmentation; monocular depth; LocateAnything + SAM3 tracking" },
{ label: "Distinctive angle", value: "ComfyUI as computer-vision lab, not just a generator" }
]} />
</Section>
<Section id="topic-7" title="Student work">
<Figure src="https://media.comfy.org/website/customers/golan-levin/student-tippi.png" alt="Student work by Tippi Li" caption={`"nuclear explosion" by Tippi Li`} />
<Figure src="https://media.comfy.org/website/customers/golan-levin/student-xiao.png" alt="Student work by Xiao Yuan" caption={`"Chinese painting, plants, ink, transparent" by Xiao Yuan`} />
<Figure src="https://media.comfy.org/website/customers/golan-levin/student-aarnav.png" alt="Student work by Aarnav Patel" caption={`"NASA space image of a new cosmos detected" by Aarnav Patel`} />
<Figure src="https://media.comfy.org/website/customers/golan-levin/student-jeffrey.png" alt="Student work by Jeffrey Wang" caption={`"Dream Scene Painting" by Jeffrey Wang`} />
<Figure src="https://media.comfy.org/website/customers/golan-levin/student-kai.gif" alt="Student work by Kai Okorodudu" caption={`"Electric hand" by Kai Okorodudu`} />
</Section>
<AuthorBio people={[{ name: "Golan Levin", photo: "https://media.comfy.org/website/customers/golan-levin/author-golan.png" }]}>Golan Levin is a Professor of Computational Art at Carnegie Mellon University and co-author, with Tega Brain, of "Code as Creative Medium." This fall he is teaching two CMU courses with ComfyUI: "Intermediate Studio: Creative Coding" (60-212), built around p5.js, and "Experimental Capture," a studio in computational and expanded photography he co-teaches with Nica Ross. Levin is also widely known for interactive art installations driven by real-time machine vision, such as his [Augmented Hand Series](https://flong.com/archive/projects/augmented-hand-series/index.html) (2014), created with Kyle McDonald and Christine Sugrue.</AuthorBio>
<EducationCta />

View File

@@ -1,149 +0,0 @@
---
title: "From Node Graph to Building Façade: how Ina Conradi's NTU students compose architectural-scale public art with ComfyUI"
category: "CREATIVE CAMPUS SHOWCASE"
description: "At NTU in Singapore, Ina Conradi's students compose 90-second films for building-sized LED walls that prompt boxes cannot render but ComfyUI can, work that travels from campus to Hangzhou's West Lake Media Façade and a million viewers a day."
cover: "https://media.comfy.org/website/customers/ina-conradi/cover.png"
order: 6
sections:
- id: topic-1
label: "INTRO"
- id: topic-2
label: "THE CANVAS"
- id: topic-3
label: "WHY COMFYUI"
- id: topic-4
label: "THE 2026 BRIEF"
- id: topic-5
label: "STUDENT WORK"
- id: topic-6
label: "PUBLIC SCREENS"
- id: topic-7
label: "AT A GLANCE"
---
<Section id="topic-1">
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig1-quantum-logos.jpg" alt="Quantum Logos (Vision Serpent) on the Media Art Nexus LED screen" caption="Quantum Logos (Vision Serpent), Mark Chavez and Ina Conradi. Experimental animation, Media Art Nexus LED screen (15 m × 2 m), Singapore. Photo: Quek Jia Liang." />
### Building an AI art pipeline from studio to screen
Ina Conradi has written and taught NTU's two AI courses since 2022: DM2012, Explorations in AI-Generated Art (undergraduate), and AP7055, Art in the Age of the Creative Machine (postgraduate). Each runs about 30 students a semester. Working alongside her on the production pipeline is Mark Chavez, an animation veteran (DreamWorks, Rhythm & Hues) and early ComfyUI adopter. Together they co-curate the platform those courses build for: a 15-metre by 2-metre LED wall installed at NTU's North Spine in 2016 as Media Art Nexus, now run by NTU Museum as NTU Index and still taking new work each semester.
Work from the wall has travelled to giant public screens in Singapore (Ten Square), Hangzhou, and Chongqing, and into collaborations with Bauhaus University, the University of the Arts Berlin, and the Elbphilharmonie in Hamburg.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig2-nature-sanctuary.jpg" alt="Nature Sanctuary 3000 on the West Lake Media Façade" caption="Nature Sanctuary 3000, Sowmya Sreeshna. Experimental animation, West Lake Media Façade (170 m × 18 m), Hangzhou, China. Photo: Limpid Art." />
</Section>
<Section id="topic-2">
### Ina, your students don't make films for laptops. Why screens the size of buildings?
Because the format teaches. A 90-second film at 6K across, in an 8:1 panorama, cannot be a lucky prompt. It has to be composed. And the screens are real: the strongest student work plays on NTU Index, our 15-metre by 2-metre wall on campus, and travels to urban façades in China and Europe through the City Digital Skin Art Festival (CDSA). When a student knows a million people a day might walk past their film in Hangzhou, the conversation about craft changes.
### Mark, describe the canvas.
Basically, we do compositions for really large media LED screens in Singapore and China. We have a screen that's eight by one in Singapore. It's 5,888 by 768 pixels.Students create images in the class, usually about 6K resolution across, a long landscape panorama. The output is 90-second short films. Two minutes, 90 seconds. I'm not going to change. I love that format because it's manageable within the class.
</Section>
<Section id="topic-3">
### That format breaks most AI tools. What happened?
Runway is one of the tools we use, on an educational plan that has worked well for the school. The constraint we hit is format: Runway works in 16:9, and our 6K panoramas fall outside that. Last semester Midjourney gave us trouble at our resolution, and the upscale was difficult. So we're expanding the palette and bringing in ComfyUI alongside what we already run.
<Quote>ComfyUI gave the cleanest results. Upscaling to 8K at a 1-by-8 panorama after composition is genuinely hard, and ComfyUI is the only pipeline that lets students compose image, motion, and upscale models together.</Quote>
### What about the budget side?
Budget will keep being an issue. The school supports us well, but new tools arrive every semester and students want to try them and build their own pipelines. Monthly per-seat licenses don't fit how a semester runs. Running ComfyUI locally is hard for students: most laptops don't have a GPU with enough VRAM, and getting it working takes real trial and error. Many would rather work from home, but the hardware blocks them, so they come into the lab. Others used Comfy Cloud. It charges a subscription, but it still cost significantly less than the prepaid tools, and the results were better. Either way they're chasing the same thing: a pipeline they can keep working on, wherever they are.
### Ina, you insist these courses are not about tools. What are they about?
My class isnt about teaching a single tool. It is the responsive system students interact with across platforms, directing, critiquing, and shaping outputs through ongoing dialogue. ComfyUI fits this: a node graph is an argument you can read, question, and rebuild. A prompt box is not. Singaporean students become technically fluent very fast. What they need from arts education is the language to question what they're making, not just the skill to make it.
</Section>
<Section id="topic-4">
### Ina, the 2026 brief sends students to the ocean. What's the assignment?
The project is The Liquid Commons: Bringing Ocean Science into Global Media Architecture, developed in dialogue with OceanX, the organization behind the OceanXplorer research vessel, and the CDSA 2026 festival theme. The brief is strict: do not illustrate the science, translate it. The 2026 cohort is the first to build these films in ComfyUI with Topaz upscaling, working towards two real deadlines at once. Their pieces are in consideration for the OceanX Summit in Singapore this October, and jury-selected works will screen during the City Digital Skin Art Festival on Hangzhou's West Lake Media Façade: 170 metres by 18 metres, around a million viewers a day.
<Quote>The delivery spec tells you why the tooling matters: final exports at 5,888 × 768 px, 8K where required. That's the brief no prompt box can fill.</Quote>
</Section>
<Section id="topic-5">
### Mark, what does the student work look like?
About eight students have built their films through Comfy so far, and they're all pretty cool. They're surprising and insightful, because they're not limited by game-engine graphics. One student was the standout: he tried every model in Comfy and pushed the furthest.
Three projects from the 2026 cohort show the range.
**The Tao of Water** (Wang Zilin, AP7055) reads the ocean through the Tao Te Ching, a three-part arc from water to marine plant to void and back to origin. The pipeline moves from Pinterest research boards through Midjourney into ComfyUI, where Nano Banana extends single frames into seamless panoramas and Kling 3.0 animates first-frame-to-last-frame motion at full 5,888-pixel width, before a Premiere edit.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig3-tao-of-water.jpg" alt="The Tao of Water on the NTU Index screen" caption="The Tao of Water, Wang Zilin. Experimental animation, NTU Index screen (15 m × 2 m), Singapore. Photo: Quek Jia Liang." />
**microscophony** (Jiin Ko, AP7055) fuses *microscopic* and *micropolyphony*, Ligeti's term for dense webs of voices that blur into a single cloud of sound. The source is based on OceanX microscope footage of deep-sea microbes, translated into the visual logic of graphic notation (Ligeti, Xenakis, Cardew) so the panorama becomes a listening score. Images ran through Midjourney and Nano Banana, video through ComfyUI with Vidu Q2, sound design in Ableton Live, with distinct sonic textures mapped to distinct visual forms.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig4-microscophony.jpg" alt="microscophony on the NTU Index screen" caption="microscophony, Jiin Ko. Experimental animation, NTU Index screen (15 m × 2 m), Singapore. Photo: Quek Jia Liang." />
**GO! PLASTIC** (Jianwei Hoe, DM2012) is an ocean-plastics piece whose production log reads like studio paperwork, not prompt history. It opens with a one-line art direction (every project states its idea in a single line, with embedded irony, before a frame is generated), then walks through model selection, a platform-versus-local cost comparison (cost per clip and per scene on an RTX 5090 against a cloud B200, render times included), and a shot-by-shot sheet pairing every source image with its full prompt and settings.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig5-go-plastic.jpg" alt="GO! PLASTIC on the NTU Index screen" caption="GO! PLASTIC, Hoe Jianwei. Experimental animation, NTU Index screen (15 m × 2 m), Singapore. Photo: Quek Jia Liang." />
</Section>
<Section id="topic-6">
### Ina, where does the work go after the classroom?
Onto public screens, and into juried international competition. The City Digital Skin Art Festival was established in 2023, initiated by the China Academy of Art's School of Sculpture and Public Art and co-curated with Public Art Lab Berlin, MEET Digital Culture Center Milan, and NTU ADM, with a network of more than 29 art academies across China and Europe.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig6-cdsa-awards.jpg" alt="CDSA Festival award winners on the West Lake Media Façade" caption="CDSA Festival award winners, curators, and organizers. West Lake Media Façade (170 m × 18 m), Hangzhou, China. Photo: Limpid Art. Asia's largest high-definition outdoor screen" />
The 2024 edition ran across 11 LED screens in 9 cities in 5 countries and reached over 100 million views. The 20252026 edition, themed Memory Coexistence, drew over 200 international submissions, with the top 40 selected by a 16-member jury. I curate the Singapore programme across NTU Index and the Ten Square landmark façade. A student composing at 6K in our classroom is composing for that circuit.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig7-crispr.jpg" alt="Crispr on the Ten Square Landmark Façade" caption="Crispr, Lee Chaewon. Experimental animation, Ten Square Landmark Façade (21.2 m × 14.4 m), Singapore. Photo: Quek Jia Liang." />
NTU ADM students have already won at this level. At CDSA 2025, the majority of the top awards went to students from these two courses: Gold (Sun Yutong, *Echoes of Her*), Silver (Tan Yu Yan Cheerie, *Eternal Flux*), Bronze (Shah Pranjal Kirti, *Mumbai Miniatures*), Business (Ong Sze Ching, *Nuwa*), and Creative (Leah Chakola, *Caravan of Memory*). The courses have also taken NTU to Ars Electronica in Linz as the only Singapore campus partner since 2023, first with *Butterfly's Dreams* (2023, "Who Owns the Truth?") and then in 2025 with *Beyond the Screen*, a joint exhibition with the China Academy of Art and Bauhaus-Universität Weimar.
### Mark, you spent a decade at DreamWorks. Why does this tool fit art students?
I come from visual effects. I was at DreamWorks about ten years, then Rhythm & Hues, then the game industry and big interactive installations. I'm not a programmer, so I love ComfyUI.
<Quote>Everybody I know who does graphics now is using this, because it's so adaptable. Sometimes we use Comfy as just a back end. That's what everybody's doing.</Quote>
We got this large 15-metre by 2-metre screen in an art installation at the university, and it let us explore media and different techniques. We found students weren't technical enough to handle TouchDesigner, so they just started making movies. Then I started playing with AI, and now everything's AI. What I'd love next is templates custom-made for these screens.
Take *Echoes, Whispers and Memories*, the piece Ina and I made. We don't use Comfy to spit out finished illustrations. We build workflows that keep recomposing the image, breaking it apart and putting it back together so it evolves on screen, which is the whole point: entropy, memory, things falling apart and reforming. Then we push those outputs into real-time and projection systems for big rooms, places like Ars Electronica's Deep Space 8K and MEET in Milan.
<Figure src="https://media.comfy.org/website/customers/ina-conradi/fig8-echoes.jpg" alt="Echoes, Whispers and Memories at Ars Electronica Deep Space 8K" caption="Echoes, Whispers and Memories, Mark Chavez and Ina Conradi. AI-generated immersive installation using ComfyUI, Deep Space 8K, Ars Electronica, Linz, Austria. Photo: Wolfgang Simlinger." />
### The signal from the industry
<Quote>I hear from my students looking for internships or jobs that the first question over there is, "Do you know Comfy?" Because they want to hire kids who know the pipeline.</Quote>
</Section>
<Section id="topic-7" title="At a glance">
<AtAGlance rows={[
{ label: "Institution", value: "Nanyang Technological University, School of Art, Design and Media (Singapore)" },
{ label: "Courses", value: "DM2012: Explorations in AI-Generated Art (UG) and AP7055: Art in the Age of the Creative Machine (PG), written and taught by Ina Conradi since 2022; ~30 students/semester" },
{ label: "The canvas", value: "6K-wide, 8:1 LED walls in Singapore and China; NTU Index wall on campus (15 m × 2 m, 5,888 × 768 px)" },
{ label: "Core technique", value: "ComfyUI compositions with Topaz upscaling for ultra-wide panoramic output; production logs with per-clip cost and prompt sheets" },
{ label: "Why Comfy won", value: "Hosted tools locked to 16:9; upscaling to 8K at a 1-by-8 panorama after composition needed a multi-model pipeline; per-seat monthly renewals didn't fit the semester" }
]} />
</Section>
<AuthorBio label="About the authors" people={[
{ name: "Ina Conradi", photo: "https://media.comfy.org/website/customers/ina-conradi/author-ina.jpg", bio: `Ina Conradi is an artist and curator based between Singapore and Los Angeles. She is founding faculty at NTU's School of Art, Design and Media (est. 2005), where she has written and taught the school's AI courses since 2022. Her film Moirai: Thread of Life won Best in Show at the SIGGRAPH Asia Computer Animation Festival 2023, a first for Singapore.` },
{ name: "Mark Chavez", photo: "https://media.comfy.org/website/customers/ina-conradi/author-mark.jpg", bio: `Mark Chavez is an animator, director, and founding faculty at NTU's School of Art, Design and Media in Singapore. After a decade at DreamWorks Animation and visual effects work at the original Rhythm & Hues Studios, he established NTU's Digital Animation area (2005) and an animation research think-tank funded by Singapore's National Research Foundation and the Media Development Authority.` }
]} />
<EducationCta />

View File

@@ -1,138 +0,0 @@
---
title: "Built for AI: Prof. Kathy Smith on USC's Expanded Animation program and ComfyUI"
category: "CREATIVE CAMPUS SHOWCASE"
description: "Inside the experimental USC MFA that put AI into animation pedagogy from day one, and the student pipelines it produced."
cover: "https://media.comfy.org/website/customers/kathy-smith/cover.png"
order: 8
sections:
- id: topic-1
label: "THE PROGRAM"
- id: topic-2
label: "TEACHING WITH AI"
- id: topic-3
label: "WHY COMFYUI"
- id: topic-4
label: "STUDENT WORK"
- id: topic-5
label: "AT A GLANCE"
- id: topic-6
label: "WHAT'S NEXT"
---
<Section id="topic-1">
### You built the Expanded Animation program in 2022 specifically to put AI into the curriculum from day one. What did you see that other programs missed?
We created Expanded Animation: Research and Practice specifically to focus on creative process and AI as part of how animators learn to make work. The thesis at the start was that AI was going to reshape animation as a medium, and the question was not whether to teach it but how to embed it in the curriculum so students learn it as part of their creative process rather than as a separate technical specialty.
USC's School of Cinematic Arts already had decades of cinematic storytelling tradition. What we did with XA was put AI inside that tradition. The conceptual thinking, the storytelling, the cinematic history come first. AI is one of the many tools available to them, sitting alongside hand-drawing, paint, 3D, and live-action footage. Students do not learn AI in one course and animation in another. They learn both side by side.
The students who arrive at the program are usually self-selected for it. They show up technically fluent, with their own GPU-equipped laptops. What we offer them is the storytelling, the cinematic history, and the conceptual frame. They bring the technical nimbleness.
<Quote>They are way ahead of the curve. They are ahead of the faculty in the way they work, technically, but not so much artistically. That is what we are there to deliver.</Quote>
<Figure src="https://media.comfy.org/website/customers/kathy-smith/usc-campus.png" alt="USC School of Cinematic Arts" caption="USC School of Cinematic Arts. Source: USC Today" />
</Section>
<Section id="topic-2">
### How do you actually structure an AI assignment? Walk us through one.
In my Animation, Dreams, and Consciousness class, I have the students document their dreams and then use the dream as the source. Some of them draw, some of them write. The dream becomes the prompt, and they generate the image and emotion of the dream. I love when you get six fingers and weird stuff happening in the algorithms. Our human perception in dreams is often doing the same thing. Therefore, AI is evolving and dreaming with us.
That structure is deliberate. The students are not asking the model to produce work for them. They are using it as a layer of their process, alongside hand-drawing and painting and 3D rendering and live-action footage. The work that comes out is theirs because the creative decisions are theirs. The tool just gives them new ways to reach what they were trying to make.
There is a fear factor around AI, and I understand it. There has been a lot of scraping of artists' work, and that conversation is real and is going to take time to resolve. But I have been working with AI conceptually since 1998, and the way I describe the data sets to my students is that they are a repository of all of our creation. It is like the collective unconscious of the human mind. Artists have always drawn from everything around them.
<Quote>What really matters is what the artist does with it, *intentionality*.</Quote>
</Section>
<Section id="topic-3">
### Why does ComfyUI specifically fit the way your students work?
It is the node-based system. Those who have done Houdini feel very at home in Comfy. You can work with the prompts, but it is very visual. That is what they are used to. They are not asking a black box for an output. They are building a workflow.
And it stays in its lane. The students are not using Comfy to make AI art. They are using Comfy as one node graph alongside Blender, hand-drawn frames, paint, and live-action footage. The reason it fits is that it does not try to be the whole pipeline. It is one stage of a creative practice that still has cinema at its core.
What also matters is that Comfy is open and inspectable. The students can see what the model is doing at each step, fork a workflow, swap a sampler, drop in a custom node, and share what they built with the next cohort. That is closer to how an animation studio tradition has always behaved, with techniques passed along and improved rather than hidden behind a paywall.
They also work across whatever hardware they have: Comfy Cloud at home and when they are mobile, the portable version on their personal laptops, and the research computer in my office for the high-end runs. Animation students do not sit in one cubicle for a thesis project. They work everywhere.
</Section>
<Section id="topic-4">
### Tell us about the work coming out of the program.
The pattern shows up across the cohort: the AI is in service of the cinematic story, not in place of it. Three students walked us through how Comfy actually sits inside their pipelines.
#### Sijia Zheng — Ori & Kiddo
<Figure src="https://media.comfy.org/website/customers/kathy-smith/ori-kiddo.png" alt="Sijia Zheng, Ori & Kiddo" />
**What Comfy enabled:** an oil-paint, brush-stroke dream look that "other AI tools cannot possibly make," held consistent across shots with IP-Adapter style transfer and a custom LoRA.
*Ori & Kiddo* follows two ghosts who, after the universe dies, search for old human memories, rediscover love, and reverse the universe back into being. Most of the film is hand-drawn 2D. Comfy enters in the dream sequences, where the ghost Kiddo dreams of past lives and the look had to be unlike anything else in the film. Sijia drew stylized reference images first, then used them as the style reference over video clips through an IP-Adapter workflow to produce long, oil-painted, brush-stroke sequences. The same control shows up in shots where Sijia appears on screen: real footage, masked in Comfy to change the haircut and swap the background. For a look that has to stay locked, Sijia trains a LoRA and runs it through Comfy.
Sijia found Comfy in early 2025 while hunting for a style-transfer tool that Midjourney and DALL-E could not deliver, testing it on a stylized animated-film-look conversion.
<Quote>It totally broke my mind. Most of the time, I think I'll just stand on other people's shoulders. The workflows are already pretty amazing, and I'll base on the workflows and add something that I want.</Quote>
Since *Ori & Kiddo*, Sijia has taken the same Comfy-anchored workflow into professional commercial video work, on deadlines as tight as four days.
#### Ion Yunyang Li — L1LY
<Figure src="https://media.comfy.org/website/customers/kathy-smith/l1ly.gif" alt="Ion Yunyang Li, L1LY" />
**What Comfy enabled:** a repeatable multi-step pipeline that drops the filmmaker into a photorealistic world, because "a sequence of a prompt is not the only thing you need."
Ion taught himself ComfyUI in early 2025, from tutorials in the generative-AI community, and built his most distinctive Comfy work in a body-and-environment project: start from 3D-model stills, convert them to a pencil-sketch style so the model would not over-study the original 3D aesthetic, generate photorealistic frames from the sketches, build character T-poses, composite himself into the scene, and animate the stills with a video model.
<Quote>A sequence of a prompt is not the only thing you need. You need many different settings, and it is very hard to redo those settings every time.</Quote>
What he values as much as the pipeline is where it can run: the same Comfy setup moves across a workstation in his school cubicle, a remote session from his apartment laptop, and fully cloud-based instances, depending on where he is.
#### Sihan Wu — Scary Coaster
<Figure src="https://media.comfy.org/website/customers/kathy-smith/scary-coaster.gif" alt="Sihan Wu, Scary Coaster" />
**What Comfy enabled:** roughly 100 hand-drawn keyframes carried through a single workflow so a two-to-three-minute film stays visually consistent, on his first-ever AI project.
*Scary Coaster* (December 2024) was Sihan's first project ever made with AI. Coming from a digital-media and game-development undergrad, Sihan joined Professor Smith's Expanded Animation class and wanted something more controllable than the prompt-only tools on offer. The workflow he built: draw roughly 100 rough keyframes by hand, run them through Comfy to find a stylized Chinese-horror look, pick the favorite, then generate the in-betweens to produce the full sequence.
<Quote>I want to have a more controllable flow. I don't want to just use prompts and generate random images. I just use one workflow to create the whole two or three minutes, and I can make everything look very consistent.</Quote>
Sihan is honest that the on-ramp was steep: learning from the official ComfyUI GitHub workflows, combining them, and debugging Python environments along the way. His ask was specific: an official, beginner-to-advanced tutorial series. And his view on where AI should head next was equally specific: aim it at "the very time-consuming but not that creative process, like creating in-betweens," and leave the creative decisions to the artist.
</Section>
<Section id="topic-5" title="At a glance">
<AtAGlance rows={[
{ label: "Program", value: "Expanded Animation: Research + Practice (XA), USC School of Cinematic Arts" },
{ label: "Founded", value: "2022, AI embedded in the MFA curriculum from day one" },
{ label: "Setup", value: "Students' own GPU laptops + Comfy Cloud + lab research machine" },
{ label: "Core techniques", value: "IP-Adapter style transfer, custom LoRAs, masked compositing, keyframe-to-in-between pipelines" },
{ label: "Outcomes", value: "Amazing student works from Sihan, and Ion, Sijia" }
]} />
</Section>
<Section id="topic-6">
### What excites you about where this is going?
I have a philosophy that everyone is an artist. They just forget that they are an artist. Creativity drives everything, and the tools we are getting now make it possible for more people to find that capacity in themselves. ComfyUI, because it is node-based and visual and open, gives non-programmers a way forward that is honest about how the model works. It does not pretend the AI is doing something magical. It shows the artist what is happening at each step.
The two basic rights of human life are health and education. The work Comfy is doing on the education side is touching something integral. The students who came through XA are already extending the work in directions the program did not anticipate, and the next generation of educators and students will keep doing the same.
<Quote>Everyone is an artist. They just forget that they are an artist.</Quote>
</Section>
<AuthorBio people={[{ name: "Kathy Smith", photo: "https://media.comfy.org/website/customers/kathy-smith/kathy-smith.jpg", bio: `Kathy Smith is Professor of Cinematic Arts at USC's School of Cinematic Arts and inaugural director (2022-2023) of Expanded Animation: Research + Practice (XA), the experimental MFA program she helped found in 2022 to integrate AI into animation pedagogy from the first day of the degree. To date she is the longest-serving chair of combined USC animation programs and has been exploring concepts of AI in her creative practice since 1998.` }]} />
<EducationCta />

View File

@@ -1,56 +0,0 @@
---
title: "Comfy and UAL's Creative Computing Institute Announce Creative Campus Partnership"
category: "CREATIVE CAMPUS PARTNERSHIP"
description: "Comfy announces Creative Campus Partnership to support teaching and research across UAL CCI's masters, PhD, and industry programmes"
cover: "https://media.comfy.org/website/customers/ual-cci/cover.png"
order: 9
sections:
- id: topic-1
label: "INTRO"
- id: topic-2
label: "WHAT CCI DOES"
- id: topic-3
label: "THE PARTNERSHIP"
- id: topic-4
label: "ABOUT CCI"
---
<Section id="topic-1">
Comfy Org, the team behind ComfyUI, the open-source node-based interface for generative AI, and the Creative Computing Institute (CCI) at University of the Arts London today announced a Creative Campus partnership, making CCI a founding partner of the [Comfy Education Initiative](https://comfy.org/education).
</Section>
<Section id="topic-2">
CCI already runs ComfyUI at every level of the institute. On the Applied Machine Learning for Creatives masters course, students build image, video, audio, and text workflows, train their own models, and construct interactive pipelines. PhD researchers use Comfy for fine-tuning, custom datasets, and custom node development. The institute also uses ComfyUI in industry training, where its node-based interface gives non-technical collaborators a way into generative AI that code alone does not.
<Quote name="Prof Mick Grierson, Research Leader, UAL Creative Computing Institute">ComfyUI has become part of how we teach, research, and work with industry. It is one of the few generative AI environments where the workflows our students build are portable, inspectable, and forkable, and that open-source foundation is exactly what a university should be teaching on.</Quote>
</Section>
<Section id="topic-3">
Through the partnership, CCI educators and students gain access to classroom licenses with central billing & administration, educational discounts, early access to upcoming team features, a dedicated educator community with direct support from the Comfy team, and a voice in shaping the future of the education program.
Creative Campus partnerships are the deepest tier of the program: a direct, ongoing collaboration in which an institution works hand in hand with the Comfy team to roll out ComfyUI across teaching, research, and industry training.
<Quote name="The Comfy Team">CCI is the model we hope every creative campus follows: ComfyUI in the masters classroom, in PhD research, and in industry collaboration, all at once. As our first Creative Campus Partner, they are helping us design an education program that works the way universities actually work.</Quote>
<Figure src="https://media.comfy.org/website/customers/ual-cci/cci-camberwell.jpg" alt="Creative Computing Institute campus at UAL" caption="Creative Computing Institute Campus. Photo: Ana Escobar, courtesy UAL." />
The institute is leading a major £1.5 million publicly funded research programme developing copyright-compliant audiovisual foundation models for the UK's creative industries. Bringing together expertise in sound, image, and artificial intelligence, the project is building open tools and responsible AI national infrastructure designed to support UK creative production, research, and experimentation across the sector.
The outputs of the research will explore wider dissemination and adoption through open, node-based tools such as ComfyUI to support experimentation, workflows, and collaboration around emerging multimodal AI systems.
UAL CCI joins a founding cohort of educators and institutions featured at the launch of the Comfy Education Initiative, alongside researchers such as CCI co-founder Dr. Phoenix Perry, whose Antigravity Machine project Comfy supports as an industry partner.
</Section>
<Section id="topic-4" title="About the Creative Computing Institute at UAL">
The Creative Computing Institute at University of the Arts London applies computing to creativity and social impact, operating at the intersection of computational technologies and creative practice, teaching undergraduate, postgraduate, and PhD students alongside research and industry collaboration.
</Section>
<EducationCta />

View File

@@ -1,103 +0,0 @@
---
title: "The tool that expands my art: Xindi Zhang's Oscar-shortlisted thesis, built in ComfyUI"
category: "CREATIVE CAMPUS SHOWCASE"
description: "How a USC Expanded Animation thesis became a Student Academy Award winner, an Oscar shortlist entry, and helped land a job at Amazon — with the artist's own illustrations as the style guide."
cover: "https://media.comfy.org/website/customers/xindi-zhang/cover.webp"
order: 5
sections:
- id: topic-1
label: "INTRO"
- id: topic-2
label: "WHY COMFYUI"
- id: topic-3
label: "THE PIPELINE"
- id: topic-4
label: "AT A GLANCE"
- id: topic-5
label: "WHAT'S NEXT"
---
<Section id="topic-1">
<Embed src="https://player.vimeo.com/video/1131160045" title="The Song of Drifters by Xindi Zhang" />
*From The Song of Drifters. Film images: Xindi Zhang.*
### Tell us about The Song of Drifters. What is it about, and where did it start?
The Song of Drifters is a documentary animation about people caught between leaving and returning, wanderers who drift through unfamiliar cities, holding onto memories of a homeland out of reach and searching for a sense of belonging. The title is a direct translation from an ancient Chinese poem about a mother's love for a child who leaves her hometown. My version takes the opposite point of view, from the child's perspective.
I built the film in ComfyUI. When I started, I was not trying to show what AI could do. I was trying to prove something almost opposite.
<Quote>It started as a challenge to the stereotype that AI-generated work is generic and cheap. I wanted to prove that AI could be an amplifier for personal vision, not a replacement for it.</Quote>
</Section>
<Section id="topic-2">
### You came to this from illustration, not engineering. How did you end up in ComfyUI?
I started as an illustrator. I earned my BFA in illustration at the Rhode Island School of Design, then worked as a game concept artist, where I picked up shaders, Unity, and Unreal. That technical side made me a fast learner with new tools. Later I went to USC's School of Cinematic Arts for an MFA in Expanded Animation, where I studied with Professor Kathy Smith.
By my thesis year I had moved from Stable Diffusion's standard interfaces to ComfyUI, because I think in node-based structures and I wanted to control every step. Most AI tools are one click: you prompt, you click, you get a result. That is not what I wanted.
<Quote>I want to control the process, and the process is even more important than the result itself. For artists like me, I don't want to automate anything. I want to participate in every single stage of designing the workflow. That's the fun part of it.</Quote>
</Section>
<Section id="topic-3">
### Walk us through the pipeline. What were you actually feeding the model?
<Figure src="https://media.comfy.org/website/customers/xindi-zhang/balloon-workflow.png" alt="Xindi's ComfyUI workflow for the balloon sequence">Xindi's ComfyUI workflow for the balloon sequence. Source: [xindizhangart.com](https://xindizhangart.com).</Figure>
My core technique was style transfer in Stable Diffusion 1.5, driven by IP-Adapter and ControlNet. What mattered most was what I fed it: my own work. The base materials were live-action footage I shot on an iPhone 15 Pro and 3D animation I built in Blender. The AI restyled imagery I had already made. It did not invent it.
<Figure src="https://media.comfy.org/website/customers/xindi-zhang/film-still.jpg" alt="Style-guide still from The Song of Drifters">Style-guide still from The Song of Drifters. Source: [xindizhangart.com](https://xindizhangart.com).</Figure>
<Quote>Unlike most AI-generated videos, which use other artists' works from the model, I use my own illustrations as the style guide.</Quote>
<Download href="https://media.comfy.org/website/customers/xindi-zhang/workflows/style-transfer-workflow.json" label="Download Xindi's style transfer workflow (json) on ComfyUI" />
I also trained custom LoRAs on my own video, footage of the cities I had lived in. Capturing that footage became a vital part of the documentary process. Wandering through the streets where I once lived let me reconnect with those cities. Most of it never appears in the final cut, but it lives in the visuals as training data. The hybrid pipeline made rendering the final look more efficient and saved more time for ideation.
For the dream sequences I combined animated 3D with AI morphing, moving from abstract to concrete to mimic the feeling of being half awake.
<Video src="https://media.comfy.org/website/customers/xindi-zhang/bts-clip.mp4" poster="https://media.comfy.org/website/customers/xindi-zhang/bts-poster.jpg" caption="BTS clip, AI morphing. Source: Xindi Zhang." />
<Download href="https://media.comfy.org/website/customers/xindi-zhang/workflows/morphing-workflow.json" label="Download Xindi's AI morphing workflow (json) on ComfyUI" />
</Section>
<Section id="topic-4" title="At a glance">
<AtAGlance rows={[
{ label: "Program", value: "USC School of Cinematic Arts — MFA Expanded Animation (thesis)" },
{ label: "Base materials", value: "iPhone 15 Pro live-action; her own Blender 3D animation" },
{ label: "Core technique", value: "Style transfer in SD 1.5 via IP-Adapter + ControlNet, in ComfyUI" },
{ label: "Style source", value: "Her own illustrations + custom LoRAs trained on her own city footage" },
{ label: "Finishing", value: "Depth, mask, and fade passes in After Effects; heavy compositing" },
{ label: "Outcome", value: "Student Academy Awards Golden Award (2025); 98th Academy Awards shortlist; AI Creative role at Amazon AI Studio" }
]} />
</Section>
<Section id="topic-5">
### The film won gold at the Student Academy Awards and was shortlisted for the Oscars. What's next?
I made the film for creative reasons, not career ones. I honestly did not expect it to connect to a job at all. Then it won the Golden Award at the 2025 Student Academy Awards and was shortlisted for the Oscars, and the calls started.
<Figure src="https://media.comfy.org/website/customers/xindi-zhang/awards.png" alt="Xindi Zhang at the 2025 Student Academy Awards" caption="Xindi Zhang at the 2025 Student Academy Awards. Source: Oscars Press Office." />
What people wanted was the combination: someone who understands both traditional craft and AI tools. I now work as an AI Creative at Amazon AI Studio building custom production pipelines. I see that same demand across the industry, with ComfyUI experience starting to show up as a requirement in job postings at major studios and design agencies.
<Quote>It's not the tool that steals my art. It's the tool that expands my art.</Quote>
My advice to other students is not really about software. AI is just another tool to convey ideas, but nothing is more important than the story itself. If you use AI, use it on purpose. The more you understand it, the more freedom you have to make work that is genuinely yours.
</Section>
<AuthorBio people={[{ name: "Xindi Zhang", photo: "https://media.comfy.org/website/customers/xindi-zhang/profile.jpg", bio: `Xindi Zhang is a Chinese animation director and visual artist (RISD BFA in illustration, 2020; USC MFA in Expanded Animation, 2025). The Song of Drifters won the Golden Award at the 2025 Student Academy Awards and was shortlisted for the 98th Academy Awards. She works as an AI Creative at Amazon AI Studio, has collaborated with Sony Music's immersive studio, and is now on the faculty at the University of South Florida.` }]} />
<EducationCta />

View File

@@ -61,11 +61,6 @@
@theme {
--color-site-dropdown: #332b38;
--color-site-bg-soft: color-mix(
in srgb,
var(--color-primary-comfy-ink) 88%,
black 12%
);
--color-primary-comfy-yellow: #f2ff59;
--color-primary-comfy-ink: #211927;
--color-primary-comfy-ink-light: #2a2330;
@@ -266,6 +261,6 @@ video::-webkit-media-controls-panel {
:root {
--site-bg: var(--color-primary-comfy-ink);
--site-bg-soft: var(--color-site-bg-soft);
--site-bg-soft: color-mix(in srgb, var(--site-bg) 88%, black 12%);
--site-border-subtle: rgb(255 255 255 / 0.1);
}

View File

@@ -28,12 +28,7 @@ const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188'
// matches it against the members self-row.
const SELF_EMAIL = 'e2e@test.comfy.org'
// consolidated_billing_enabled routes personal workspaces to the unified
// pricing table asserted here; without it they fall back to the legacy table.
const BOOT_FEATURES = {
team_workspaces_enabled: true,
consolidated_billing_enabled: true
} satisfies RemoteConfig
const BOOT_FEATURES = { team_workspaces_enabled: true } satisfies RemoteConfig
// Disable the experimental Asset API: with it on (cloud default) the unmocked
// asset endpoints 403 and workflow restore throws uncaught, aborting the
// GraphCanvas onMounted chain before the deep-link loader.

View File

@@ -158,8 +158,8 @@ import { creditsToUsd, usdToCredits } from '@/base/credits/comfyCredits'
import Button from '@/components/ui/button/Button.vue'
import FormattedNumberStepper from '@/components/ui/stepper/FormattedNumberStepper.vue'
import { useAuthActions } from '@/composables/auth/useAuthActions'
import { useBillingRouting } from '@/composables/billing/useBillingRouting'
import { useExternalLink } from '@/composables/useExternalLink'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription'
import { useTelemetry } from '@/platform/telemetry'
import { clearTopupTracking } from '@/platform/telemetry/topupTracker'
@@ -178,7 +178,7 @@ const settingsDialog = useSettingsDialog()
const telemetry = useTelemetry()
const toast = useToast()
const { buildDocsUrl, docsPaths } = useExternalLink()
const { shouldUseWorkspaceBilling } = useBillingRouting()
const { flags } = useFeatureFlags()
const { isSubscriptionEnabled } = useSubscription()
// Constants
@@ -260,9 +260,9 @@ async function handleBuy() {
// Close top-up dialog (keep tracking) and open credits panel to show updated balance
handleClose(false)
// On the consolidated (workspace) billing flow, show the workspace settings
// panel; otherwise show the legacy subscription/credits panel.
const settingsPanel = shouldUseWorkspaceBilling.value
// In workspace mode (personal workspace), show workspace settings panel
// Otherwise, show legacy subscription/credits panel
const settingsPanel = flags.teamWorkspacesEnabled
? 'workspace'
: isSubscriptionEnabled()
? 'subscription'

View File

@@ -2,11 +2,12 @@ import { createTestingPinia } from '@pinia/testing'
import PrimeVue from 'primevue/config'
import Tooltip from 'primevue/tooltip'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { defineComponent, onMounted, ref } from 'vue'
import { createI18n } from 'vue-i18n'
import { render, screen, waitFor } from '@testing-library/vue'
import type * as DistributionTypes from '@/platform/distribution/types'
import type { AuditLog } from '@/services/customerEventsService'
import { EventType } from '@/services/customerEventsService'
@@ -34,29 +35,19 @@ vi.mock('@/services/customerEventsService', () => ({
}
}))
const mockTelemetry = vi.hoisted(() => ({
checkForCompletedTopup: vi.fn()
}))
vi.mock('@/platform/telemetry', () => ({
useTelemetry: () => mockTelemetry
useTelemetry: () => null
}))
const mockBillingRouting = vi.hoisted(() => ({
shouldUseWorkspaceBilling: false
const mockFlags = vi.hoisted(() => ({ teamWorkspacesEnabled: false }))
vi.mock('@/composables/useFeatureFlags', () => ({
useFeatureFlags: () => ({ flags: mockFlags })
}))
vi.mock('@/platform/distribution/types', async (importOriginal) => ({
...(await importOriginal<typeof DistributionTypes>()),
isCloud: true
}))
vi.mock('@/composables/billing/useBillingRouting', async () => {
const { ref } = await import('vue')
const shouldUseWorkspaceBilling = ref(false)
Object.defineProperty(mockBillingRouting, 'shouldUseWorkspaceBilling', {
get: () => shouldUseWorkspaceBilling.value,
set: (value: boolean) => {
shouldUseWorkspaceBilling.value = value
}
})
return {
useBillingRouting: () => ({ shouldUseWorkspaceBilling })
}
})
const mockWorkspaceApi = vi.hoisted(() => ({
getBillingEvents: vi.fn()
@@ -77,10 +68,7 @@ const i18n = createI18n({
additionalInfo: 'Additional Info',
added: 'Added',
accountInitialized: 'Account initialized',
model: 'Model',
loadEventsError: 'Failed to load activity. Please try again.',
loadEventsUnknownError:
'Something went wrong while loading activity. Please refresh and try again.'
model: 'Model'
}
}
}
@@ -107,11 +95,6 @@ const AutoRefreshWrapper = defineComponent({
template: '<UsageLogsTable ref="tableRef" />'
})
async function flushMicrotasks() {
await new Promise((resolve) => setTimeout(resolve, 0))
await nextTick()
}
function makeEventsResponse(
events: Partial<AuditLog>[],
overrides: Record<string, unknown> = {}
@@ -154,7 +137,7 @@ describe('UsageLogsTable', () => {
mockCustomerEventsService.getMyEvents.mockResolvedValue(mockEventsResponse)
mockWorkspaceApi.getBillingEvents.mockResolvedValue(mockEventsResponse)
mockBillingRouting.shouldUseWorkspaceBilling = false
mockFlags.teamWorkspacesEnabled = false
mockCustomerEventsService.formatEventType.mockImplementation(
(type: string) => {
switch (type) {
@@ -245,7 +228,7 @@ describe('UsageLogsTable', () => {
})
})
it('shows a localized fallback instead of a raw Error message', async () => {
it('shows error message when service throws', async () => {
mockCustomerEventsService.getMyEvents.mockRejectedValue(
new Error('Network error')
)
@@ -253,25 +236,7 @@ describe('UsageLogsTable', () => {
renderWithAutoRefresh()
await waitFor(() => {
expect(
screen.getByText(
'Something went wrong while loading activity. Please refresh and try again.'
)
).toBeInTheDocument()
})
expect(screen.queryByText('Network error')).not.toBeInTheDocument()
})
it('shows a localized fallback when the service reports no message', async () => {
mockCustomerEventsService.getMyEvents.mockResolvedValue(null)
mockCustomerEventsService.error.value = null
renderWithAutoRefresh()
await waitFor(() => {
expect(
screen.getByText('Failed to load activity. Please try again.')
).toBeInTheDocument()
expect(screen.getByText('Network error')).toBeInTheDocument()
})
})
@@ -376,8 +341,8 @@ describe('UsageLogsTable', () => {
})
describe('billing events source', () => {
it('uses workspaceApi.getBillingEvents on the workspace billing flow', async () => {
mockBillingRouting.shouldUseWorkspaceBilling = true
it('uses workspaceApi.getBillingEvents when teamWorkspacesEnabled is on', async () => {
mockFlags.teamWorkspacesEnabled = true
await renderLoaded()
@@ -387,90 +352,6 @@ describe('UsageLogsTable', () => {
})
expect(mockCustomerEventsService.getMyEvents).not.toHaveBeenCalled()
})
it('discards a stale legacy response when routing flips mid-fetch', async () => {
let resolveLegacy!: (value: ReturnType<typeof makeEventsResponse>) => void
mockCustomerEventsService.getMyEvents.mockReturnValue(
new Promise((resolve) => {
resolveLegacy = resolve
})
)
mockWorkspaceApi.getBillingEvents.mockResolvedValue(
makeEventsResponse([
{
event_id: 'workspace-1',
event_type: EventType.API_USAGE_COMPLETED,
params: { api_name: 'WorkspaceAPI', model: 'workspace-model' },
createdAt: '2024-02-01T10:00:00Z'
}
])
)
renderWithAutoRefresh()
mockBillingRouting.shouldUseWorkspaceBilling = true
await waitFor(() => {
expect(screen.getByText('WorkspaceAPI')).toBeInTheDocument()
})
resolveLegacy(
makeEventsResponse([
{
event_id: 'legacy-1',
event_type: EventType.API_USAGE_COMPLETED,
params: { api_name: 'LegacyAPI', model: 'legacy-model' },
createdAt: '2024-01-01T10:00:00Z'
}
])
)
await flushMicrotasks()
expect(screen.getByText('WorkspaceAPI')).toBeInTheDocument()
expect(screen.queryByText('LegacyAPI')).not.toBeInTheDocument()
})
it('runs top-up completion telemetry for a superseded response', async () => {
let resolveLegacy!: (value: ReturnType<typeof makeEventsResponse>) => void
mockCustomerEventsService.getMyEvents.mockReturnValue(
new Promise((resolve) => {
resolveLegacy = resolve
})
)
mockWorkspaceApi.getBillingEvents.mockResolvedValue(
makeEventsResponse([
{
event_id: 'workspace-1',
event_type: EventType.API_USAGE_COMPLETED,
params: { api_name: 'WorkspaceAPI', model: 'workspace-model' },
createdAt: '2024-02-01T10:00:00Z'
}
])
)
renderWithAutoRefresh()
mockBillingRouting.shouldUseWorkspaceBilling = true
await waitFor(() => {
expect(screen.getByText('WorkspaceAPI')).toBeInTheDocument()
})
const legacyResponse = makeEventsResponse([
{
event_id: 'legacy-1',
event_type: EventType.CREDIT_ADDED,
params: { amount: 1000 },
createdAt: '2024-01-01T10:00:00Z'
}
])
resolveLegacy(legacyResponse)
await waitFor(() => {
expect(mockTelemetry.checkForCompletedTopup).toHaveBeenCalledWith(
legacyResponse.events
)
})
})
})
describe('EventType integration', () => {

View File

@@ -96,11 +96,11 @@ import Column from 'primevue/column'
import DataTable from 'primevue/datatable'
import Message from 'primevue/message'
import ProgressSpinner from 'primevue/progressspinner'
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { computed, ref } from 'vue'
import Button from '@/components/ui/button/Button.vue'
import { useBillingRouting } from '@/composables/billing/useBillingRouting'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { isCloud } from '@/platform/distribution/types'
import { useTelemetry } from '@/platform/telemetry'
import { workspaceApi } from '@/platform/workspace/api/workspaceApi'
import type { AuditLog } from '@/services/customerEventsService'
@@ -109,15 +109,14 @@ import {
useCustomerEventsService
} from '@/services/customerEventsService'
const { t } = useI18n()
const events = ref<AuditLog[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const customerEventService = useCustomerEventsService()
const { shouldUseWorkspaceBilling } = useBillingRouting()
const { flags } = useFeatureFlags()
const useBillingApi = computed(() => isCloud && flags.teamWorkspacesEnabled)
const pagination = ref({
page: 1,
@@ -140,12 +139,7 @@ const tooltipContentMap = computed(() => {
return map
})
// A billing-route flip can overlap two loads against different backends; only
// the latest may mutate state, so a superseded response is discarded.
let latestLoadToken = 0
const loadEvents = async () => {
const loadToken = ++latestLoadToken
loading.value = true
error.value = null
@@ -154,17 +148,10 @@ const loadEvents = async () => {
page: pagination.value.page,
limit: pagination.value.limit
}
const response = shouldUseWorkspaceBilling.value
const response = useBillingApi.value
? await workspaceApi.getBillingEvents(params)
: await customerEventService.getMyEvents(params)
// Completion telemetry must run even when a mid-checkout route flip
// supersedes this load, since legacy and workspace backends emit different
// top-up events and the winning fetch may not carry the completion yet.
useTelemetry()?.checkForCompletedTopup(response?.events)
if (loadToken !== latestLoadToken) return
if (response) {
if (response.events) {
events.value = response.events
@@ -178,25 +165,24 @@ const loadEvents = async () => {
pagination.value.limit = response.limit
}
if (response.total != null) {
if (response.total) {
pagination.value.total = response.total
}
if (response.totalPages != null) {
if (response.totalPages) {
pagination.value.totalPages = response.totalPages
}
// Check if a pending top-up has completed
useTelemetry()?.checkForCompletedTopup(response.events)
} else {
const legacyError = shouldUseWorkspaceBilling.value
? null
: customerEventService.error.value
error.value = legacyError || t('credits.loadEventsError')
error.value = customerEventService.error.value || 'Failed to load events'
}
} catch (err) {
if (loadToken !== latestLoadToken) return
error.value = t('credits.loadEventsUnknownError')
error.value = err instanceof Error ? err.message : 'Unknown error'
console.error('Error loading events:', err)
} finally {
if (loadToken === latestLoadToken) loading.value = false
loading.value = false
}
}
@@ -212,12 +198,6 @@ const refresh = async () => {
await loadEvents()
}
watch(shouldUseWorkspaceBilling, () => {
refresh().catch((error) => {
console.error('Error loading events:', error)
})
})
defineExpose({
refresh
})

View File

@@ -8,7 +8,16 @@ import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workfl
type ModifiedWorkflow = Pick<ComfyWorkflow, 'path' | 'isModified'>
const mockAuthStore = vi.hoisted(() => ({
logout: vi.fn().mockResolvedValue(undefined)
logout: vi.fn().mockResolvedValue(undefined),
sendPasswordReset: vi.fn().mockResolvedValue(undefined),
initiateCreditPurchase: vi.fn(),
accessBillingPortal: vi.fn(),
fetchBalance: vi.fn(),
loginWithGoogle: vi.fn(),
loginWithGithub: vi.fn(),
login: vi.fn(),
register: vi.fn(),
updatePassword: vi.fn().mockResolvedValue(undefined)
}))
const mockToastStore = vi.hoisted(() => ({
@@ -29,6 +38,16 @@ const mockDialogService = vi.hoisted(() => ({
const mockToastErrorHandler = vi.hoisted(() => vi.fn())
const mockBillingContext = vi.hoisted(() => ({
isActiveSubscription: { value: false },
isFreeTier: { value: true },
type: { value: 'free' }
}))
const mockTelemetry = vi.hoisted(() => ({
startTopupTracking: vi.fn()
}))
const knownAuthErrorCodes = new Set([
'auth/invalid-credential',
'auth/email-already-in-use'
@@ -48,7 +67,7 @@ vi.mock('@/platform/distribution/types', () => ({
}))
vi.mock('@/platform/telemetry', () => ({
useTelemetry: vi.fn(() => undefined)
useTelemetry: vi.fn(() => mockTelemetry)
}))
vi.mock('@/platform/updates/common/toastStore', () => ({
@@ -72,11 +91,7 @@ vi.mock('@/stores/authStore', () => ({
}))
vi.mock('@/composables/billing/useBillingContext', () => ({
useBillingContext: vi.fn(() => ({
isActiveSubscription: { value: false },
isFreeTier: { value: true },
type: { value: 'free' }
}))
useBillingContext: vi.fn(() => mockBillingContext)
}))
vi.mock('@/composables/useErrorHandling', () => ({
@@ -97,6 +112,7 @@ describe('useAuthActions.logout', () => {
setActivePinia(createPinia())
vi.clearAllMocks()
mockWorkflowStore.modifiedWorkflows = []
mockBillingContext.isActiveSubscription.value = false
})
it('logs out without prompting when no workflows are modified', async () => {
@@ -281,4 +297,158 @@ describe('useAuthActions.reportError', () => {
expect(mockToastErrorHandler).toHaveBeenCalledWith(networkError)
expect(mockToastStore.add).not.toHaveBeenCalled()
})
it('shows the unauthorized-domain access error message', () => {
const { reportError, accessError } = useAuthActions()
reportError(new FirebaseError('auth/unauthorized-domain', 'blocked'))
expect(accessError.value).toBe(true)
expect(mockToastStore.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'g.error',
detail: 'toastMessages.unauthorizedDomain'
})
})
})
describe('useAuthActions account actions', () => {
beforeEach(() => {
setActivePinia(createPinia())
vi.clearAllMocks()
mockBillingContext.isActiveSubscription.value = false
vi.stubGlobal(
'open',
vi.fn(() => ({}))
)
})
it('sends password reset emails and shows success toast', async () => {
const { sendPasswordReset } = useAuthActions()
await sendPasswordReset('user@example.com')
expect(mockAuthStore.sendPasswordReset).toHaveBeenCalledWith(
'user@example.com'
)
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({
severity: 'success',
summary: 'auth.login.passwordResetSent'
})
)
})
it('does not purchase credits without an active subscription', async () => {
const { purchaseCredits } = useAuthActions()
await purchaseCredits(25)
expect(mockAuthStore.initiateCreditPurchase).not.toHaveBeenCalled()
expect(window.open).not.toHaveBeenCalled()
})
it('opens checkout and tracks top-up starts for credit purchases', async () => {
mockBillingContext.isActiveSubscription.value = true
mockAuthStore.initiateCreditPurchase.mockResolvedValueOnce({
checkout_url: 'https://checkout.example.test'
})
const { purchaseCredits } = useAuthActions()
await purchaseCredits(25)
expect(mockAuthStore.initiateCreditPurchase).toHaveBeenCalledWith({
amount_micros: 25000000,
currency: 'usd'
})
expect(mockTelemetry.startTopupTracking).toHaveBeenCalledOnce()
expect(window.open).toHaveBeenCalledWith(
'https://checkout.example.test',
'_blank'
)
})
it('throws when credit checkout URL is missing', async () => {
mockBillingContext.isActiveSubscription.value = true
mockAuthStore.initiateCreditPurchase.mockResolvedValueOnce({})
const { purchaseCredits } = useAuthActions()
await expect(purchaseCredits(10)).rejects.toThrow(
'toastMessages.failedToPurchaseCredits'
)
})
it('opens the billing portal in a new tab by default', async () => {
mockAuthStore.accessBillingPortal.mockResolvedValueOnce({
billing_portal_url: 'https://billing.example.test'
})
const { accessBillingPortal } = useAuthActions()
await expect(accessBillingPortal('pro')).resolves.toBe(true)
expect(mockAuthStore.accessBillingPortal).toHaveBeenCalledWith('pro')
expect(window.open).toHaveBeenCalledWith(
'https://billing.example.test',
'_blank'
)
})
it('throws when billing portal URL is missing', async () => {
mockAuthStore.accessBillingPortal.mockResolvedValueOnce({})
const { accessBillingPortal } = useAuthActions()
await expect(accessBillingPortal()).rejects.toThrow(
'toastMessages.failedToAccessBillingPortal'
)
})
it('delegates balance and sign-in methods to the auth store', async () => {
mockAuthStore.fetchBalance.mockResolvedValueOnce({ balance: 12 })
mockAuthStore.loginWithGoogle.mockResolvedValueOnce('google')
mockAuthStore.loginWithGithub.mockResolvedValueOnce('github')
mockAuthStore.login.mockResolvedValueOnce('email')
mockAuthStore.register.mockResolvedValueOnce('registered')
const actions = useAuthActions()
await expect(actions.fetchBalance()).resolves.toEqual({ balance: 12 })
await expect(actions.signInWithGoogle({ isNewUser: true })).resolves.toBe(
'google'
)
await expect(actions.signInWithGithub({ isNewUser: false })).resolves.toBe(
'github'
)
await expect(actions.signInWithEmail('u@example.com', 'pw')).resolves.toBe(
'email'
)
await expect(
actions.signUpWithEmail('u@example.com', 'pw', 'turnstile')
).resolves.toBe('registered')
expect(mockAuthStore.loginWithGoogle).toHaveBeenCalledWith({
isNewUser: true
})
expect(mockAuthStore.loginWithGithub).toHaveBeenCalledWith({
isNewUser: false
})
expect(mockAuthStore.login).toHaveBeenCalledWith('u@example.com', 'pw')
expect(mockAuthStore.register).toHaveBeenCalledWith(
'u@example.com',
'pw',
'turnstile'
)
})
it('updates passwords and shows success toast', async () => {
const { updatePassword } = useAuthActions()
await updatePassword('new-password')
expect(mockAuthStore.updatePassword).toHaveBeenCalledWith('new-password')
expect(mockToastStore.add).toHaveBeenCalledWith(
expect.objectContaining({
severity: 'success',
summary: 'auth.passwordUpdate.success'
})
)
})
})

View File

@@ -0,0 +1,191 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick, reactive } from 'vue'
import type { User as FirebaseUser } from 'firebase/auth'
import type { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
type FirebaseUserMock = Pick<
FirebaseUser,
'uid' | 'displayName' | 'email' | 'photoURL'
> & {
providerData: Array<Pick<FirebaseUser['providerData'][number], 'providerId'>>
}
type ApiKeyUser = NonNullable<
ReturnType<typeof useApiKeyAuthStore>['currentUser']
>
const mockStores = vi.hoisted(() => ({
authStore: undefined as
| undefined
| {
currentUser: FirebaseUserMock | null
loading: boolean
tokenRefreshTrigger: number
},
apiKeyStore: undefined as
| undefined
| {
isAuthenticated: boolean
currentUser: ApiKeyUser | null
clearStoredApiKey: ReturnType<typeof vi.fn>
},
commandStore: undefined as
| undefined
| {
execute: ReturnType<typeof vi.fn>
}
}))
vi.mock('@/stores/authStore', () => ({
useAuthStore: () => mockStores.authStore
}))
vi.mock('@/stores/apiKeyAuthStore', () => ({
useApiKeyAuthStore: () => mockStores.apiKeyStore
}))
vi.mock('@/stores/commandStore', () => ({
useCommandStore: () => mockStores.commandStore
}))
async function setup() {
vi.resetModules()
const authStore = reactive({
currentUser: null as FirebaseUserMock | null,
loading: false,
tokenRefreshTrigger: 0
})
const apiKeyStore = reactive({
isAuthenticated: false,
currentUser: null as ApiKeyUser | null,
clearStoredApiKey: vi.fn()
})
const commandStore = {
execute: vi.fn()
}
mockStores.authStore = authStore
mockStores.apiKeyStore = apiKeyStore
mockStores.commandStore = commandStore
const { useCurrentUser } = await import('./useCurrentUser')
return {
currentUser: useCurrentUser(),
authStore,
apiKeyStore,
commandStore
}
}
function firebaseUser(
providerId: string,
overrides: Partial<FirebaseUserMock> = {}
): FirebaseUserMock {
return {
uid: 'firebase-user',
displayName: 'Firebase User',
email: 'firebase@example.com',
photoURL: 'https://example.com/photo.png',
providerData: [{ providerId }],
...overrides
}
}
describe('useCurrentUser', () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it('uses API key user identity before firebase identity', async () => {
const { currentUser, authStore, apiKeyStore } = await setup()
expect(currentUser.isLoggedIn.value).toBe(false)
authStore.currentUser = firebaseUser('google.com')
apiKeyStore.isAuthenticated = true
apiKeyStore.currentUser = {
id: 'api-user',
name: 'API User',
email: 'api@example.com'
}
expect(currentUser.isLoggedIn.value).toBe(true)
expect(currentUser.isApiKeyLogin.value).toBe(true)
expect(currentUser.resolvedUserInfo.value).toEqual({ id: 'api-user' })
expect(currentUser.userDisplayName.value).toBe('API User')
expect(currentUser.userEmail.value).toBe('api@example.com')
expect(currentUser.userPhotoUrl.value).toBeNull()
expect(currentUser.providerName.value).toBe('Comfy API Key')
expect(currentUser.providerIcon.value).toBe('pi pi-key')
expect(currentUser.isEmailProvider.value).toBe(false)
})
it('maps firebase provider metadata to display fields', async () => {
const { currentUser, authStore } = await setup()
authStore.currentUser = firebaseUser('google.com')
expect(currentUser.providerName.value).toBe('Google')
expect(currentUser.providerIcon.value).toBe('pi pi-google')
expect(currentUser.userDisplayName.value).toBe('Firebase User')
expect(currentUser.userEmail.value).toBe('firebase@example.com')
expect(currentUser.userPhotoUrl.value).toBe('https://example.com/photo.png')
expect(currentUser.resolvedUserInfo.value).toEqual({ id: 'firebase-user' })
authStore.currentUser = firebaseUser('github.com')
expect(currentUser.providerName.value).toBe('GitHub')
expect(currentUser.providerIcon.value).toBe('pi pi-github')
authStore.currentUser = firebaseUser('password')
expect(currentUser.providerName.value).toBe('password')
expect(currentUser.providerIcon.value).toBe('pi pi-user')
expect(currentUser.isEmailProvider.value).toBe(true)
})
it('routes sign out through the active auth source', async () => {
const { currentUser, apiKeyStore, commandStore } = await setup()
apiKeyStore.isAuthenticated = true
apiKeyStore.currentUser = { id: 'api-user' }
await currentUser.handleSignOut()
expect(apiKeyStore.clearStoredApiKey).toHaveBeenCalledOnce()
apiKeyStore.isAuthenticated = false
await currentUser.handleSignOut()
expect(commandStore.execute).toHaveBeenCalledWith('Comfy.User.SignOut')
})
it('runs user lifecycle callbacks for resolve, token refresh, and logout', async () => {
const { currentUser, authStore } = await setup()
const resolved = vi.fn()
const tokenRefreshed = vi.fn()
const logout = vi.fn()
currentUser.onUserResolved(resolved)
currentUser.onTokenRefreshed(tokenRefreshed)
currentUser.onUserLogout(logout)
authStore.currentUser = firebaseUser('google.com')
await nextTick()
expect(resolved.mock.calls[0][0]).toEqual({ id: 'firebase-user' })
authStore.tokenRefreshTrigger += 1
await nextTick()
expect(tokenRefreshed).toHaveBeenCalledOnce()
authStore.currentUser = null
await nextTick()
expect(logout).toHaveBeenCalledOnce()
})
it('runs onUserResolved immediately when a user already exists', async () => {
const { currentUser, apiKeyStore } = await setup()
apiKeyStore.isAuthenticated = true
apiKeyStore.currentUser = { id: 'api-user' }
const resolved = vi.fn()
currentUser.onUserResolved(resolved)
expect(resolved.mock.calls[0][0]).toEqual({ id: 'api-user' })
})
})

View File

@@ -19,7 +19,6 @@ const DEFAULT_BILLING_STATUS: BillingStatusResponse = {
const {
mockTeamWorkspacesEnabled,
mockConsolidatedBillingEnabled,
mockIsPersonal,
mockPlans,
mockPurchaseCredits,
@@ -27,7 +26,6 @@ const {
mockBillingStatus
} = vi.hoisted(() => ({
mockTeamWorkspacesEnabled: { value: false },
mockConsolidatedBillingEnabled: { value: false },
mockIsPersonal: { value: true },
mockPlans: { value: [] as Plan[] },
mockPurchaseCredits: vi.fn(),
@@ -59,23 +57,11 @@ vi.mock('@/composables/useFeatureFlags', async () => {
teamWorkspacesEnabledRef.value = value
}
})
const consolidatedBillingEnabledRef = ref(
mockConsolidatedBillingEnabled.value
)
Object.defineProperty(mockConsolidatedBillingEnabled, 'value', {
get: () => consolidatedBillingEnabledRef.value,
set: (value: boolean) => {
consolidatedBillingEnabledRef.value = value
}
})
return {
useFeatureFlags: () => ({
flags: {
get teamWorkspacesEnabled() {
return mockTeamWorkspacesEnabled.value
},
get consolidatedBillingEnabled() {
return mockConsolidatedBillingEnabled.value
}
}
})
@@ -165,7 +151,6 @@ describe('useBillingContext', () => {
setActivePinia(createPinia())
vi.clearAllMocks()
mockTeamWorkspacesEnabled.value = false
mockConsolidatedBillingEnabled.value = false
mockIsPersonal.value = true
mockPlans.value = []
mockBillingStatus.value = { ...DEFAULT_BILLING_STATUS }
@@ -177,27 +162,16 @@ describe('useBillingContext', () => {
expect(type.value).toBe('legacy')
})
it('keeps personal on legacy when consolidated billing is disabled', () => {
it('selects workspace type for personal when team workspaces are enabled', () => {
mockTeamWorkspacesEnabled.value = true
mockConsolidatedBillingEnabled.value = false
mockIsPersonal.value = true
const { type } = useBillingContext()
expect(type.value).toBe('legacy')
})
it('selects workspace type for personal when consolidated billing is enabled', () => {
mockTeamWorkspacesEnabled.value = true
mockConsolidatedBillingEnabled.value = true
mockIsPersonal.value = true
const { type } = useBillingContext()
expect(type.value).toBe('workspace')
})
it('selects workspace type for team regardless of consolidated billing', () => {
it('selects workspace type for team when team workspaces are enabled', () => {
mockTeamWorkspacesEnabled.value = true
mockConsolidatedBillingEnabled.value = false
mockIsPersonal.value = false
const { type } = useBillingContext()
@@ -298,7 +272,6 @@ describe('useBillingContext', () => {
expect(workspaceApi.getBillingStatus).not.toHaveBeenCalled()
// Authenticated remote config resolves the flag on for the same workspace
mockConsolidatedBillingEnabled.value = true
mockTeamWorkspacesEnabled.value = true
await vi.waitFor(() => {
@@ -307,27 +280,9 @@ describe('useBillingContext', () => {
})
})
it('moves a personal workspace to workspace billing when consolidated billing flips on', async () => {
mockTeamWorkspacesEnabled.value = true
mockConsolidatedBillingEnabled.value = false
mockIsPersonal.value = true
const { type } = useBillingContext()
await nextTick()
expect(type.value).toBe('legacy')
mockConsolidatedBillingEnabled.value = true
await vi.waitFor(() => {
expect(type.value).toBe('workspace')
expect(workspaceApi.getBillingStatus).toHaveBeenCalled()
})
})
describe('subscription mirror to workspace store', () => {
it('mirrors subscription for personal workspaces on the consolidated billing flow', async () => {
it('mirrors subscription for personal workspaces when team workspaces are enabled', async () => {
mockTeamWorkspacesEnabled.value = true
mockConsolidatedBillingEnabled.value = true
mockIsPersonal.value = true
const { initialize } = useBillingContext()
@@ -339,20 +294,6 @@ describe('useBillingContext', () => {
subscriptionPlan: null
})
})
it('never clobbers the list-derived store when a subscription is absent', async () => {
mockTeamWorkspacesEnabled.value = true
mockIsPersonal.value = false
const { initialize } = useBillingContext()
await initialize()
await nextTick()
expect(mockUpdateActiveWorkspace).not.toHaveBeenCalledWith({
isSubscribed: false,
subscriptionPlan: null
})
})
})
describe('getMaxSeats', () => {

View File

@@ -1,6 +1,7 @@
import { computed, ref, shallowRef, toValue, watch } from 'vue'
import { createSharedComposable } from '@vueuse/core'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import {
KEY_TO_TIER,
getTierFeatures
@@ -17,10 +18,10 @@ import type {
BalanceInfo,
BillingActions,
BillingContext,
BillingType,
BillingState,
SubscriptionInfo
} from './types'
import { useBillingRouting } from './useBillingRouting'
import { useLegacyBilling } from './useLegacyBilling'
import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling'
@@ -34,9 +35,8 @@ const LEGACY_TEAM_PLAN_SLUG_PREFIX = 'team-'
* Unified billing context that selects the billing implementation by build/flag.
*
* - Team workspaces disabled (OSS/Desktop): legacy billing via /customers/*
* - Team workspaces enabled: workspace billing via /api/billing/* for team
* workspaces, and for personal workspaces once consolidated billing is
* enabled; personal workspaces otherwise stay on legacy billing
* - Team workspaces enabled: workspace billing via /api/billing/* for both
* personal (single-seat workspace) and team workspaces
*
* The context automatically initializes when the workspace changes and provides
* a unified interface for subscription status, balance, and billing actions.
@@ -69,7 +69,7 @@ const LEGACY_TEAM_PLAN_SLUG_PREFIX = 'team-'
*/
function useBillingContextInternal(): BillingContext {
const store = useTeamWorkspaceStore()
const { type } = useBillingRouting()
const { flags } = useFeatureFlags()
const legacyBillingRef = shallowRef<(BillingState & BillingActions) | null>(
null
@@ -96,6 +96,16 @@ function useBillingContextInternal(): BillingContext {
const isLoading = ref(false)
const error = ref<string | null>(null)
/**
* Determines which billing type to use, keyed only on the build/flag:
* - Team workspaces feature disabled (OSS/Desktop): legacy (/customers)
* - Team workspaces feature enabled: workspace (/api/billing), for both
* personal (single-seat workspace) and team workspaces
*/
const type = computed<BillingType>(() =>
flags.teamWorkspacesEnabled ? 'workspace' : 'legacy'
)
const activeContext = computed(() =>
type.value === 'legacy' ? getLegacyBilling() : getWorkspaceBilling()
)
@@ -160,12 +170,9 @@ function useBillingContextInternal(): BillingContext {
return plan?.max_seats ?? getTierFeatures(tierKey).maxMembers
}
// Sync subscription info to workspace store for display in workspace switcher.
// Subscribed means active AND not cancelled, so the delete button enables
// after cancellation, even before the period ends. A null subscription means
// "not loaded yet" (adapters are discarded on every workspace/type switch);
// skip it so the transient reinit gap can't clobber the list-derived baseline
// (personal workspaces and subscribed teams already read subscribed there).
// Sync subscription info to workspace store for display in workspace switcher
// A subscription is considered "subscribed" for workspace purposes if it's active AND not cancelled
// This ensures the delete button is enabled after cancellation, even before the period ends
watch(
subscription,
(sub) => {
@@ -179,27 +186,24 @@ function useBillingContextInternal(): BillingContext {
{ immediate: true }
)
// Discarding the adapter instances forces a fresh fetch and lets an in-flight
// init detect that it was superseded (its captured adapter is no longer the
// active one), so a stale response can't resolve into a ready state for the
// wrong workspace.
function resetBillingState() {
legacyBillingRef.value = null
workspaceBillingRef.value = null
isInitialized.value = false
isLoading.value = false
error.value = null
}
// type flips when the team-workspaces or consolidated-billing flag resolves
// from authenticated config, swapping the active backend. Reset then reinit
// on every workspace-id or type change.
// type can flip after setup when the team-workspaces flag resolves from
// authenticated config, swapping the active backend; a fresh init is needed.
// The watch fires only when id or type actually changes, so any fire with a
// workspace selected warrants a reinit.
watch(
[() => store.activeWorkspace?.id, () => type.value],
async ([newWorkspaceId]) => {
resetBillingState()
if (!newWorkspaceId) return
if (!newWorkspaceId) {
resetBillingState()
return
}
isInitialized.value = false
try {
await initialize()
} catch (err) {
@@ -212,20 +216,17 @@ function useBillingContextInternal(): BillingContext {
async function initialize(): Promise<void> {
if (isInitialized.value) return
const adapter = activeContext.value
isLoading.value = true
error.value = null
try {
await adapter.initialize()
if (activeContext.value !== adapter) return
await activeContext.value.initialize()
isInitialized.value = true
} catch (err) {
if (activeContext.value !== adapter) return
error.value =
err instanceof Error ? err.message : 'Failed to initialize billing'
throw err
} finally {
if (activeContext.value === adapter) isLoading.value = false
isLoading.value = false
}
}

View File

@@ -1,99 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useBillingRouting } from './useBillingRouting'
const { mockFlags, mockActiveWorkspace } = vi.hoisted(() => ({
mockFlags: {
teamWorkspacesEnabled: false,
consolidatedBillingEnabled: false
},
mockActiveWorkspace: {
value: null as { id: string; type: 'personal' | 'team' } | null
}
}))
vi.mock('@/composables/useFeatureFlags', () => ({
useFeatureFlags: () => ({ flags: mockFlags })
}))
vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({
useTeamWorkspaceStore: () => ({
get activeWorkspace() {
return mockActiveWorkspace.value
}
})
}))
const personal = { id: 'w-personal', type: 'personal' as const }
const team = { id: 'w-team', type: 'team' as const }
describe('useBillingRouting', () => {
beforeEach(() => {
mockFlags.teamWorkspacesEnabled = false
mockFlags.consolidatedBillingEnabled = false
mockActiveWorkspace.value = personal
})
it('uses legacy billing when team workspaces are disabled', () => {
mockFlags.teamWorkspacesEnabled = false
mockActiveWorkspace.value = team
const { type, shouldUseWorkspaceBilling } = useBillingRouting()
expect(type.value).toBe('legacy')
expect(shouldUseWorkspaceBilling.value).toBe(false)
})
it('keeps personal on legacy when consolidated billing is disabled', () => {
mockFlags.teamWorkspacesEnabled = true
mockFlags.consolidatedBillingEnabled = false
mockActiveWorkspace.value = personal
const { type } = useBillingRouting()
expect(type.value).toBe('legacy')
})
it('moves personal to workspace billing when consolidated billing is enabled', () => {
mockFlags.teamWorkspacesEnabled = true
mockFlags.consolidatedBillingEnabled = true
mockActiveWorkspace.value = personal
const { type, shouldUseWorkspaceBilling } = useBillingRouting()
expect(type.value).toBe('workspace')
expect(shouldUseWorkspaceBilling.value).toBe(true)
})
it('uses workspace billing for team workspaces regardless of consolidated billing', () => {
mockFlags.teamWorkspacesEnabled = true
mockFlags.consolidatedBillingEnabled = false
mockActiveWorkspace.value = team
const { type, shouldUseWorkspaceBilling } = useBillingRouting()
expect(type.value).toBe('workspace')
expect(shouldUseWorkspaceBilling.value).toBe(true)
})
it('uses workspace billing for team workspaces with consolidated billing enabled', () => {
mockFlags.teamWorkspacesEnabled = true
mockFlags.consolidatedBillingEnabled = true
mockActiveWorkspace.value = team
const { type, shouldUseWorkspaceBilling } = useBillingRouting()
expect(type.value).toBe('workspace')
expect(shouldUseWorkspaceBilling.value).toBe(true)
})
it('defaults to legacy while the workspace has not loaded', () => {
mockFlags.teamWorkspacesEnabled = true
mockFlags.consolidatedBillingEnabled = true
mockActiveWorkspace.value = null
const { type } = useBillingRouting()
expect(type.value).toBe('legacy')
})
})

View File

@@ -1,36 +0,0 @@
import { computed } from 'vue'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
import type { BillingType } from './types'
/**
* Selects the billing backend for the active workspace: legacy user-scoped
* (`/customers/*`) or workspace-scoped (`/api/billing/*`). Personal workspaces
* stay legacy until `consolidatedBillingEnabled`; team workspaces are always
* workspace-scoped. The routing matrix is covered in useBillingRouting.test.ts.
*/
export function useBillingRouting() {
const { flags } = useFeatureFlags()
const workspaceStore = useTeamWorkspaceStore()
const type = computed<BillingType>(() => {
if (!flags.teamWorkspacesEnabled) return 'legacy'
// An unloaded workspace has no type yet; stay legacy so bootstrap never
// eagerly routes to workspace billing.
const workspaceType = workspaceStore.activeWorkspace?.type
if (!workspaceType) return 'legacy'
if (workspaceType === 'personal' && !flags.consolidatedBillingEnabled) {
return 'legacy'
}
return 'workspace'
})
const shouldUseWorkspaceBilling = computed(() => type.value === 'workspace')
return { type, shouldUseWorkspaceBilling }
}

View File

@@ -1,104 +0,0 @@
import type { AxiosInstance, AxiosResponse } from 'axios'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useApiRequest } from '@/composables/useApiRequest'
const mockIsAbortError = vi.hoisted(() => vi.fn())
vi.mock('@/utils/typeGuardUtil', () => ({
isAbortError: mockIsAbortError
}))
const client = { id: 'test-client' } as unknown as AxiosInstance
function response<T>(data: T): AxiosResponse<T> {
return { data } as AxiosResponse<T>
}
describe('useApiRequest', () => {
beforeEach(() => {
mockIsAbortError.mockReset()
mockIsAbortError.mockReturnValue(false)
})
it('returns response data and toggles loading state', async () => {
const { isLoading, error, executeRequest } = useApiRequest({
client,
mapError: vi.fn()
})
expect(isLoading.value).toBe(false)
const pending = executeRequest(async () => response('ok'), {
errorContext: 'ctx'
})
expect(isLoading.value).toBe(true)
await expect(pending).resolves.toBe('ok')
expect(isLoading.value).toBe(false)
expect(error.value).toBeNull()
})
it('passes the injected client to the api call', async () => {
const apiCall = vi.fn(async () => response(1))
const { executeRequest } = useApiRequest({ client, mapError: vi.fn() })
await executeRequest(apiCall, { errorContext: 'ctx' })
expect(apiCall).toHaveBeenCalledWith(client)
})
it('maps errors through the injected mapper and stores the message', async () => {
const mapError = vi.fn(() => 'mapped message')
const routeSpecificErrors = { 404: 'nope' }
const boom = new Error('boom')
const { error, executeRequest } = useApiRequest({ client, mapError })
const result = await executeRequest(
() => {
throw boom
},
{ errorContext: 'ctx', routeSpecificErrors }
)
expect(result).toBeNull()
expect(mapError).toHaveBeenCalledWith(boom, 'ctx', routeSpecificErrors)
expect(error.value).toBe('mapped message')
})
it('swallows cancellations without mapping an error', async () => {
mockIsAbortError.mockReturnValue(true)
const mapError = vi.fn(() => 'should not run')
const { error, executeRequest } = useApiRequest({ client, mapError })
const result = await executeRequest(
() => {
throw new Error('aborted')
},
{ errorContext: 'ctx' }
)
expect(result).toBeNull()
expect(mapError).not.toHaveBeenCalled()
expect(error.value).toBeNull()
})
it('runs onSuccess only after a successful response', async () => {
const onSuccess = vi.fn()
const { executeRequest } = useApiRequest({ client, mapError: vi.fn() })
await executeRequest(async () => response('ok'), {
errorContext: 'ctx',
onSuccess
})
expect(onSuccess).toHaveBeenCalledTimes(1)
onSuccess.mockClear()
await executeRequest(
() => {
throw new Error('boom')
},
{ errorContext: 'ctx', onSuccess }
)
expect(onSuccess).not.toHaveBeenCalled()
})
})

View File

@@ -1,63 +0,0 @@
import type { AxiosInstance, AxiosResponse } from 'axios'
import { ref } from 'vue'
import { isAbortError } from '@/utils/typeGuardUtil'
/**
* Maps a caught request error to a user-facing message string.
* Each service injects its own mapper so it keeps control of the exact
* status-to-message copy it presents.
*/
export type ApiErrorMapper = (
err: unknown,
errorContext: string,
routeSpecificErrors?: Record<number, string>
) => string
export interface ExecuteRequestOptions {
errorContext: string
routeSpecificErrors?: Record<number, string>
/** Side effect run after a successful response, before the data is returned. */
onSuccess?: () => unknown
}
/**
* Shared axios request wrapper: owns the `isLoading`/`error` state and the
* try/catch/finally plumbing, while the caller injects the axios instance and
* an error mapper. Cancellations are swallowed (no error set, `null` returned).
*/
export function useApiRequest({
client,
mapError
}: {
client: AxiosInstance
mapError: ApiErrorMapper
}) {
const isLoading = ref(false)
const error = ref<string | null>(null)
async function executeRequest<T>(
apiCall: (client: AxiosInstance) => Promise<AxiosResponse<T>>,
options: ExecuteRequestOptions
): Promise<T | null> {
const { errorContext, routeSpecificErrors, onSuccess } = options
isLoading.value = true
error.value = null
try {
const response = await apiCall(client)
await onSuccess?.()
return response.data
} catch (err) {
if (isAbortError(err)) return null
error.value = mapError(err, errorContext, routeSpecificErrors)
return null
} finally {
isLoading.value = false
}
}
return { isLoading, error, executeRequest }
}

View File

@@ -6,12 +6,6 @@ import {
useFeatureFlags
} from '@/composables/useFeatureFlags'
import * as distributionTypes from '@/platform/distribution/types'
import {
cachedConsolidatedBillingEnabled,
cachedTeamWorkspacesEnabled,
remoteConfig,
remoteConfigState
} from '@/platform/remoteConfig/remoteConfig'
import { api } from '@/scripts/api'
// Mock the API module
@@ -225,86 +219,6 @@ describe('useFeatureFlags', () => {
const { flags } = useFeatureFlags()
expect(flags.teamWorkspacesEnabled).toBe(true)
})
it('consolidatedBillingEnabled override bypasses isCloud and isAuthenticatedConfigLoaded guards', () => {
vi.mocked(distributionTypes).isCloud = false
localStorage.setItem('ff:consolidated_billing_enabled', 'true')
const { flags } = useFeatureFlags()
expect(flags.consolidatedBillingEnabled).toBe(true)
})
it('consolidatedBillingEnabled is false off-cloud even without an override', () => {
vi.mocked(distributionTypes).isCloud = false
const { flags } = useFeatureFlags()
expect(flags.consolidatedBillingEnabled).toBe(false)
})
})
describe('auth-gated flags on cloud', () => {
beforeEach(() => {
vi.mocked(distributionTypes).isCloud = true
remoteConfigState.value = 'unloaded'
remoteConfig.value = {}
cachedTeamWorkspacesEnabled.value = undefined
cachedConsolidatedBillingEnabled.value = undefined
localStorage.clear()
})
afterEach(() => {
vi.mocked(distributionTypes).isCloud = false
remoteConfigState.value = 'unloaded'
remoteConfig.value = {}
cachedTeamWorkspacesEnabled.value = undefined
cachedConsolidatedBillingEnabled.value = undefined
localStorage.clear()
})
it('returns the cached session value during the auth window', () => {
cachedTeamWorkspacesEnabled.value = false
cachedConsolidatedBillingEnabled.value = true
const { flags } = useFeatureFlags()
expect(flags.teamWorkspacesEnabled).toBe(false)
expect(flags.consolidatedBillingEnabled).toBe(true)
})
it('defaults to false during the auth window when nothing is cached', () => {
const { flags } = useFeatureFlags()
expect(flags.teamWorkspacesEnabled).toBe(false)
expect(flags.consolidatedBillingEnabled).toBe(false)
})
it('prefers authenticated remoteConfig over the server feature fallback', () => {
remoteConfigState.value = 'authenticated'
remoteConfig.value = {
team_workspaces_enabled: true,
consolidated_billing_enabled: true
}
vi.mocked(api.getServerFeature).mockReturnValue(false)
const { flags } = useFeatureFlags()
expect(flags.teamWorkspacesEnabled).toBe(true)
expect(flags.consolidatedBillingEnabled).toBe(true)
})
it('falls back to api.getServerFeature when authenticated config omits the flag', () => {
remoteConfigState.value = 'authenticated'
remoteConfig.value = {}
vi.mocked(api.getServerFeature).mockImplementation(
(path, defaultValue) => {
if (path === ServerFeatureFlag.TEAM_WORKSPACES_ENABLED) return true
if (path === ServerFeatureFlag.CONSOLIDATED_BILLING_ENABLED)
return true
return defaultValue
}
)
const { flags } = useFeatureFlags()
expect(flags.teamWorkspacesEnabled).toBe(true)
expect(flags.consolidatedBillingEnabled).toBe(true)
})
})
describe('signupTurnstileMode', () => {

View File

@@ -1,9 +1,7 @@
import { computed, reactive, readonly } from 'vue'
import type { Ref } from 'vue'
import { isCloud, isNightly } from '@/platform/distribution/types'
import {
cachedConsolidatedBillingEnabled,
cachedTeamWorkspacesEnabled,
isAuthenticatedConfigLoaded,
remoteConfig
@@ -32,7 +30,6 @@ export enum ServerFeatureFlag {
COMFYHUB_PROFILE_GATE_ENABLED = 'comfyhub_profile_gate_enabled',
SHOW_SIGNIN_BUTTON = 'show_signin_button',
UNIFIED_CLOUD_AUTH = 'unified_cloud_auth',
CONSOLIDATED_BILLING_ENABLED = 'consolidated_billing_enabled',
SIGNUP_TURNSTILE = 'signup_turnstile'
}
@@ -49,26 +46,6 @@ function resolveFlag<T>(
return remoteConfigValue ?? api.getServerFeature(flagKey, defaultValue)
}
/**
* Resolves a per-user, Cloud-only flag that selects backend behavior. Off the
* Cloud build it is always false; during the auth window it falls back to the
* cached session value so anonymous bootstrap config cannot route the user to
* the wrong backend before authenticated config confirms the flag.
*/
function resolveAuthGatedFlag(
flagKey: string,
remoteConfigValue: boolean | undefined,
cachedValue: Ref<boolean | undefined>
): boolean {
const override = getDevOverride<boolean>(flagKey)
if (override !== undefined) return override
if (!isCloud) return false
if (!isAuthenticatedConfigLoaded.value) return cachedValue.value ?? false
return remoteConfigValue ?? api.getServerFeature(flagKey, false)
}
/**
* Composable for reactive access to server-side feature flags
*/
@@ -127,10 +104,18 @@ export function useFeatureFlags() {
* and prevents race conditions during initialization.
*/
get teamWorkspacesEnabled() {
return resolveAuthGatedFlag(
ServerFeatureFlag.TEAM_WORKSPACES_ENABLED,
remoteConfig.value.team_workspaces_enabled,
cachedTeamWorkspacesEnabled
const override = getDevOverride<boolean>(
ServerFeatureFlag.TEAM_WORKSPACES_ENABLED
)
if (override !== undefined) return override
if (!isCloud) return false
if (!isAuthenticatedConfigLoaded.value)
return cachedTeamWorkspacesEnabled.value ?? false
return (
remoteConfig.value.team_workspaces_enabled ??
api.getServerFeature(ServerFeatureFlag.TEAM_WORKSPACES_ENABLED, false)
)
},
get userSecretsEnabled() {
@@ -190,18 +175,6 @@ export function useFeatureFlags() {
false
)
},
/**
* Whether personal workspaces use the consolidated (workspace-scoped)
* billing flow. While false (default), personal workspaces stay on the
* legacy per-user billing flow; team workspaces are unaffected.
*/
get consolidatedBillingEnabled() {
return resolveAuthGatedFlag(
ServerFeatureFlag.CONSOLIDATED_BILLING_ENABLED,
remoteConfig.value.consolidated_billing_enabled,
cachedConsolidatedBillingEnabled
)
},
get signupTurnstileMode() {
return resolveFlag(
ServerFeatureFlag.SIGNUP_TURNSTILE,

View File

@@ -2484,8 +2484,6 @@
"model": "Model",
"added": "Added",
"accountInitialized": "Account initialized",
"loadEventsError": "Failed to load activity. Please try again.",
"loadEventsUnknownError": "Something went wrong while loading activity. Please refresh and try again.",
"eventTypes": {
"creditAdded": "Credits Added",
"accountCreated": "Account Created",

View File

@@ -18,7 +18,7 @@
</div>
<!-- Workspace mode: workspace-aware subscription content (renders its own footer) -->
<SubscriptionPanelContentWorkspace v-if="shouldUseWorkspaceBilling" />
<SubscriptionPanelContentWorkspace v-if="teamWorkspacesEnabled" />
<!-- Legacy mode: user-level subscription content -->
<template v-else>
<SubscriptionPanelContentLegacy />
@@ -29,20 +29,24 @@
</template>
<script setup lang="ts">
import { defineAsyncComponent } from 'vue'
import { computed, defineAsyncComponent } from 'vue'
import CloudBadge from '@/components/topbar/CloudBadge.vue'
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useBillingRouting } from '@/composables/billing/useBillingRouting'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import SubscriptionFooterLinks from '@/platform/cloud/subscription/components/SubscriptionFooterLinks.vue'
import SubscriptionPanelContentLegacy from '@/platform/cloud/subscription/components/SubscriptionPanelContentLegacy.vue'
import { isCloud } from '@/platform/distribution/types'
const SubscriptionPanelContentWorkspace = defineAsyncComponent(
() =>
import('@/platform/workspace/components/SubscriptionPanelContentWorkspace.vue')
)
const { shouldUseWorkspaceBilling } = useBillingRouting()
const { flags } = useFeatureFlags()
const teamWorkspacesEnabled = computed(
() => isCloud && flags.teamWorkspacesEnabled
)
const { isActiveSubscription } = useBillingContext()
</script>

View File

@@ -9,7 +9,7 @@ const mockTrackSubscription = vi.hoisted(() => vi.fn())
const mockIsInPersonalWorkspace = vi.hoisted(() => ({ value: true }))
const mockIsFreeTier = vi.hoisted(() => ({ value: false }))
const mockTier = vi.hoisted(() => ({ value: 'FREE' as string | null }))
const mockShouldUseWorkspaceBilling = vi.hoisted(() => ({ value: false }))
const mockTeamWorkspacesEnabled = vi.hoisted(() => ({ value: false }))
const mockIsCloud = vi.hoisted(() => ({ value: true }))
const mockIsLegacyTeamPlan = vi.hoisted(() => ({ value: false }))
const mockCanManageSubscription = vi.hoisted(() => ({ value: true }))
@@ -35,10 +35,12 @@ vi.mock('@/services/dialogService', () => ({
})
}))
vi.mock('@/composables/billing/useBillingRouting', () => ({
useBillingRouting: () => ({
get shouldUseWorkspaceBilling() {
return mockShouldUseWorkspaceBilling
vi.mock('@/composables/useFeatureFlags', () => ({
useFeatureFlags: () => ({
flags: {
get teamWorkspacesEnabled() {
return mockTeamWorkspacesEnabled.value
}
}
})
}))
@@ -86,7 +88,7 @@ describe('useSubscriptionDialog', () => {
mockIsInPersonalWorkspace.value = true
mockIsFreeTier.value = false
mockTier.value = 'FREE'
mockShouldUseWorkspaceBilling.value = false
mockTeamWorkspacesEnabled.value = false
mockIsLegacyTeamPlan.value = false
mockCanManageSubscription.value = true
@@ -117,7 +119,7 @@ describe('useSubscriptionDialog', () => {
})
it('does not wire onChooseTeam on the unified table (personal subscribes directly)', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = true
const { showPricingTable } = useSubscriptionDialog()
@@ -129,7 +131,7 @@ describe('useSubscriptionDialog', () => {
})
it('sizes the unified pricing dialog via the Reka contentClass, not the ignored PrimeVue style', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = true
const { showPricingTable } = useSubscriptionDialog()
@@ -144,7 +146,7 @@ describe('useSubscriptionDialog', () => {
})
it('defaults to the personal tab in a personal workspace', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = true
const { showPricingTable } = useSubscriptionDialog()
@@ -155,7 +157,7 @@ describe('useSubscriptionDialog', () => {
})
it('opens the team tab when planMode is forced from a personal workspace', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = true
const { showPricingTable } = useSubscriptionDialog()
@@ -165,9 +167,8 @@ describe('useSubscriptionDialog', () => {
expect(props.initialPlanMode).toBe('team')
})
it('uses the legacy table (with onChooseTeam) on the legacy billing flow', () => {
mockShouldUseWorkspaceBilling.value = false
mockIsInPersonalWorkspace.value = true
it('uses the legacy table (with onChooseTeam) when team workspaces are disabled', () => {
mockTeamWorkspacesEnabled.value = false
const { showPricingTable } = useSubscriptionDialog()
showPricingTable()
@@ -177,7 +178,7 @@ describe('useSubscriptionDialog', () => {
})
it('routes an existing per-member (legacy) team subscriber to the old team table', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = false
mockIsLegacyTeamPlan.value = true
const { showPricingTable } = useSubscriptionDialog()
@@ -195,7 +196,7 @@ describe('useSubscriptionDialog', () => {
})
it('keeps a non-legacy (credit-slider) team subscriber on the unified table', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = false
mockIsLegacyTeamPlan.value = false
const { showPricingTable } = useSubscriptionDialog()
@@ -219,7 +220,7 @@ describe('useSubscriptionDialog', () => {
})
it('tracks modal_opened on the workspace (unified) path too', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
const { showPricingTable } = useSubscriptionDialog()
showPricingTable({ reason: 'subscribe_to_run' })
@@ -231,7 +232,7 @@ describe('useSubscriptionDialog', () => {
})
it('does not track modal_opened for the inactive member dialog', () => {
mockShouldUseWorkspaceBilling.value = true
mockTeamWorkspacesEnabled.value = true
mockIsInPersonalWorkspace.value = false
mockCanManageSubscription.value = false
const { showPricingTable } = useSubscriptionDialog()

View File

@@ -2,7 +2,7 @@ import { defineAsyncComponent } from 'vue'
import { useDialogService } from '@/services/dialogService'
import { useDialogStore } from '@/stores/dialogStore'
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useBillingRouting } from '@/composables/billing/useBillingRouting'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { isCloud } from '@/platform/distribution/types'
import { useTelemetry } from '@/platform/telemetry'
import type { PaymentIntentSource } from '@/platform/telemetry/types'
@@ -24,7 +24,7 @@ export interface SubscriptionDialogOptions {
}
export const useSubscriptionDialog = () => {
const { shouldUseWorkspaceBilling } = useBillingRouting()
const { flags } = useFeatureFlags()
const dialogService = useDialogService()
const dialogStore = useDialogStore()
const workspaceStore = useTeamWorkspaceStore()
@@ -57,7 +57,7 @@ export const useSubscriptionDialog = () => {
// small read-only "ask your owner to reactivate" modal instead of the
// pricing table. Out-of-credits still routes everyone to the credits flow.
if (
shouldUseWorkspaceBilling.value &&
flags.teamWorkspacesEnabled &&
!workspaceStore.isInPersonalWorkspace &&
!permissions.value.canManageSubscription &&
options?.reason !== 'out_of_credits'
@@ -95,10 +95,9 @@ export const useSubscriptionDialog = () => {
}
// Jun-5 model: a single unified pricing table (personal/team plan toggle on
// one workspace) for workspaces on the consolidated billing flow. Replaces
// the old personal-vs-team workspace fork. Personal workspaces still on the
// legacy flow (consolidated billing disabled) get the legacy table.
if (shouldUseWorkspaceBilling.value) {
// one workspace) when team workspaces are enabled. Replaces the old
// personal-vs-team workspace fork. Flag-off keeps the legacy table.
if (flags.teamWorkspacesEnabled) {
// Existing per-member (legacy) team subscribers keep the old tier-based
// team table; the unified credit-slider table is for everyone else.
// Resolved lazily (not at composable setup): these three composables form

View File

@@ -1,5 +1,4 @@
import {
cachedConsolidatedBillingEnabled,
cachedTeamWorkspacesEnabled,
remoteConfig,
remoteConfigState
@@ -56,14 +55,10 @@ export async function refreshRemoteConfig(
window.__CONFIG__ = config
remoteConfig.value = config
remoteConfigState.value = useAuth ? 'authenticated' : 'anonymous'
if (useAuth) {
if (useAuth)
cachedTeamWorkspacesEnabled.value = Boolean(
config.team_workspaces_enabled
)
cachedConsolidatedBillingEnabled.value = Boolean(
config.consolidated_billing_enabled
)
}
return
}

View File

@@ -59,8 +59,3 @@ export const cachedTeamWorkspacesEnabled = useStorage<boolean | undefined>(
'team_workspaces_enabled' satisfies `${ServerFeatureFlag.TEAM_WORKSPACES_ENABLED}`,
undefined
)
export const cachedConsolidatedBillingEnabled = useStorage<boolean | undefined>(
'consolidated_billing_enabled' satisfies `${ServerFeatureFlag.CONSOLIDATED_BILLING_ENABLED}`,
undefined
)

View File

@@ -111,7 +111,6 @@ export type RemoteConfig = {
comfyhub_upload_enabled?: boolean
comfyhub_profile_gate_enabled?: boolean
unified_cloud_auth?: boolean
consolidated_billing_enabled?: boolean
sentry_dsn?: string
turnstile_sitekey?: string
// Raw, unvalidated wire value (a server typo like 'enfroce' is possible).

View File

@@ -11,49 +11,21 @@ import type { SettingTreeNode } from '@/platform/settings/settingStore'
import { useSettingUI } from './useSettingUI'
const env = vi.hoisted(() => {
const state = {
isCloud: false,
isDesktop: false,
isLoggedIn: false,
teamWorkspacesEnabled: false,
userSecretsEnabled: false,
isActiveSubscription: false,
billingType: 'legacy' as 'legacy' | 'workspace'
}
const fakeRef = <K extends keyof typeof state>(key: K) => ({
get value() {
return state[key]
}
})
return { state, fakeRef }
})
vi.mock('vue-i18n', () => ({
useI18n: () => ({ t: (_: string, fallback: string) => fallback })
}))
vi.mock('@/composables/auth/useCurrentUser', () => ({
useCurrentUser: () => ({ isLoggedIn: env.fakeRef('isLoggedIn') })
useCurrentUser: () => ({ isLoggedIn: ref(false) })
}))
vi.mock('@/composables/billing/useBillingContext', () => ({
useBillingContext: () => ({
isActiveSubscription: env.fakeRef('isActiveSubscription'),
type: env.fakeRef('billingType')
})
useBillingContext: () => ({ isActiveSubscription: ref(false) })
}))
vi.mock('@/composables/useFeatureFlags', () => ({
useFeatureFlags: () => ({
flags: {
get teamWorkspacesEnabled() {
return env.state.teamWorkspacesEnabled
},
get userSecretsEnabled() {
return env.state.userSecretsEnabled
}
}
flags: { teamWorkspacesEnabled: false, userSecretsEnabled: false }
})
}))
@@ -62,12 +34,8 @@ vi.mock('@/composables/useVueFeatureFlags', () => ({
}))
vi.mock('@/platform/distribution/types', () => ({
get isCloud() {
return env.state.isCloud
},
get isDesktop() {
return env.state.isDesktop
}
isCloud: false,
isDesktop: false
}))
vi.mock('@/platform/settings/settingStore', () => ({
@@ -109,16 +77,6 @@ describe('useSettingUI', () => {
setActivePinia(createTestingPinia())
vi.clearAllMocks()
Object.assign(env.state, {
isCloud: false,
isDesktop: false,
isLoggedIn: false,
teamWorkspacesEnabled: false,
userSecretsEnabled: false,
isActiveSubscription: false,
billingType: 'legacy'
})
vi.mocked(useSettingStore).mockReturnValue({
settingsById: mockSettings
} as ReturnType<typeof useSettingStore>)
@@ -179,59 +137,4 @@ describe('useSettingUI', () => {
const { defaultCategory } = useSettingUI('about', 'Comfy.Locale')
expect(defaultCategory.value.key).toBe('about')
})
describe('legacy billing in the workspace layout', () => {
const navKeys = (groups: { items: { id: string }[] }[]) =>
groups.flatMap((group) => group.items.map((item) => item.id))
beforeEach(() => {
Object.assign(env.state, {
isCloud: true,
isLoggedIn: true,
teamWorkspacesEnabled: true,
isActiveSubscription: true
})
window.__CONFIG__ = {
subscription_required: true
} as typeof window.__CONFIG__
})
it('exposes the legacy plan panel when billing is legacy', () => {
env.state.billingType = 'legacy'
const { defaultCategory, navGroups } = useSettingUI('subscription')
expect(defaultCategory.value.key).toBe('subscription')
expect(navKeys(navGroups.value)).toContain('subscription')
expect(navKeys(navGroups.value)).toContain('workspace')
})
it('hides the legacy plan panel when billing is workspace', () => {
env.state.billingType = 'workspace'
const { navGroups } = useSettingUI()
expect(navKeys(navGroups.value)).not.toContain('subscription')
expect(navKeys(navGroups.value)).toContain('workspace')
})
it('never renders the plan panel in more than one tab', () => {
const countSubscription = () => {
const { navGroups } = useSettingUI()
return navKeys(navGroups.value).filter((id) => id === 'subscription')
.length
}
for (const teamWorkspacesEnabled of [true, false]) {
for (const billingType of ['legacy', 'workspace'] as const) {
for (const isLoggedIn of [true, false]) {
Object.assign(env.state, {
teamWorkspacesEnabled,
billingType,
isLoggedIn
})
expect(countSubscription()).toBeLessThanOrEqual(1)
}
}
}
})
})
})

View File

@@ -53,7 +53,7 @@ export function useSettingUI(
const { flags } = useFeatureFlags()
const { shouldRenderVueNodes } = useVueFeatureFlags()
const { isActiveSubscription, type: billingType } = useBillingContext()
const { isActiveSubscription } = useBillingContext()
const teamWorkspacesEnabled = computed(
() => isCloud && flags.teamWorkspacesEnabled
@@ -157,13 +157,6 @@ export function useSettingUI(
return isActiveSubscription.value
})
const shouldShowLegacyPlanCreditsPanel = computed(
() =>
isLoggedIn.value &&
billingType.value === 'legacy' &&
shouldShowPlanCreditsPanel.value
)
const userPanel: SettingPanelItem = {
node: {
key: 'user',
@@ -308,9 +301,6 @@ export function useSettingUI(
label: 'General',
children: [
translateCategory(userPanel.node),
...(shouldShowLegacyPlanCreditsPanel.value && subscriptionPanel
? [translateCategory(subscriptionPanel.node)]
: []),
...coreSettingCategories.value.slice(0, 1).map(translateCategory),
...(shouldShowSecretsPanel.value
? [translateCategory(secretsPanel.node)]
@@ -342,7 +332,9 @@ export function useSettingUI(
label: 'Account',
children: [
userPanel.node,
...(shouldShowLegacyPlanCreditsPanel.value && subscriptionPanel
...(isLoggedIn.value &&
shouldShowPlanCreditsPanel.value &&
subscriptionPanel
? [subscriptionPanel.node]
: []),
...(shouldShowSecretsPanel.value ? [secretsPanel.node] : []),

View File

@@ -1,10 +1,10 @@
import type { AxiosError } from 'axios'
import type { AxiosError, AxiosResponse } from 'axios'
import axios from 'axios'
import { watch } from 'vue'
import { ref, watch } from 'vue'
import { useApiRequest } from '@/composables/useApiRequest'
import { getComfyApiBaseUrl } from '@/config/comfyApi'
import type { components, operations } from '@/types/comfyRegistryTypes'
import { isAbortError } from '@/utils/typeGuardUtil'
// Use generated types from OpenAPI spec
export type ReleaseNote = components['schemas']['ReleaseNote']
@@ -22,6 +22,9 @@ const releaseApiClient = axios.create({
// Release service for fetching release notes
export const useReleaseService = () => {
const isLoading = ref(false)
const error = ref<string | null>(null)
watch(
() => getComfyApiBaseUrl(),
(url) => {
@@ -29,7 +32,10 @@ export const useReleaseService = () => {
}
)
const mapError = (
// No transformation needed - API response matches the generated type
// Handle API errors with context
const handleApiError = (
err: unknown,
context: string,
routeSpecificErrors?: Record<number, string>
@@ -66,10 +72,28 @@ export const useReleaseService = () => {
return `${context}: ${axiosError.message}`
}
const { isLoading, error, executeRequest } = useApiRequest({
client: releaseApiClient,
mapError
})
// Execute API request with error handling
const executeApiRequest = async <T>(
apiCall: () => Promise<AxiosResponse<T>>,
errorContext: string,
routeSpecificErrors?: Record<number, string>
): Promise<T | null> => {
isLoading.value = true
error.value = null
try {
const response = await apiCall()
return response.data
} catch (err) {
// Don't treat cancellations as errors
if (isAbortError(err)) return null
error.value = handleApiError(err, errorContext, routeSpecificErrors)
return null
} finally {
isLoading.value = false
}
}
// Fetch release notes from API
const getReleases = async (
@@ -83,16 +107,17 @@ export const useReleaseService = () => {
400: 'Invalid project or version parameter'
}
const apiResponse = await executeRequest(
(client) =>
client.get<ReleaseNote[]>(endpoint, {
const apiResponse = await executeApiRequest(
() =>
releaseApiClient.get<ReleaseNote[]>(endpoint, {
params,
signal,
headers: deployEnvironment
? { 'Comfy-Env': deployEnvironment }
: undefined
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
return apiResponse

View File

@@ -1,198 +0,0 @@
import axios from 'axios'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useComfyRegistryService } from '@/services/comfyRegistryService'
const mockAxiosInstance = vi.hoisted(() => ({
get: vi.fn(),
post: vi.fn()
}))
vi.mock('axios', () => ({
default: {
create: vi.fn(() => mockAxiosInstance),
isAxiosError: vi.fn()
}
}))
describe('useComfyRegistryService', () => {
let service: ReturnType<typeof useComfyRegistryService>
beforeEach(() => {
vi.clearAllMocks()
mockAxiosInstance.get.mockResolvedValue({ data: {} })
mockAxiosInstance.post.mockResolvedValue({ data: {} })
service = useComfyRegistryService()
})
it('initializes with idle state', () => {
expect(service.isLoading.value).toBe(false)
expect(service.error.value).toBeNull()
})
describe('request routing', () => {
it('getNodeDefs hits the comfy-nodes endpoint', async () => {
await service.getNodeDefs({ packId: 'pack', version: '1.0.0' })
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/nodes/pack/versions/1.0.0/comfy-nodes',
expect.objectContaining({ params: {} })
)
})
it('getNodeDefs returns null without a packId or version', async () => {
const result = await service.getNodeDefs({ packId: '', version: '' })
expect(result).toBeNull()
expect(mockAxiosInstance.get).not.toHaveBeenCalled()
})
it('search hits the search endpoint', async () => {
await service.search({ search: 'sampler' })
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/nodes/search',
expect.objectContaining({ params: { search: 'sampler' } })
)
})
it('getPublisherById hits the publisher endpoint', async () => {
await service.getPublisherById('pub-1')
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/publishers/pub-1',
expect.any(Object)
)
})
it('listPacksForPublisher forwards include_banned', async () => {
await service.listPacksForPublisher('pub-1', true)
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/publishers/pub-1/nodes',
expect.objectContaining({ params: { include_banned: true } })
)
})
it('postPackReview posts the star rating', async () => {
await service.postPackReview('pack', 5)
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'/nodes/pack/reviews',
null,
expect.objectContaining({ params: { star: 5 } })
)
})
it('listAllPacks hits the nodes endpoint', async () => {
await service.listAllPacks({ page: 1 })
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/nodes',
expect.objectContaining({ params: { page: 1 } })
)
})
it('getPackVersions hits the versions endpoint', async () => {
await service.getPackVersions('pack')
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/nodes/pack/versions',
expect.any(Object)
)
})
it('getPackByVersion hits the specific version endpoint', async () => {
await service.getPackByVersion('pack', 'v-1')
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/nodes/pack/versions/v-1',
expect.any(Object)
)
})
it('getPackById hits the node endpoint', async () => {
await service.getPackById('pack')
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/nodes/pack',
expect.any(Object)
)
})
it('inferPackFromNodeName hits the comfy-nodes lookup endpoint', async () => {
await service.inferPackFromNodeName('KSampler')
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'/comfy-nodes/KSampler/node',
expect.any(Object)
)
})
it('getBulkNodeVersions posts the identifiers', async () => {
const nodeVersions = [{ node_id: 'pack', version: '1.0.0' }]
await service.getBulkNodeVersions(nodeVersions)
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'/bulk/nodes/versions',
{ node_versions: nodeVersions },
expect.any(Object)
)
})
it('returns the response data on success', async () => {
mockAxiosInstance.get.mockResolvedValue({ data: { id: 'pack' } })
const result = await service.getPackById('pack')
expect(result).toEqual({ id: 'pack' })
})
})
describe('error mapping', () => {
it('prefers a route-specific message for a matching status', async () => {
mockAxiosInstance.get.mockRejectedValue({
response: { status: 404, data: {} }
})
vi.mocked(axios.isAxiosError).mockReturnValue(true)
const result = await service.getPackById('missing')
expect(result).toBeNull()
expect(service.error.value).toBe(
'Pack not found: The pack with ID missing does not exist'
)
})
it('maps generic status codes to friendly messages', async () => {
mockAxiosInstance.get.mockRejectedValue({
response: { status: 401, data: {} }
})
vi.mocked(axios.isAxiosError).mockReturnValue(true)
await service.search()
expect(service.error.value).toBe('Unauthorized: Authentication required')
})
it('falls back to the axios message when there is no response', async () => {
mockAxiosInstance.get.mockRejectedValue({ message: 'Network Error' })
vi.mocked(axios.isAxiosError).mockReturnValue(true)
await service.search()
expect(service.error.value).toBe(
'Failed to perform search: Network Error'
)
})
it('handles non-axios errors', async () => {
mockAxiosInstance.get.mockRejectedValue(new Error('boom'))
vi.mocked(axios.isAxiosError).mockReturnValue(false)
await service.search()
expect(service.error.value).toBe('Failed to perform search: boom')
})
})
})

View File

@@ -1,8 +1,9 @@
import type { AxiosError } from 'axios'
import type { AxiosError, AxiosResponse } from 'axios'
import axios from 'axios'
import { ref } from 'vue'
import { useApiRequest } from '@/composables/useApiRequest'
import type { components, operations } from '@/types/comfyRegistryTypes'
import { isAbortError } from '@/utils/typeGuardUtil'
const API_BASE_URL = 'https://api.comfy.org'
@@ -21,7 +22,10 @@ const registryApiClient = axios.create({
* Service for interacting with the Comfy Registry API
*/
export const useComfyRegistryService = () => {
const mapError = (
const isLoading = ref(false)
const error = ref<string | null>(null)
const handleApiError = (
err: unknown,
context: string,
routeSpecificErrors?: Record<number, string>
@@ -60,10 +64,34 @@ export const useComfyRegistryService = () => {
return `${context}: ${axiosError.message}`
}
const { isLoading, error, executeRequest } = useApiRequest({
client: registryApiClient,
mapError
})
/**
* Execute an API request with error and loading state handling
* @param apiCall - Function that returns a promise with the API call
* @param errorContext - Context description for error messages
* @param routeSpecificErrors - Optional map of status codes to custom error messages
* @returns Promise with the API response data or null if the request failed
*/
const executeApiRequest = async <T>(
apiCall: () => Promise<AxiosResponse<T>>,
errorContext: string,
routeSpecificErrors?: Record<number, string>
): Promise<T | null> => {
isLoading.value = true
error.value = null
try {
const response = await apiCall()
return response.data
} catch (err) {
// Don't treat cancellations as errors
if (isAbortError(err)) return null
error.value = handleApiError(err, errorContext, routeSpecificErrors)
return null
} finally {
isLoading.value = false
}
}
/**
* Get the Comfy Node definitions in a specific version of a node pack
@@ -88,15 +116,16 @@ export const useComfyRegistryService = () => {
404: 'The requested node, version, or comfy node does not exist'
}
return executeRequest(
(client) =>
client.get<
return executeApiRequest(
() =>
registryApiClient.get<
operations['ListComfyNodes']['responses'][200]['content']['application/json']
>(endpoint, {
params: queryParams,
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -111,12 +140,12 @@ export const useComfyRegistryService = () => {
const endpoint = '/nodes/search'
const errorContext = 'Failed to perform search'
return executeRequest(
(client) =>
client.get<
return executeApiRequest(
() =>
registryApiClient.get<
operations['searchNodes']['responses'][200]['content']['application/json']
>(endpoint, { params, signal }),
{ errorContext }
errorContext
)
}
@@ -133,12 +162,13 @@ export const useComfyRegistryService = () => {
404: `Publisher not found: The publisher with ID ${publisherId} does not exist`
}
return executeRequest(
(client) =>
client.get<components['schemas']['Publisher']>(endpoint, {
return executeApiRequest(
() =>
registryApiClient.get<components['schemas']['Publisher']>(endpoint, {
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -158,13 +188,14 @@ export const useComfyRegistryService = () => {
404: `Publisher not found: The publisher with ID ${publisherId} does not exist`
}
return executeRequest(
(client) =>
client.get<components['schemas']['Node'][]>(endpoint, {
return executeApiRequest(
() =>
registryApiClient.get<components['schemas']['Node'][]>(endpoint, {
params,
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -184,13 +215,14 @@ export const useComfyRegistryService = () => {
404: `Pack not found: Pack with ID ${packId} does not exist`
}
return executeRequest(
(client) =>
client.post<components['schemas']['Node']>(endpoint, null, {
return executeApiRequest(
() =>
registryApiClient.post<components['schemas']['Node']>(endpoint, null, {
params,
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -204,12 +236,12 @@ export const useComfyRegistryService = () => {
const endpoint = '/nodes'
const errorContext = 'Failed to list packs'
return executeRequest(
(client) =>
client.get<
return executeApiRequest(
() =>
registryApiClient.get<
operations['listAllNodes']['responses'][200]['content']['application/json']
>(endpoint, { params, signal }),
{ errorContext }
errorContext
)
}
@@ -228,13 +260,14 @@ export const useComfyRegistryService = () => {
404: `Pack not found: Pack with ID ${packId} does not exist`
}
return executeRequest(
(client) =>
client.get<components['schemas']['NodeVersion'][]>(endpoint, {
params,
signal
}),
{ errorContext, routeSpecificErrors }
return executeApiRequest(
() =>
registryApiClient.get<components['schemas']['NodeVersion'][]>(
endpoint,
{ params, signal }
),
errorContext,
routeSpecificErrors
)
}
@@ -253,12 +286,13 @@ export const useComfyRegistryService = () => {
404: `Pack not found: Pack with ID ${packId} does not exist`
}
return executeRequest(
(client) =>
client.get<components['schemas']['NodeVersion']>(endpoint, {
return executeApiRequest(
() =>
registryApiClient.get<components['schemas']['NodeVersion']>(endpoint, {
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -275,12 +309,13 @@ export const useComfyRegistryService = () => {
404: `Pack not found: The pack with ID ${packId} does not exist`
}
return executeRequest(
(client) =>
client.get<components['schemas']['Node']>(endpoint, {
return executeApiRequest(
() =>
registryApiClient.get<components['schemas']['Node']>(endpoint, {
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -315,12 +350,13 @@ export const useComfyRegistryService = () => {
404: `Comfy node not found: The node with name ${nodeName} does not exist in the registry`
}
return executeRequest(
(client) =>
client.get<components['schemas']['Node']>(endpoint, {
return executeApiRequest(
() =>
registryApiClient.get<components['schemas']['Node']>(endpoint, {
signal
}),
{ errorContext, routeSpecificErrors }
errorContext,
routeSpecificErrors
)
}
@@ -361,16 +397,15 @@ export const useComfyRegistryService = () => {
node_versions: nodeVersions
}
return executeRequest(
(client) =>
client.post<components['schemas']['BulkNodeVersionsResponse']>(
endpoint,
requestBody,
{
signal
}
),
{ errorContext, routeSpecificErrors }
return executeApiRequest(
() =>
registryApiClient.post<
components['schemas']['BulkNodeVersionsResponse']
>(endpoint, requestBody, {
signal
}),
errorContext,
routeSpecificErrors
)
}

View File

@@ -1,13 +1,13 @@
import type { AxiosError } from 'axios'
import type { AxiosError, AxiosResponse } from 'axios'
import axios from 'axios'
import { watch } from 'vue'
import { ref, watch } from 'vue'
import { useApiRequest } from '@/composables/useApiRequest'
import { attachUnifiedRemintInterceptor } from '@/platform/auth/unified/remintRetry'
import { getComfyApiBaseUrl } from '@/config/comfyApi'
import { d, t } from '@/i18n'
import { useAuthStore } from '@/stores/authStore'
import type { components, operations } from '@/types/comfyRegistryTypes'
import { isAbortError } from '@/utils/typeGuardUtil'
export enum EventType {
CREDIT_ADDED = 'credit_added',
@@ -34,6 +34,9 @@ const customerApiClient = axios.create({
attachUnifiedRemintInterceptor(customerApiClient)
export const useCustomerEventsService = () => {
const isLoading = ref(false)
const error = ref<string | null>(null)
watch(
() => getComfyApiBaseUrl(),
(url) => {
@@ -41,31 +44,54 @@ export const useCustomerEventsService = () => {
}
)
const mapError = (
const handleRequestError = (
err: unknown,
context: string,
routeSpecificErrors?: Record<number, string>
): string => {
) => {
// Don't treat cancellation as an error
if (isAbortError(err)) return
let message: string
if (!axios.isAxiosError(err)) {
return `${context} failed: ${err instanceof Error ? err.message : String(err)}`
message = `${context} failed: ${err instanceof Error ? err.message : String(err)}`
} else {
const axiosError = err as AxiosError<{ message: string }>
const status = axiosError.response?.status
if (status && routeSpecificErrors?.[status]) {
message = routeSpecificErrors[status]
} else {
message =
axiosError.response?.data?.message ??
`${context} failed with status ${status}`
}
}
const axiosError = err as AxiosError<{ message: string }>
const status = axiosError.response?.status
if (status && routeSpecificErrors?.[status]) {
return routeSpecificErrors[status]
}
return (
axiosError.response?.data?.message ??
`${context} failed with status ${status}`
)
error.value = message
}
const { isLoading, error, executeRequest } = useApiRequest({
client: customerApiClient,
mapError
})
const executeRequest = async <T>(
requestCall: () => Promise<AxiosResponse<T>>,
options: {
errorContext: string
routeSpecificErrors?: Record<number, string>
}
): Promise<T | null> => {
const { errorContext, routeSpecificErrors } = options
isLoading.value = true
error.value = null
try {
const response = await requestCall()
return response.data
} catch (err) {
handleRequestError(err, errorContext, routeSpecificErrors)
return null
} finally {
isLoading.value = false
}
}
function formatEventType(eventType: string) {
switch (eventType) {
@@ -172,8 +198,8 @@ export const useCustomerEventsService = () => {
}
const result = await executeRequest<CustomerEventsResponse>(
(client) =>
client.get('/customers/events', {
() =>
customerApiClient.get('/customers/events', {
params: { page, limit },
headers: authHeaders
}),

View File

@@ -0,0 +1,26 @@
import { createTestingPinia } from '@pinia/testing'
import { setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useActionBarButtonStore } from '@/stores/actionBarButtonStore'
import { useExtensionStore } from '@/stores/extensionStore'
describe('actionBarButtonStore', () => {
beforeEach(() => {
setActivePinia(createTestingPinia({ stubActions: false }))
})
it('collects action bar buttons from registered extensions', () => {
const extensionStore = useExtensionStore()
const onClick = vi.fn()
extensionStore.registerExtension({
name: 'buttons',
actionBarButtons: [{ icon: 'icon-[lucide--plus]', onClick }]
})
extensionStore.registerExtension({ name: 'plain' })
const store = useActionBarButtonStore()
expect(store.buttons).toEqual([{ icon: 'icon-[lucide--plus]', onClick }])
})
})

View File

@@ -1,7 +1,7 @@
import { createTestingPinia } from '@pinia/testing'
import { fromAny, fromPartial } from '@total-typescript/shoehorn'
import { fromPartial } from '@total-typescript/shoehorn'
import { setActivePinia } from 'pinia'
import { nextTick } from 'vue'
import { nextTick, reactive } from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
@@ -23,11 +23,15 @@ import type {
LinearInput,
LoadedComfyWorkflow
} from '@/platform/workflow/management/stores/comfyWorkflow'
import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema'
import { ComfyWorkflow as ComfyWorkflowClass } from '@/platform/workflow/management/stores/comfyWorkflow'
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
import { app } from '@/scripts/app'
import { ChangeTracker } from '@/scripts/changeTracker'
import { createMockChangeTracker } from '@/utils/__tests__/litegraphTestUtils'
import {
createMockChangeTracker,
createMockLGraphNode
} from '@/utils/__tests__/litegraphTestUtils'
import type { WidgetId } from '@/types/widgetId'
const mockEmptyWorkflowDialog = vi.hoisted(() => {
@@ -56,9 +60,13 @@ vi.mock('@/utils/litegraphUtil', async (importOriginal) => ({
resolveNode: mockResolveNode
}))
const mockCanvas = vi.hoisted(() => ({
state: undefined as { readOnly: boolean } | undefined
}))
vi.mock('@/renderer/core/canvas/canvasStore', () => ({
useCanvasStore: () => ({
getCanvas: () => ({ read_only: false })
getCanvas: () => ({ state: mockCanvas.state })
})
}))
@@ -104,7 +112,7 @@ function createBuilderWorkflow(
function createBuilderWorkflowWithOutputs(
activeMode: string
): LoadedComfyWorkflow {
mockResolveNode.mockReturnValue(fromAny({ id: 1 }))
mockResolveNode.mockReturnValue(createMockLGraphNode({ id: 1 }))
const workflow = createBuilderWorkflow(activeMode)
workflow.changeTracker!.activeState!.extra ??= {}
workflow.changeTracker.activeState.extra.linearData = {
@@ -120,20 +128,12 @@ function createWorkflowWithLinearData(
outputs: SerializedNodeId[]
): LoadedComfyWorkflow {
const workflow = createBuilderWorkflow(activeMode)
workflow.changeTracker = createMockChangeTracker(
fromPartial<Partial<ChangeTracker>>({
activeState: {
last_node_id: 0,
last_link_id: 0,
nodes: [],
links: [],
groups: [],
config: {},
version: 0.4,
extra: { linearData: fromAny({ inputs, outputs }) }
}
})
)
const ct = createMockChangeTracker()
ct.activeState = {
...ct.activeState,
extra: { linearData: { inputs, outputs } }
} as ComfyWorkflowJSON
workflow.changeTracker = ct
return workflow
}
@@ -143,7 +143,7 @@ const entitySeed = `${rootGraphId}:1:seed` as WidgetId
const entitySteps = `${rootGraphId}:1:steps` as WidgetId
function nodeWithWidgets(id: number, widgetNames: string[]) {
return fromAny<LGraphNode, unknown>({
return createMockLGraphNode({
id,
widgets: widgetNames.map((name) => ({
name,
@@ -162,6 +162,7 @@ describe('appModeStore', () => {
ChangeTracker.isLoadingGraph = false
mockResolveNode.mockReturnValue(undefined)
mockSettings.reset()
mockCanvas.state = undefined
vi.mocked(app.rootGraph).nodes = [{ id: toNodeId(1) } as LGraphNode]
workflowStore = useWorkflowStore()
store = useAppModeStore()
@@ -365,6 +366,88 @@ describe('appModeStore', () => {
expect(store.selectedInputs).toEqual([[entityPrompt, 'prompt']])
})
it('keeps canonical entity ids when the node still exists', () => {
const node1 = nodeWithWidgets(1, [])
vi.mocked(app.rootGraph).nodes = [node1]
vi.mocked(app.rootGraph).getNodeById = vi.fn((id) =>
id === toNodeId(1) ? node1 : null
)
store.loadSelections({
inputs: [[entityPrompt, 'prompt']]
})
expect(store.selectedInputs).toEqual([[entityPrompt, 'prompt']])
})
it('drops canonical entity ids when their node is gone', () => {
vi.mocked(app.rootGraph).nodes = []
vi.mocked(app.rootGraph).getNodeById = vi.fn(() => null)
store.loadSelections({
inputs: [[entityPrompt, 'prompt']]
})
expect(store.selectedInputs).toEqual([])
})
it('drops locator inputs when the widget does not resolve', () => {
const hostLocator = `${rootGraphId}:5`
const hostNode = createMockLGraphNode({
id: 5,
isSubgraphNode: () => false,
widgets: [{ name: 'other' }]
})
vi.mocked(app.rootGraph).nodes = [hostNode]
vi.mocked(app.rootGraph).getNodeById = vi.fn((id) =>
id === toNodeId(5) ? hostNode : null
)
store.loadSelections({
inputs: [[hostLocator, 'prompt']]
})
expect(store.selectedInputs).toEqual([])
})
it('drops malformed legacy input ids', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.mocked(app.rootGraph).nodes = []
store.loadSelections({
inputs: [
[
fromPartial<SerializedNodeId | null>(null) as SerializedNodeId,
'prompt'
]
]
})
expect(store.selectedInputs).toEqual([])
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('legacy selectedInput tuple'),
expect.objectContaining({ storedId: null, widgetName: 'prompt' })
)
warnSpy.mockRestore()
})
it('drops direct node inputs when the widget is missing', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const node1 = nodeWithWidgets(1, [])
vi.mocked(app.rootGraph).nodes = [node1]
vi.mocked(app.rootGraph).getNodeById = vi.fn((id) =>
id === toNodeId(1) ? node1 : null
)
store.loadSelections({
inputs: [[1, 'prompt']]
})
expect(store.selectedInputs).toEqual([])
expect(warnSpy).toHaveBeenCalled()
warnSpy.mockRestore()
})
it('drops legacy entries whose widget no longer exists', () => {
const node1 = nodeWithWidgets(1, ['prompt'])
vi.mocked(app.rootGraph).nodes = [node1]
@@ -391,7 +474,7 @@ describe('appModeStore', () => {
it('removes outputs referencing deleted nodes on load', () => {
const node1 = { id: 1 }
mockResolveNode.mockImplementation((id) =>
id == 1 ? fromAny<LGraphNode, unknown>(node1) : undefined
id == 1 ? createMockLGraphNode(node1) : undefined
)
store.loadSelections({ outputs: [toNodeId(1), toNodeId(99)] })
@@ -399,6 +482,32 @@ describe('appModeStore', () => {
expect(store.selectedOutputs).toEqual([toNodeId(1)])
})
it('drops malformed output ids on load', () => {
store.loadSelections({
outputs: ['']
})
expect(store.selectedOutputs).toEqual([])
})
it('drops legacy subgraph input slots without widget ids', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const hostNode = Object.assign(Object.create(SubgraphNode.prototype), {
id: 5,
inputs: [{ name: 'Prompt' }]
})
vi.mocked(app.rootGraph).nodes = [hostNode]
vi.mocked(app.rootGraph).getNodeById = vi.fn(() => null)
store.loadSelections({
inputs: [[1, 'prompt']]
})
expect(store.selectedInputs).toEqual([])
expect(warnSpy).toHaveBeenCalled()
warnSpy.mockRestore()
})
it('reloads selections on configured event', async () => {
const node1 = nodeWithWidgets(1, ['seed'])
@@ -481,7 +590,7 @@ describe('appModeStore', () => {
expect(
store.pruneLinearData({
inputs: [[1, 'seed']],
outputs: [toNodeId(1)]
outputs: [toNodeId(1), '']
})
).toEqual({
inputs: [[1, 'seed']],
@@ -559,7 +668,7 @@ describe('appModeStore', () => {
setupNodeWithSeedAndSteps()
const workflow = createBuilderWorkflow('app')
workflow.changeTracker.activeState.extra = {}
workflow.changeTracker.initialState = fromAny({
workflow.changeTracker.initialState = fromPartial<ComfyWorkflowJSON>({
...workflow.changeTracker.activeState,
extra: {
linearData: { inputs: [[1, 'seed']], outputs: [toNodeId(1)] }
@@ -579,7 +688,7 @@ describe('appModeStore', () => {
workflow.changeTracker.activeState.extra = {
linearData: { inputs: [[1, 'steps']], outputs: [toNodeId(1)] }
}
workflow.changeTracker.initialState = fromAny({
workflow.changeTracker.initialState = fromPartial<ComfyWorkflowJSON>({
...workflow.changeTracker.activeState,
extra: {
linearData: { inputs: [[1, 'seed']], outputs: [toNodeId(1)] }
@@ -641,6 +750,17 @@ describe('appModeStore', () => {
expect(originalRootGraph.extra.linearData).toEqual(dataBefore)
})
it('does not write while graph loading is in progress', async () => {
workflowStore.activeWorkflow = createBuilderWorkflow()
ChangeTracker.isLoadingGraph = true
await nextTick()
store.selectedOutputs.push(toNodeId(1))
await nextTick()
expect(app.rootGraph.extra.linearData).toBeUndefined()
})
it('calls captureCanvasState when input is selected', async () => {
const workflow = createBuilderWorkflow()
workflowStore.activeWorkflow = workflow
@@ -683,8 +803,8 @@ describe('appModeStore', () => {
describe('updateInputConfig', () => {
const entity = 'g:1:prompt' as WidgetId
const otherEntity = 'g:99:prompt' as WidgetId
const widget = fromAny<IBaseWidget, unknown>({ widgetId: entity })
const otherWidget = fromAny<IBaseWidget, unknown>({ widgetId: otherEntity })
const widget = fromPartial<IBaseWidget>({ widgetId: entity })
const otherWidget = fromPartial<IBaseWidget>({ widgetId: otherEntity })
it('sets config on an existing input', () => {
store.selectedInputs.push([entity, 'prompt'])
@@ -706,7 +826,7 @@ describe('appModeStore', () => {
store.selectedInputs.push([entity, 'prompt'])
store.updateInputConfig(
fromAny<IBaseWidget, unknown>({ widgetId: undefined }),
fromPartial<IBaseWidget>({ widgetId: undefined }),
{ height: 200 }
)
@@ -744,7 +864,7 @@ describe('appModeStore', () => {
it('removes the matching input entry only', () => {
const promptEntity = 'g:1:prompt' as WidgetId
const stepsEntity = 'g:2:steps' as WidgetId
const stepsWidget = fromAny<IBaseWidget, unknown>({
const stepsWidget = fromPartial<IBaseWidget>({
widgetId: stepsEntity,
name: 'steps'
})
@@ -755,6 +875,24 @@ describe('appModeStore', () => {
expect(store.selectedInputs).toEqual([[promptEntity, 'prompt']])
})
it('ignores widgets without ids', () => {
store.selectedInputs.push(['g:1:prompt' as WidgetId, 'prompt'])
store.removeSelectedInput(fromPartial<IBaseWidget>({}))
expect(store.selectedInputs).toEqual([['g:1:prompt', 'prompt']])
})
it('ignores missing input ids', () => {
store.selectedInputs.push(['g:1:prompt' as WidgetId, 'prompt'])
store.removeSelectedInput(
fromPartial<IBaseWidget>({ widgetId: 'g:2:prompt' })
)
expect(store.selectedInputs).toEqual([['g:1:prompt', 'prompt']])
})
})
describe('autoEnableVueNodes', () => {
@@ -819,6 +957,47 @@ describe('appModeStore', () => {
expect.anything()
)
})
it('does not enable Vue nodes after leaving select mode', async () => {
mockSettings.store['Comfy.VueNodes.Enabled'] = false
workflowStore.activeWorkflow = createBuilderWorkflow('graph')
store.enterBuilder()
await nextTick()
mockSettings.set.mockClear()
store.exitBuilder()
await nextTick()
expect(mockSettings.set).not.toHaveBeenCalled()
})
})
describe('read only canvas sync', () => {
it('keeps canvas read-only while in select mode', async () => {
mockCanvas.state = reactive({ readOnly: false })
workflowStore.activeWorkflow = createBuilderWorkflow('graph')
store.enterBuilder()
await nextTick()
mockCanvas.state.readOnly = false
await nextTick()
expect(mockCanvas.state.readOnly).toBe(true)
})
it('stops enforcing read-only after leaving select mode', async () => {
mockCanvas.state = reactive({ readOnly: false })
workflowStore.activeWorkflow = createBuilderWorkflow('graph')
store.enterBuilder()
await nextTick()
store.exitBuilder()
await nextTick()
mockCanvas.state.readOnly = false
await nextTick()
expect(mockCanvas.state.readOnly).toBe(false)
})
})
describe('legacy selectedInput tuple migration', () => {
@@ -873,7 +1052,7 @@ describe('appModeStore', () => {
const sourceWidgetName = 'text'
const rootEntityId =
`${rootGraphId}:${sourceNodeId}:${sourceWidgetName}` as WidgetId
const rootNode = fromAny<LGraphNode, unknown>({
const rootNode = createMockLGraphNode({
id: sourceNodeId,
widgets: [{ name: sourceWidgetName, widgetId: rootEntityId }]
})
@@ -907,6 +1086,121 @@ describe('appModeStore', () => {
])
})
it('drops direct root-node widgets that cannot produce an entity id', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const sourceNodeId = 42
const sourceWidgetName = 'text'
const rootNode = createMockLGraphNode({
id: sourceNodeId,
widgets: [{ name: sourceWidgetName }]
})
vi.mocked(app.rootGraph).id = rootGraphId
vi.mocked(app.rootGraph).nodes = [rootNode]
vi.mocked(app.rootGraph).getNodeById = vi.fn(
(id: SerializedNodeId | null | undefined) =>
id == sourceNodeId ? rootNode : null
)
const result = store.pruneLinearData({
inputs: [[sourceNodeId, sourceWidgetName, { height: 120 }]],
outputs: []
})
expect(result.inputs).toEqual([])
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('legacy selectedInput tuple'),
expect.objectContaining({
storedId: sourceNodeId,
widgetName: sourceWidgetName
})
)
warnSpy.mockRestore()
})
it('drops promoted inputs whose source target no longer matches', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const subgraphInputName = 'Prompt'
const sourceWidgetName = 'text'
const subgraph = createTestSubgraph({
inputs: [{ name: subgraphInputName, type: 'STRING' }]
})
const interior = new LGraphNodeClass('Interior')
const interiorInput = interior.addInput(subgraphInputName, 'STRING')
interior.addWidget('string', sourceWidgetName, '', () => undefined)
interiorInput.widget = { name: sourceWidgetName }
subgraph.add(interior)
subgraph.inputNode.slots[0].connect(interiorInput, interior)
const host = createTestSubgraphNode(subgraph, { id: 5 })
const rootGraph = host.graph as LGraph
rootGraph.add(host)
host._internalConfigureAfterSlots()
vi.mocked(app.rootGraph).id = rootGraph.id
vi.mocked(app.rootGraph).nodes = rootGraph.nodes
vi.mocked(app.rootGraph).getNodeById = vi.fn((id) =>
rootGraph.getNodeById(id)
)
const result = store.pruneLinearData({
inputs: [[interior.id, 'other-widget', { height: 120 }]],
outputs: []
})
expect(result.inputs).toEqual([])
expect(warnSpy).toHaveBeenCalled()
warnSpy.mockRestore()
})
it('drops legacy inputs when multiple promoted inputs match', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const subgraphInputName = 'Prompt'
const sourceWidgetName = 'text'
const subgraph = createTestSubgraph({
inputs: [{ name: subgraphInputName, type: 'STRING' }]
})
const interior = new LGraphNodeClass('Interior')
const interiorInput = interior.addInput(subgraphInputName, 'STRING')
interior.addWidget('string', sourceWidgetName, '', () => undefined)
interiorInput.widget = { name: sourceWidgetName }
subgraph.add(interior)
subgraph.inputNode.slots[0].connect(interiorInput, interior)
const firstHost = createTestSubgraphNode(subgraph, { id: 5 })
const rootGraph = firstHost.graph as LGraph
const secondHost = createTestSubgraphNode(subgraph, {
id: 6,
parentGraph: rootGraph
})
rootGraph.add(firstHost)
rootGraph.add(secondHost)
firstHost._internalConfigureAfterSlots()
secondHost._internalConfigureAfterSlots()
vi.mocked(app.rootGraph).id = rootGraph.id
vi.mocked(app.rootGraph).nodes = rootGraph.nodes
vi.mocked(app.rootGraph).getNodeById = vi.fn((id) =>
rootGraph.getNodeById(id)
)
const result = store.pruneLinearData({
inputs: [[interior.id, sourceWidgetName, { height: 120 }]],
outputs: []
})
expect(result.inputs).toEqual([])
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('ambiguous legacy selectedInput tuple'),
expect.objectContaining({
storedId: interior.id,
widgetName: sourceWidgetName
})
)
warnSpy.mockRestore()
})
it('warns and drops a tuple whose target widget no longer resolves', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.mocked(app.rootGraph).id = rootGraphId
@@ -936,7 +1230,7 @@ describe('appModeStore', () => {
const hostLocator = `${rootGraphId}:${hostId}`
const promotedEntityId =
`${rootGraphId}:${hostId}:subgraph_input_name` as WidgetId
const hostNode = fromAny<LGraphNode, unknown>({
const hostNode = createMockLGraphNode({
id: hostId,
isSubgraphNode: () => true,
widgets: [{ name: 'subgraph_input_name', widgetId: promotedEntityId }]

View File

@@ -1,3 +1,4 @@
import { fromPartial } from '@total-typescript/shoehorn'
import { FirebaseError } from 'firebase/app'
import type { User, UserCredential } from 'firebase/auth'
import * as firebaseAuth from 'firebase/auth'
@@ -37,6 +38,14 @@ type MockUser = Omit<User, 'getIdToken' | 'delete'> & {
type MockAuth = Record<string, unknown>
/**
* Centralizes the type-boundary double-cast for Firebase mock credentials
* so individual tests only deal with the mock user.
*/
function asUserCredential(user: Partial<MockUser>): UserCredential {
return fromPartial<UserCredential>({ user })
}
// Mock fetch
const mockFetch = vi.fn()
vi.stubGlobal('fetch', mockFetch)
@@ -65,19 +74,12 @@ const mockAccessBillingPortalResponse = {
Promise.resolve({ billing_portal_url: 'https://billing.stripe.com/test' })
}
vi.mock('vuefire', () => ({
useFirebaseAuth: vi.fn()
vi.mock('@/i18n', () => ({
t: (key: string) => key
}))
vi.mock('vue-i18n', () => ({
useI18n: () => ({
t: (key: string) => key
}),
createI18n: () => ({
global: {
t: (key: string) => key
}
})
vi.mock('vuefire', () => ({
useFirebaseAuth: vi.fn()
}))
vi.mock('firebase/auth', async (importOriginal) => {
@@ -90,6 +92,7 @@ vi.mock('firebase/auth', async (importOriginal) => {
onAuthStateChanged: vi.fn(),
onIdTokenChanged: vi.fn(),
signInWithPopup: vi.fn(),
sendPasswordResetEmail: vi.fn(),
GoogleAuthProvider: class {
addScope = vi.fn()
setCustomParameters = vi.fn()
@@ -99,7 +102,8 @@ vi.mock('firebase/auth', async (importOriginal) => {
setCustomParameters = vi.fn()
},
getAdditionalUserInfo: vi.fn(),
setPersistence: vi.fn().mockResolvedValue(undefined)
setPersistence: vi.fn().mockResolvedValue(undefined),
updatePassword: vi.fn()
}
})
@@ -127,6 +131,18 @@ vi.mock('@/composables/useFeatureFlags', () => ({
})
}))
const mockWorkspaceAuthStore = vi.hoisted(() => ({
unifiedToken: null as string | null,
clearWorkspaceContext: vi.fn(),
mintAtLogin: vi.fn(),
getWorkspaceAuthHeader: vi.fn(),
getWorkspaceToken: vi.fn()
}))
vi.mock('@/platform/workspace/stores/workspaceAuthStore', () => ({
useWorkspaceAuthStore: () => mockWorkspaceAuthStore
}))
// Mock apiKeyAuthStore
const mockApiKeyGetAuthHeader = vi.fn().mockReturnValue(null)
vi.mock('@/stores/apiKeyAuthStore', () => ({
@@ -149,12 +165,12 @@ describe('useAuthStore', () => {
/* mock Auth object */
}
const mockUser: MockUser = {
const mockUser: MockUser = fromPartial<MockUser>({
uid: 'test-user-id',
email: 'test@example.com',
getIdToken: vi.fn().mockResolvedValue('mock-id-token'),
delete: vi.fn().mockResolvedValue(undefined)
} as Partial<User> as MockUser
})
beforeEach(() => {
vi.resetAllMocks()
@@ -163,6 +179,9 @@ describe('useAuthStore', () => {
mockFeatureFlags.teamWorkspacesEnabled = false
mockFeatureFlags.unifiedCloudAuthEnabled = false
mockWorkspaceAuthStore.unifiedToken = null
mockWorkspaceAuthStore.getWorkspaceAuthHeader.mockReturnValue(null)
mockWorkspaceAuthStore.getWorkspaceToken.mockReturnValue(undefined)
// Setup dialog service mock
vi.mocked(useDialogService, { partial: true }).mockReturnValue({
@@ -171,9 +190,7 @@ describe('useAuthStore', () => {
// Mock useFirebaseAuth to return our mock auth object
vi.mocked(vuefire.useFirebaseAuth).mockReturnValue(
mockAuth as Partial<
ReturnType<typeof vuefire.useFirebaseAuth>
> as ReturnType<typeof vuefire.useFirebaseAuth>
fromPartial<ReturnType<typeof vuefire.useFirebaseAuth>>(mockAuth)
)
// Mock onAuthStateChanged to capture the callback and simulate initial auth state
@@ -228,9 +245,7 @@ describe('useAuthStore', () => {
)
vi.mocked(vuefire.useFirebaseAuth).mockReturnValue(
mockAuth as Partial<
ReturnType<typeof vuefire.useFirebaseAuth>
> as ReturnType<typeof vuefire.useFirebaseAuth>
fromPartial<ReturnType<typeof vuefire.useFirebaseAuth>>(mockAuth)
)
setActivePinia(createTestingPinia({ stubActions: false }))
@@ -250,14 +265,14 @@ describe('useAuthStore', () => {
})
it('should not increment when ID token event is for a different user UID', () => {
const otherUser = { uid: 'other-user-id' } as Partial<User> as User
const otherUser = fromPartial<User>({ uid: 'other-user-id' })
idTokenCallback?.(mockUser)
idTokenCallback?.(otherUser)
expect(store.tokenRefreshTrigger).toBe(0)
})
it('should increment after switching to a new UID and receiving a second event for that UID', () => {
const otherUser = { uid: 'other-user-id' } as Partial<User> as User
const otherUser = fromPartial<User>({ uid: 'other-user-id' })
idTokenCallback?.(mockUser)
idTokenCallback?.(otherUser)
idTokenCallback?.(otherUser)
@@ -275,6 +290,11 @@ describe('useAuthStore', () => {
store.notifyTokenRefreshed()
expect(store.tokenRefreshTrigger).toBe(1)
})
it('ignores null ID token events', () => {
idTokenCallback?.(null)
expect(store.tokenRefreshTrigger).toBe(0)
})
})
it('should initialize with the current user', () => {
@@ -292,6 +312,27 @@ describe('useAuthStore', () => {
)
})
it('mints workspace auth on cloud login and clears it on logout state', () => {
expect(mockWorkspaceAuthStore.mintAtLogin).toHaveBeenCalledOnce()
authStateCallback(null)
expect(mockWorkspaceAuthStore.clearWorkspaceContext).toHaveBeenCalledOnce()
})
it('does not mint workspace auth outside cloud', () => {
mockWorkspaceAuthStore.mintAtLogin.mockClear()
mockDistributionTypes.isCloud = false
try {
authStateCallback(mockUser)
expect(mockWorkspaceAuthStore.mintAtLogin).not.toHaveBeenCalled()
} finally {
mockDistributionTypes.isCloud = true
}
})
it('should properly clean up error state between operations', async () => {
// First, cause an error
const mockError = new Error('Invalid password')
@@ -306,18 +347,18 @@ describe('useAuthStore', () => {
}
// Now, succeed on next attempt
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValueOnce({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValueOnce(
asUserCredential(mockUser)
)
await store.login('test@example.com', 'correct-password')
})
describe('login', () => {
it('should login with valid credentials', async () => {
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
const result = await store.login('test@example.com', 'password')
@@ -349,11 +390,35 @@ describe('useAuthStore', () => {
expect(store.loading).toBe(false)
})
it('tracks login when Firebase returns no email', async () => {
const userWithoutEmail = { ...mockUser, email: null }
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue(
asUserCredential(userWithoutEmail)
)
await store.login('test@example.com', 'password')
expect(mockTrackAuth).toHaveBeenCalledWith(
expect.objectContaining({ email: undefined })
)
})
it('fails customer creation when the signed-in user has no token yet', async () => {
authStateCallback(null)
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue(
asUserCredential(mockUser)
)
await expect(store.login('test@example.com', 'password')).rejects.toThrow(
'Cannot create customer: User not authenticated'
)
})
it('should handle concurrent login attempts correctly', async () => {
// Set up multiple login promises
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
const loginPromise1 = store.login('user1@example.com', 'password1')
@@ -369,9 +434,9 @@ describe('useAuthStore', () => {
describe('register', () => {
it('should register a new user', async () => {
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
const result = await store.register('new@example.com', 'password')
@@ -404,9 +469,9 @@ describe('useAuthStore', () => {
})
it('forwards the turnstile token to createCustomer as turnstile_token', async () => {
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue(
asUserCredential(mockUser)
)
await store.register('new@example.com', 'password', 'turnstile-abc')
@@ -420,9 +485,9 @@ describe('useAuthStore', () => {
})
it('omits the request body when no turnstile token is provided', async () => {
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue(
asUserCredential(mockUser)
)
await store.register('new@example.com', 'password')
@@ -433,9 +498,9 @@ describe('useAuthStore', () => {
})
it('rolls back the orphaned Firebase user when customer creation fails', async () => {
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue(
asUserCredential(mockUser)
)
// The server-side customer creation (where Turnstile is validated) fails.
mockFetch.mockImplementation((url: string) =>
url.endsWith('/customers')
@@ -456,9 +521,9 @@ describe('useAuthStore', () => {
})
it('does not delete the user on a successful registration', async () => {
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue(
asUserCredential(mockUser)
)
await store.register('new@example.com', 'password')
@@ -468,9 +533,9 @@ describe('useAuthStore', () => {
it('does not delete an existing user when customer creation fails during login', async () => {
// Regression guard: the rollback must be scoped to register only — login
// signs in an EXISTING user, so a customer hiccup must never delete it.
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue(
asUserCredential(mockUser)
)
mockFetch.mockImplementation((url: string) =>
url.endsWith('/customers')
? Promise.resolve({
@@ -486,6 +551,19 @@ describe('useAuthStore', () => {
).rejects.toThrow()
expect(mockUser.delete).not.toHaveBeenCalled()
})
it('tracks registration when Firebase returns no email', async () => {
const userWithoutEmail = { ...mockUser, email: null }
vi.mocked(firebaseAuth.createUserWithEmailAndPassword).mockResolvedValue(
asUserCredential(userWithoutEmail)
)
await store.register('new@example.com', 'password')
expect(mockTrackAuth).toHaveBeenCalledWith(
expect.objectContaining({ email: undefined })
)
})
})
describe('logout', () => {
@@ -530,9 +608,9 @@ describe('useAuthStore', () => {
it('should return null for token after login and logout sequence', async () => {
// Setup mock for login
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.signInWithEmailAndPassword).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
// Login
@@ -619,14 +697,62 @@ describe('useAuthStore', () => {
const authHeader = await store.getAuthHeader()
expect(authHeader).toBeNull() // Should fallback gracefully
})
it('uses the unified cloud token when enabled', async () => {
mockFeatureFlags.unifiedCloudAuthEnabled = true
mockWorkspaceAuthStore.unifiedToken = 'unified-token'
await expect(store.getAuthHeader()).resolves.toEqual({
Authorization: 'Bearer unified-token'
})
await expect(store.getAuthToken()).resolves.toBe('unified-token')
})
it('returns no unified auth when the unified token is missing', async () => {
mockFeatureFlags.unifiedCloudAuthEnabled = true
mockWorkspaceAuthStore.unifiedToken = null
await expect(store.getAuthHeader()).resolves.toBeNull()
await expect(store.getAuthToken()).resolves.toBeUndefined()
})
it('prefers workspace auth when team workspaces are enabled', async () => {
mockFeatureFlags.teamWorkspacesEnabled = true
mockWorkspaceAuthStore.getWorkspaceAuthHeader.mockReturnValue({
Authorization: 'Bearer workspace-header'
})
mockWorkspaceAuthStore.getWorkspaceToken.mockReturnValue(
'workspace-token'
)
await expect(store.getAuthHeader()).resolves.toEqual({
Authorization: 'Bearer workspace-header'
})
await expect(store.getAuthToken()).resolves.toBe('workspace-token')
})
it('falls back to Firebase when workspace auth is unavailable', async () => {
mockFeatureFlags.teamWorkspacesEnabled = true
mockWorkspaceAuthStore.getWorkspaceAuthHeader.mockReturnValue(null)
mockWorkspaceAuthStore.getWorkspaceToken.mockReturnValue(undefined)
await expect(store.getAuthHeader()).resolves.toEqual({
Authorization: 'Bearer mock-id-token'
})
await expect(store.getAuthToken()).resolves.toBe('mock-id-token')
})
it('returns the Firebase token by default', async () => {
await expect(store.getAuthToken()).resolves.toBe('mock-id-token')
})
})
describe('social authentication', () => {
describe('loginWithGoogle', () => {
it('should sign in with Google', async () => {
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
const result = await store.loginWithGoogle()
@@ -640,9 +766,9 @@ describe('useAuthStore', () => {
})
it('never sends a turnstile_token on the customer request (OAuth is exempt)', async () => {
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
asUserCredential(mockUser)
)
await store.loginWithGoogle()
@@ -671,9 +797,9 @@ describe('useAuthStore', () => {
describe('loginWithGithub', () => {
it('should sign in with Github', async () => {
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
const result = await store.loginWithGithub()
@@ -687,9 +813,9 @@ describe('useAuthStore', () => {
})
it('never sends a turnstile_token on the customer request (OAuth is exempt)', async () => {
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue({
user: mockUser
} as Partial<UserCredential> as UserCredential)
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
asUserCredential(mockUser)
)
await store.loginWithGithub()
@@ -717,9 +843,9 @@ describe('useAuthStore', () => {
})
it('should handle concurrent social login attempts correctly', async () => {
const mockUserCredential = { user: mockUser }
const mockUserCredential = asUserCredential(mockUser)
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
mockUserCredential as Partial<UserCredential> as UserCredential
mockUserCredential
)
const googleLoginPromise = store.loginWithGoogle()
@@ -731,9 +857,7 @@ describe('useAuthStore', () => {
})
describe('sign-up telemetry OR logic', () => {
const mockUserCredential = {
user: mockUser
} as Partial<UserCredential> as UserCredential
const mockUserCredential = asUserCredential(mockUser)
beforeEach(() => {
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
@@ -804,6 +928,22 @@ describe('useAuthStore', () => {
)
}
)
it.for(['loginWithGoogle', 'loginWithGithub'] as const)(
'%s should track undefined email when Firebase returns no email',
async (method) => {
const userWithoutEmail = { ...mockUser, email: null }
vi.mocked(firebaseAuth.signInWithPopup).mockResolvedValue(
asUserCredential(userWithoutEmail)
)
await store[method]()
expect(mockTrackAuth).toHaveBeenCalledWith(
expect.objectContaining({ email: undefined })
)
}
)
})
})
@@ -975,6 +1115,61 @@ describe('useAuthStore', () => {
await expect(store.accessBillingPortal()).rejects.toThrow()
})
it('throws when no auth method is available', async () => {
authStateCallback(null)
mockApiKeyGetAuthHeader.mockReturnValue(null)
await expect(store.accessBillingPortal()).rejects.toMatchObject({
name: 'AuthStoreError',
message: 'toastMessages.userNotAuthenticated'
})
})
})
describe('fetchBalance', () => {
it('stores the balance and update time when fetching succeeds', async () => {
await expect(store.fetchBalance()).resolves.toEqual({ balance: 0 })
expect(store.balance).toEqual({ balance: 0 })
expect(store.lastBalanceUpdateTime).toBeInstanceOf(Date)
expect(store.isFetchingBalance).toBe(false)
})
it('throws when no auth method is available', async () => {
authStateCallback(null)
mockApiKeyGetAuthHeader.mockReturnValue(null)
await expect(store.fetchBalance()).rejects.toMatchObject({
name: 'AuthStoreError',
message: 'toastMessages.userNotAuthenticated'
})
expect(store.isFetchingBalance).toBe(false)
})
it('returns null when the customer balance is missing', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404
})
await expect(store.fetchBalance()).resolves.toBeNull()
expect(store.balance).toBeNull()
expect(store.isFetchingBalance).toBe(false)
})
it('throws API errors when fetching balance fails', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 500,
json: () => Promise.resolve({ message: 'Balance unavailable' })
})
await expect(store.fetchBalance()).rejects.toThrow(
'toastMessages.failedToFetchBalance'
)
expect(store.isFetchingBalance).toBe(false)
})
})
describe('getAuthHeaderOrThrow', () => {
@@ -1062,5 +1257,117 @@ describe('useAuthStore', () => {
expect(error).toBeInstanceOf(AuthStoreError)
expect((error as AuthStoreError).status).toBe(422)
})
it('throws when the response has no customer id', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({})
})
await expect(store.createCustomer()).rejects.toThrow(
'toastMessages.failedToCreateCustomer'
)
})
})
describe('password actions', () => {
it('sends password reset emails', async () => {
vi.mocked(firebaseAuth.sendPasswordResetEmail).mockResolvedValue()
await store.sendPasswordReset('test@example.com')
expect(firebaseAuth.sendPasswordResetEmail).toHaveBeenCalledWith(
mockAuth,
'test@example.com'
)
})
it('updates the current user password', async () => {
vi.mocked(firebaseAuth.updatePassword).mockResolvedValue()
await store.updatePassword('new-password')
expect(firebaseAuth.updatePassword).toHaveBeenCalledWith(
mockUser,
'new-password'
)
})
it('throws when updating password without a user', async () => {
authStateCallback(null)
await expect(store.updatePassword('new-password')).rejects.toMatchObject({
name: 'AuthStoreError',
message: 'toastMessages.userNotAuthenticated'
})
})
})
describe('initiateCreditPurchase', () => {
it('creates the customer once before adding credits', async () => {
mockFetch.mockImplementation((url: string) => {
if (url.endsWith('/customers')) {
return Promise.resolve(mockCreateCustomerResponse)
}
if (url.endsWith('/customers/credit')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({ redirect_url: 'https://stripe.test' })
})
}
return Promise.reject(new Error('Unexpected API call'))
})
await store.initiateCreditPurchase({
amount_micros: 10_000_000,
currency: 'usd'
})
await store.initiateCreditPurchase({
amount_micros: 10_000_000,
currency: 'usd'
})
const customerCalls = mockFetch.mock.calls.filter(([url]) =>
String(url).endsWith('/customers')
)
expect(customerCalls).toHaveLength(1)
})
it('throws when credit purchase fails', async () => {
mockFetch.mockImplementation((url: string) => {
if (url.endsWith('/customers')) {
return Promise.resolve(mockCreateCustomerResponse)
}
if (url.endsWith('/customers/credit')) {
return Promise.resolve({
ok: false,
json: () => Promise.resolve({ message: 'Checkout unavailable' })
})
}
return Promise.reject(new Error('Unexpected API call'))
})
await expect(
store.initiateCreditPurchase({
amount_micros: 10_000_000,
currency: 'usd'
})
).rejects.toThrow('toastMessages.failedToInitiateCreditPurchase')
})
it('throws when no auth method is available', async () => {
authStateCallback(null)
mockApiKeyGetAuthHeader.mockReturnValue(null)
await expect(
store.initiateCreditPurchase({
amount_micros: 10_000_000,
currency: 'usd'
})
).rejects.toMatchObject({
name: 'AuthStoreError',
message: 'toastMessages.userNotAuthenticated'
})
})
})
})

View File

@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick, ref } from 'vue'
import { useSettingStore } from '@/platform/settings/settingStore'
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
import { useBootstrapStore } from './bootstrapStore'
@@ -21,25 +22,28 @@ vi.mock('@/i18n', () => ({
}))
const mockIsSettingsReady = ref(false)
const mockSettingStore = {
load: vi.fn(() => {
mockIsSettingsReady.value = true
}),
get isReady() {
return mockIsSettingsReady.value
},
isLoading: ref(false),
error: ref(undefined)
}
vi.mock('@/platform/settings/settingStore', () => ({
useSettingStore: vi.fn(() => ({
load: vi.fn(() => {
mockIsSettingsReady.value = true
}),
get isReady() {
return mockIsSettingsReady.value
},
isLoading: ref(false),
error: ref(undefined)
}))
useSettingStore: vi.fn(() => mockSettingStore)
}))
const mockWorkflowStore = {
loadWorkflows: vi.fn(),
syncWorkflows: vi.fn().mockResolvedValue(undefined)
}
vi.mock('@/platform/workflow/management/stores/workflowStore', () => ({
useWorkflowStore: vi.fn(() => ({
loadWorkflows: vi.fn(),
syncWorkflows: vi.fn().mockResolvedValue(undefined)
}))
useWorkflowStore: vi.fn(() => mockWorkflowStore)
}))
const mockNeedsLogin = ref(false)
@@ -93,6 +97,21 @@ describe('bootstrapStore', () => {
})
})
it('does not reload authenticated stores after bootstrap already ran', async () => {
const store = useBootstrapStore()
const settingStore = useSettingStore()
const workflowStore = useWorkflowStore()
await store.startStoreBootstrap()
await store.startStoreBootstrap()
await vi.waitFor(() => {
expect(store.isI18nReady).toBe(true)
})
expect(settingStore.load).toHaveBeenCalledOnce()
expect(workflowStore.loadWorkflows).toHaveBeenCalledOnce()
})
describe('cloud mode', () => {
beforeEach(() => {
mockDistributionTypes.isCloud = true

View File

@@ -4,6 +4,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useCommandStore } from '@/stores/commandStore'
const keybindingMock = vi.hoisted(() => ({
value: null as null | { combo: { getKeySequences: () => string[] } }
}))
vi.mock('@/composables/useErrorHandling', () => ({
useErrorHandling: () => ({
wrapWithErrorHandlingAsync:
@@ -21,12 +25,13 @@ vi.mock('@/composables/useErrorHandling', () => ({
vi.mock('@/platform/keybindings/keybindingStore', () => ({
useKeybindingStore: () => ({
getKeybindingByCommandId: () => null
getKeybindingByCommandId: () => keybindingMock.value
})
}))
describe('commandStore', () => {
beforeEach(() => {
keybindingMock.value = null
setActivePinia(createTestingPinia({ stubActions: false }))
})
@@ -164,6 +169,16 @@ describe('commandStore', () => {
expect(store.getCommand('tip.fn')?.tooltip).toBe('Dynamic tip')
})
it('resolves icon as function', () => {
const store = useCommandStore()
store.registerCommand({
id: 'icon.fn',
function: vi.fn(),
icon: () => 'pi pi-bolt'
})
expect(store.getCommand('icon.fn')?.icon).toBe('pi pi-bolt')
})
it('uses explicit menubarLabel over label', () => {
const store = useCommandStore()
store.registerCommand({
@@ -184,6 +199,16 @@ describe('commandStore', () => {
})
expect(store.getCommand('mbl.default')?.menubarLabel).toBe('My Label')
})
it('resolves menubarLabel as function', () => {
const store = useCommandStore()
store.registerCommand({
id: 'mbl.fn',
function: vi.fn(),
menubarLabel: () => 'Dynamic menu'
})
expect(store.getCommand('mbl.fn')?.menubarLabel).toBe('Dynamic menu')
})
})
describe('formatKeySequence', () => {
@@ -193,5 +218,17 @@ describe('commandStore', () => {
const cmd = store.getCommand('no.kb')!
expect(store.formatKeySequence(cmd)).toBe('')
})
it('formats keybinding sequences', () => {
const store = useCommandStore()
keybindingMock.value = {
combo: { getKeySequences: () => ['Control+A', 'Shift+B'] }
}
store.registerCommand({ id: 'with.kb', function: vi.fn() })
const cmd = store.getCommand('with.kb')!
expect(store.formatKeySequence(cmd)).toBe('Ctrl+A + Shift+B')
})
})
})

View File

@@ -1,6 +1,6 @@
import { createTestingPinia } from '@pinia/testing'
import { setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent } from 'vue'
import { useDialogStore } from '@/stores/dialogStore'
@@ -141,6 +141,114 @@ describe('dialogStore', () => {
})
describe('basic dialog operations', () => {
it('generates a key when none is provided', () => {
const store = useDialogStore()
const dialog = store.showDialog({ component: MockComponent })
expect(dialog.key).toMatch(/^dialog-/)
expect(store.isDialogOpen(dialog.key)).toBe(true)
})
it('evicts the first stack entry when the stack is full', () => {
const store = useDialogStore()
for (let i = 0; i < 11; i++) {
store.showDialog({
key: `dialog-${i}`,
component: MockComponent,
priority: i
})
}
expect(store.dialogStack).toHaveLength(10)
expect(store.isDialogOpen('dialog-9')).toBe(false)
})
it('stores optional header and footer components and props', () => {
const store = useDialogStore()
const dialog = store.showDialog({
key: 'with-slots',
component: MockComponent,
headerComponent: MockComponent,
footerComponent: MockComponent,
headerProps: { title: 'Header' },
footerProps: { action: 'Save' }
})
expect(dialog.headerComponent).toBeDefined()
expect(dialog.footerComponent).toBeDefined()
expect(dialog.headerProps).toEqual({ title: 'Header' })
expect(dialog.footerProps).toEqual({ action: 'Save' })
})
it('runs dialog lifecycle handlers', () => {
const store = useDialogStore()
const onClose = vi.fn()
const dialog = store.showDialog({
key: 'lifecycle',
component: MockComponent,
dialogComponentProps: { onClose }
})
// A second dialog steals focus so the mousedown below actually
// exercises riseDialog's promote-to-front behavior.
store.showDialog({ key: 'other', component: MockComponent })
const props =
dialog.dialogComponentProps as typeof dialog.dialogComponentProps & {
onAfterHide: () => void
onMaximize: () => void
onUnmaximize: () => void
pt: { root: { onMousedown: () => void } }
}
props.onMaximize()
expect(dialog.dialogComponentProps.maximized).toBe(true)
props.onUnmaximize()
expect(dialog.dialogComponentProps.maximized).toBe(false)
expect(store.activeKey).toBe('other')
props.pt.root.onMousedown()
expect(store.activeKey).toBe('lifecycle')
props.onAfterHide()
expect(onClose).toHaveBeenCalledOnce()
expect(store.isDialogOpen('lifecycle')).toBe(false)
})
it('does nothing when rising or closing a missing dialog', () => {
const store = useDialogStore()
store.riseDialog({ key: 'missing' })
store.closeDialog({ key: 'missing' })
expect(store.dialogStack).toEqual([])
expect(store.activeKey).toBeNull()
})
it('closes the active dialog when no key is provided', () => {
const store = useDialogStore()
store.showDialog({ key: 'active', component: MockComponent })
store.closeDialog()
expect(store.isDialogOpen('active')).toBe(false)
expect(store.activeKey).toBeNull()
})
it('disables escape closing for a non-closable active dialog', () => {
const store = useDialogStore()
const dialog = store.showDialog({
key: 'locked',
component: MockComponent,
dialogComponentProps: { closable: false }
})
expect(dialog.dialogComponentProps.closeOnEscape).toBe(false)
})
it('should show and close dialogs', () => {
const store = useDialogStore()
@@ -208,6 +316,86 @@ describe('dialogStore', () => {
false
)
})
it('updates only content props when dialog component props are omitted', () => {
const store = useDialogStore()
store.showDialog({
key: 'content-only',
component: MockContentPropsComponent,
props: { openingAction: null }
})
expect(
store.updateDialog({
key: 'content-only',
contentProps: { openingAction: 'open' }
})
).toBe(true)
expect(store.dialogStack[0].contentProps.openingAction).toBe('open')
})
it('updates only dialog component props when content props are omitted', () => {
const store = useDialogStore()
store.showDialog({
key: 'dialog-props-only',
component: MockContentPropsComponent,
dialogComponentProps: { dismissableMask: true }
})
expect(
store.updateDialog({
key: 'dialog-props-only',
dialogComponentProps: { dismissableMask: false }
})
).toBe(true)
expect(store.dialogStack[0].dialogComponentProps.dismissableMask).toBe(
false
)
})
it('returns false when updating a missing dialog', () => {
const store = useDialogStore()
expect(
store.updateDialog({
key: 'missing',
contentProps: { openingAction: 'open' }
})
).toBe(false)
})
it('creates and reuses extension dialogs with extension-prefixed keys', () => {
const store = useDialogStore()
const first = store.showExtensionDialog({
key: 'external',
component: MockComponent
})
const second = store.showExtensionDialog({
key: 'extension-external',
component: MockComponent
})
expect(first?.key).toBe('extension-external')
expect(second?.key).toBe(first?.key)
expect(store.dialogStack).toHaveLength(1)
})
it('rejects extension dialogs without keys', () => {
const store = useDialogStore()
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const dialog = store.showExtensionDialog({
key: '',
component: MockComponent
})
expect(dialog).toBeUndefined()
expect(error).toHaveBeenCalledWith('Extension dialog key is required')
error.mockRestore()
})
})
describe('ESC key behavior with multiple dialogs', () => {

View File

@@ -1,7 +1,7 @@
import { setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it } from 'vitest'
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils'
import { useDomWidgetStore } from '@/stores/domWidgetStore'
import { createTestingPinia } from '@pinia/testing'
@@ -11,12 +11,12 @@ const createMockDOMWidget = (id: string) => {
return {
id,
element,
node: {
node: createMockLGraphNode({
id: 'node-1',
title: 'Test Node',
pos: [0, 0],
size: [200, 100]
} as Partial<LGraphNode> as LGraphNode,
}),
name: 'test_widget',
type: 'text',
value: 'test',
@@ -112,6 +112,36 @@ describe('domWidgetStore', () => {
store.activateWidget('non-existent')
}).not.toThrow()
})
it('should ignore deactivating non-existent widgets', () => {
store.deactivateWidget('non-existent')
expect(store.widgetStates.size).toBe(0)
})
it('should replace registered widgets', () => {
const widget = createMockDOMWidget('widget-1')
const replacement = {
...createMockDOMWidget('widget-1'),
value: 'replacement'
}
store.registerWidget(widget)
store.deactivateWidget('widget-1')
store.setWidget(replacement)
const state = store.widgetStates.get('widget-1')
expect(state?.widget.value).toBe('replacement')
expect(state?.active).toBe(true)
})
it('should ignore missing widgets when replacing', () => {
const widget = createMockDOMWidget('widget-1')
store.setWidget(widget)
expect(store.widgetStates.size).toBe(0)
})
})
describe('computed states', () => {

View File

@@ -0,0 +1,149 @@
import { createTestingPinia } from '@pinia/testing'
import { setActivePinia } from 'pinia'
import type { MenuItem } from 'primevue/menuitem'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useCommandStore } from '@/stores/commandStore'
import { useMenuItemStore } from '@/stores/menuItemStore'
const canvasStoreMock = vi.hoisted(() => ({ linearMode: false }))
vi.mock('@/constants/coreMenuCommands', () => ({
CORE_MENU_COMMANDS: [[['Core'], ['core.command']]]
}))
vi.mock('@/composables/useErrorHandling', () => ({
useErrorHandling: () => ({
wrapWithErrorHandlingAsync:
(fn: () => Promise<void>, errorHandler?: (e: unknown) => void) =>
async () => {
try {
await fn()
} catch (e) {
if (errorHandler) errorHandler(e)
else throw e
}
}
})
}))
vi.mock('@/platform/keybindings/keybindingStore', () => ({
useKeybindingStore: () => ({
getKeybindingByCommandId: () => null
})
}))
vi.mock('@/renderer/core/canvas/canvasStore', () => ({
useCanvasStore: () => canvasStoreMock
}))
describe('menuItemStore', () => {
beforeEach(() => {
setActivePinia(createTestingPinia({ stubActions: false }))
canvasStoreMock.linearMode = false
})
it('records that linear mode has been seen', () => {
canvasStoreMock.linearMode = true
const store = useMenuItemStore()
expect(store.hasSeenLinear).toBe(true)
})
it('creates nested groups, separators, and active-state metadata', () => {
const store = useMenuItemStore()
const activeItem: MenuItem = {
label: 'Active',
comfyCommand: { id: 'active', function: vi.fn(), active: () => true }
}
const plainItem: MenuItem = { label: 'Plain' }
store.registerMenuGroup(['File', 'Export'], [activeItem])
store.registerMenuGroup(['File', 'Export'], [plainItem])
const file = store.menuItems[0]
const exportGroup = file.items?.[0]
expect(file.label).toBe('File')
expect(exportGroup?.items).toEqual([
activeItem,
{ separator: true },
plainItem
])
expect(store.menuItemHasActiveStateChildren['File.Export']).toBe(true)
})
it('repairs existing group items before appending children', () => {
const store = useMenuItemStore()
store.menuItems.push({ label: 'Tools' })
store.registerMenuGroup(['Tools'], [{ label: 'Child' }])
expect(store.menuItems[0].items).toEqual([{ label: 'Child' }])
})
it('maps command ids to executable menu items', async () => {
const commandStore = useCommandStore()
const fn = vi.fn()
commandStore.registerCommand({
id: 'test.command',
function: fn,
icon: 'icon-[lucide--test]',
label: 'Label',
menubarLabel: 'Menu Label',
tooltip: 'Tip'
})
const store = useMenuItemStore()
const item = store.commandIdToMenuItem('test.command', ['Tools'])
await item.command?.({ originalEvent: new Event('click'), item })
expect(fn).toHaveBeenCalled()
expect(item).toMatchObject({
label: 'Menu Label',
icon: 'icon-[lucide--test]',
tooltip: 'Tip',
parentPath: 'Tools'
})
})
it('loads extension menu commands only for commands owned by the extension', () => {
const commandStore = useCommandStore()
commandStore.registerCommand({
id: 'owned',
function: vi.fn(),
menubarLabel: 'Owned'
})
const store = useMenuItemStore()
store.loadExtensionMenuCommands({
name: 'extension',
commands: [{ id: 'owned', function: vi.fn() }],
menuCommands: [{ path: ['Tools'], commands: ['owned', 'external'] }]
})
store.loadExtensionMenuCommands({ name: 'plain' })
store.loadExtensionMenuCommands({
name: 'empty',
menuCommands: [{ path: ['Tools'], commands: ['missing'] }]
})
expect(store.menuItems[0].items?.map((item) => item.label)).toEqual([
'Owned'
])
})
it('registers core menu commands', () => {
const commandStore = useCommandStore()
commandStore.registerCommand({
id: 'core.command',
function: vi.fn(),
menubarLabel: 'Core Command'
})
const store = useMenuItemStore()
store.registerCoreMenuCommands()
expect(store.menuItems[0].items?.[0].label).toBe('Core Command')
})
})

View File

@@ -90,6 +90,12 @@ describe('templateRankingStore', () => {
})
describe('computePopularScore', () => {
it('normalizes usage against itself before a largest score is loaded', () => {
const store = useTemplateRankingStore()
expect(store.computePopularScore('2024-01-01', 10)).toBeGreaterThan(0.8)
})
it('does not use searchRank', () => {
const store = useTemplateRankingStore()
store.largestUsageScore = 100

View File

@@ -0,0 +1,25 @@
import { createTestingPinia } from '@pinia/testing'
import { setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it } from 'vitest'
import { useExtensionStore } from '@/stores/extensionStore'
import { useTopbarBadgeStore } from '@/stores/topbarBadgeStore'
describe('topbarBadgeStore', () => {
beforeEach(() => {
setActivePinia(createTestingPinia({ stubActions: false }))
})
it('collects topbar badges from registered extensions', () => {
const extensionStore = useExtensionStore()
extensionStore.registerExtension({
name: 'badges',
topbarBadges: [{ text: 'Beta', label: 'BETA' }]
})
extensionStore.registerExtension({ name: 'plain' })
const store = useTopbarBadgeStore()
expect(store.badges).toEqual([{ text: 'Beta', label: 'BETA' }])
})
})

View File

@@ -25,15 +25,13 @@ export enum ServerFeatureFlag {
COMFYHUB_UPLOAD_ENABLED = 'comfyhub_upload_enabled',
COMFYHUB_PROFILE_GATE_ENABLED = 'comfyhub_profile_gate_enabled',
SHOW_SIGNIN_BUTTON = 'show_signin_button',
UNIFIED_CLOUD_AUTH = 'unified_cloud_auth',
CONSOLIDATED_BILLING_ENABLED = 'consolidated_billing_enabled'
UNIFIED_CLOUD_AUTH = 'unified_cloud_auth'
}
export function useFeatureFlags() {
return {
flags: {
teamWorkspacesEnabled: true,
consolidatedBillingEnabled: true
teamWorkspacesEnabled: true
}
}
}

View File

@@ -1,252 +0,0 @@
import axios from 'axios'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useComfyManagerService } from '@/workbench/extensions/manager/services/comfyManagerService'
const mockAxiosInstance = vi.hoisted(() => ({
get: vi.fn(),
post: vi.fn()
}))
const managerState = vi.hoisted(() => ({ isNewManagerUI: true }))
vi.mock('axios', () => ({
default: {
create: vi.fn(() => mockAxiosInstance),
isAxiosError: vi.fn()
}
}))
vi.mock('@/scripts/api', () => ({
api: {
apiURL: (path: string) => path,
clientId: 'client-1',
initialClientId: null
}
}))
vi.mock('@/workbench/extensions/manager/composables/useManagerState', () => ({
useManagerState: () => ({
isNewManagerUI: { value: managerState.isNewManagerUI }
})
}))
vi.mock('uuid', () => ({ v4: () => 'generated-uuid' }))
describe('useComfyManagerService', () => {
let service: ReturnType<typeof useComfyManagerService>
beforeEach(() => {
vi.clearAllMocks()
managerState.isNewManagerUI = true
mockAxiosInstance.get.mockResolvedValue({ data: {} })
mockAxiosInstance.post.mockResolvedValue({ data: null })
service = useComfyManagerService()
})
it('initializes with idle state', () => {
expect(service.isLoading.value).toBe(false)
expect(service.error.value).toBeNull()
})
describe('availability gate', () => {
it('short-circuits requests when Manager is not in NEW_UI mode', async () => {
managerState.isNewManagerUI = false
const result = await service.listInstalledPacks()
expect(result).toBeNull()
expect(mockAxiosInstance.get).not.toHaveBeenCalled()
expect(service.error.value).toBe(
'Manager service is not available in current mode'
)
})
})
describe('read requests', () => {
it('getQueueStatus forwards the client_id param', async () => {
await service.getQueueStatus('abc')
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'manager/queue/status',
expect.objectContaining({ params: { client_id: 'abc' } })
)
})
it('listInstalledPacks hits the installed endpoint', async () => {
await service.listInstalledPacks()
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'customnode/installed',
expect.any(Object)
)
})
it('getImportFailInfo hits the import-fail endpoint', async () => {
await service.getImportFailInfo()
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'customnode/import_fail_info',
expect.any(Object)
)
})
it('getImportFailInfoBulk returns empty without identifiers', async () => {
const result = await service.getImportFailInfoBulk({})
expect(result).toEqual({})
expect(mockAxiosInstance.post).not.toHaveBeenCalled()
})
it('getImportFailInfoBulk posts when identifiers are present', async () => {
await service.getImportFailInfoBulk({ cnr_ids: ['a'] })
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'customnode/import_fail_info_bulk',
{ cnr_ids: ['a'] },
expect.any(Object)
)
})
it('isLegacyManagerUI hits the legacy-ui endpoint', async () => {
await service.isLegacyManagerUI()
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'manager/is_legacy_manager_ui',
expect.any(Object)
)
})
it('getTaskHistory forwards options as params', async () => {
await service.getTaskHistory({ max_items: 5 })
expect(mockAxiosInstance.get).toHaveBeenCalledWith(
'manager/queue/history',
expect.objectContaining({ params: { max_items: 5 } })
)
})
})
describe('queue operations', () => {
it('installPack queues an install task then starts the queue', async () => {
await service.installPack({
id: 'pack',
version: '1.0.0',
selected_version: '1.0.0',
mode: 'remote',
channel: 'default'
})
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/queue/task',
expect.objectContaining({ kind: 'install' }),
expect.any(Object)
)
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/queue/start',
null,
expect.any(Object)
)
})
it('uninstallPack queues an uninstall task', async () => {
await service.uninstallPack({ node_name: 'pack', is_unknown: false })
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/queue/task',
expect.objectContaining({ kind: 'uninstall' }),
expect.any(Object)
)
})
it('updateAllPacks posts to the update_all endpoint', async () => {
await service.updateAllPacks({ mode: 'remote' })
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/queue/update_all',
null,
expect.objectContaining({
params: expect.objectContaining({ mode: 'remote' })
})
)
})
it('updateComfyUI posts to the update_comfyui endpoint', async () => {
await service.updateComfyUI({ is_stable: true })
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/queue/update_comfyui',
null,
expect.objectContaining({
params: expect.objectContaining({ is_stable: true })
})
)
})
it('rebootComfyUI posts to the reboot endpoint', async () => {
await service.rebootComfyUI()
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/reboot',
null,
expect.any(Object)
)
})
it('startQueue posts to the start endpoint', async () => {
await service.startQueue()
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'manager/queue/start',
null,
expect.any(Object)
)
})
})
describe('error mapping', () => {
it('prefers a route-specific message for a matching status', async () => {
mockAxiosInstance.post.mockRejectedValue({
response: { status: 403, data: {} }
})
vi.mocked(axios.isAxiosError).mockReturnValue(true)
await service.rebootComfyUI()
expect(service.error.value).toBe(
'Forbidden: Rebooting ComfyUI requires security_level of middle or below'
)
})
it('maps 404 to a connection message', async () => {
mockAxiosInstance.get.mockRejectedValue({
response: { status: 404, data: {} }
})
vi.mocked(axios.isAxiosError).mockReturnValue(true)
await service.listInstalledPacks()
expect(service.error.value).toBe('Could not connect to ComfyUI-Manager')
})
it('falls back to the response message for other statuses', async () => {
mockAxiosInstance.get.mockRejectedValue({
response: { status: 500, data: { message: 'server exploded' } }
})
vi.mocked(axios.isAxiosError).mockReturnValue(true)
await service.listInstalledPacks()
expect(service.error.value).toBe('server exploded')
})
it('handles non-axios errors', async () => {
mockAxiosInstance.get.mockRejectedValue(new Error('boom'))
vi.mocked(axios.isAxiosError).mockReturnValue(false)
await service.listInstalledPacks()
expect(service.error.value).toBe('Fetching installed packs failed: boom')
})
})
})

View File

@@ -1,9 +1,10 @@
import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios'
import type { AxiosError, AxiosResponse } from 'axios'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'
import { ref } from 'vue'
import { useApiRequest } from '@/composables/useApiRequest'
import { api } from '@/scripts/api'
import { isAbortError } from '@/utils/typeGuardUtil'
import { useManagerState } from '@/workbench/extensions/manager/composables/useManagerState'
import type { components } from '@/workbench/extensions/manager/types/generatedManagerTypes'
@@ -50,64 +51,72 @@ const managerApiClient = axios.create({
* Note: This service should only be used when Manager state is NEW_UI
*/
export const useComfyManagerService = () => {
const isLoading = ref(false)
const error = ref<string | null>(null)
// Check if manager service should be available
const isManagerServiceAvailable = () => {
const managerState = useManagerState()
return managerState.isNewManagerUI.value
}
const mapError = (
const handleRequestError = (
err: unknown,
context: string,
routeSpecificErrors?: Record<number, string>
): string => {
) => {
// Don't treat cancellation as an error
if (isAbortError(err)) return
let message: string
if (!axios.isAxiosError(err)) {
return `${context} failed: ${err instanceof Error ? err.message : String(err)}`
message = `${context} failed: ${err instanceof Error ? err.message : String(err)}`
} else {
const axiosError = err as AxiosError<{ message: string }>
const status = axiosError.response?.status
if (status && routeSpecificErrors?.[status]) {
message = routeSpecificErrors[status]
} else if (status === 404) {
message = 'Could not connect to ComfyUI-Manager'
} else {
message =
axiosError.response?.data?.message ??
`${context} failed with status ${status}`
}
}
const axiosError = err as AxiosError<{ message: string }>
const status = axiosError.response?.status
if (status && routeSpecificErrors?.[status]) {
return routeSpecificErrors[status]
}
if (status === 404) {
return 'Could not connect to ComfyUI-Manager'
}
return (
axiosError.response?.data?.message ??
`${context} failed with status ${status}`
)
error.value = message
}
const {
isLoading,
error,
executeRequest: sendRequest
} = useApiRequest({
client: managerApiClient,
mapError
})
const executeRequest = <T>(
apiCall: (client: AxiosInstance) => Promise<AxiosResponse<T>>,
const executeRequest = async <T>(
requestCall: () => Promise<AxiosResponse<T>>,
options: {
errorContext: string
routeSpecificErrors?: Record<number, string>
isQueueOperation?: boolean
}
): Promise<T | null> => {
const { errorContext, routeSpecificErrors, isQueueOperation } = options
// Block service calls if not in NEW_UI state
if (!isManagerServiceAvailable()) {
error.value = 'Manager service is not available in current mode'
return Promise.resolve(null)
return null
}
const { isQueueOperation, ...requestOptions } = options
return sendRequest(apiCall, {
...requestOptions,
onSuccess: isQueueOperation ? startQueue : undefined
})
isLoading.value = true
error.value = null
try {
const response = await requestCall()
if (isQueueOperation) await startQueue()
return response.data
} catch (err) {
handleRequestError(err, errorContext, routeSpecificErrors)
return null
} finally {
isLoading.value = false
}
}
const startQueue = async (signal?: AbortSignal) => {
@@ -117,7 +126,7 @@ export const useComfyManagerService = () => {
}
return executeRequest<null>(
(client) => client.post(ManagerRoute.START_QUEUE, null, { signal }),
() => managerApiClient.post(ManagerRoute.START_QUEUE, null, { signal }),
{ errorContext, routeSpecificErrors }
)
}
@@ -126,8 +135,8 @@ export const useComfyManagerService = () => {
const errorContext = 'Getting ComfyUI-Manager queue status'
return executeRequest<ManagerQueueStatus>(
(client) =>
client.get(ManagerRoute.QUEUE_STATUS, {
() =>
managerApiClient.get(ManagerRoute.QUEUE_STATUS, {
params: client_id ? { client_id } : undefined,
signal
}),
@@ -139,7 +148,7 @@ export const useComfyManagerService = () => {
const errorContext = 'Fetching installed packs'
return executeRequest<InstalledPacksResponse>(
(client) => client.get(ManagerRoute.LIST_INSTALLED, { signal }),
() => managerApiClient.get(ManagerRoute.LIST_INSTALLED, { signal }),
{ errorContext }
)
}
@@ -148,7 +157,7 @@ export const useComfyManagerService = () => {
const errorContext = 'Fetching import failure information'
return executeRequest<Record<string, unknown>>(
(client) => client.get(ManagerRoute.IMPORT_FAIL_INFO, { signal }),
() => managerApiClient.get(ManagerRoute.IMPORT_FAIL_INFO, { signal }),
{ errorContext }
)
}
@@ -164,8 +173,8 @@ export const useComfyManagerService = () => {
}
return executeRequest<components['schemas']['ImportFailInfoBulkResponse']>(
(client) =>
client.post(ManagerRoute.IMPORT_FAIL_INFO_BULK, params, {
() =>
managerApiClient.post(ManagerRoute.IMPORT_FAIL_INFO_BULK, params, {
signal
}),
{ errorContext }
@@ -192,7 +201,7 @@ export const useComfyManagerService = () => {
}
return executeRequest<null>(
(client) => client.post(ManagerRoute.QUEUE_TASK, task, { signal }),
() => managerApiClient.post(ManagerRoute.QUEUE_TASK, task, { signal }),
{ errorContext, routeSpecificErrors, isQueueOperation: true }
)
}
@@ -255,8 +264,8 @@ export const useComfyManagerService = () => {
}
return executeRequest<null>(
(client) =>
client.post(ManagerRoute.UPDATE_ALL, null, {
() =>
managerApiClient.post(ManagerRoute.UPDATE_ALL, null, {
params: queryParams,
signal
}),
@@ -282,8 +291,8 @@ export const useComfyManagerService = () => {
}
return executeRequest<null>(
(client) =>
client.post(ManagerRoute.UPDATE_COMFYUI, null, {
() =>
managerApiClient.post(ManagerRoute.UPDATE_COMFYUI, null, {
params: queryParams,
signal
}),
@@ -298,7 +307,7 @@ export const useComfyManagerService = () => {
}
return executeRequest<null>(
(client) => client.post(ManagerRoute.REBOOT, null, { signal }),
() => managerApiClient.post(ManagerRoute.REBOOT, null, { signal }),
{ errorContext, routeSpecificErrors }
)
}
@@ -307,7 +316,7 @@ export const useComfyManagerService = () => {
const errorContext = 'Checking if user set Manager to use the legacy UI'
return executeRequest<{ is_legacy_manager_ui: boolean }>(
(client) => client.get(ManagerRoute.IS_LEGACY_MANAGER_UI, { signal }),
() => managerApiClient.get(ManagerRoute.IS_LEGACY_MANAGER_UI, { signal }),
{ errorContext }
)
}
@@ -324,8 +333,8 @@ export const useComfyManagerService = () => {
const errorContext = 'Getting ComfyUI-Manager task history'
return executeRequest<ManagerTaskHistory>(
(client) =>
client.get(ManagerRoute.TASK_HISTORY, {
() =>
managerApiClient.get(ManagerRoute.TASK_HISTORY, {
params: options,
signal
}),