For the stew:
8 tablespoons (1 stick) unsalted butter, divided
7 large yellow onions (5 to 5 1/2 pounds total), halved and cut into 1/4-inch-thick slices
4 large shallots (about 8 ounces), peeled and cut into small dice
4 teaspoons kosher salt, divided
1 teaspoon freshly ground black pepper, divided
6 cloves garlic, minced
5 stalks celery (about 12 ounces), including leaves, cut into small dice
5 carrots (about 8 ounces), peeled and cut into small dice
6 cups cremini and/or button mushrooms (about 1 1/2 pounds), sliced thinly
1/4 cup all-purpose flour
1 cup dry Riesling wine
6 to 8 fresh sage leaves, minced, or 2 teaspoons dried sage
Leaves of 5 sprigs fresh thyme, finely chopped
1 (15-ounce) can white beans and their liquid (optional)
For the topping:
1 large baguette (about 1 pound), cut crosswise into 24 slices
12 ounces Gruyere, Comté, or Raclette cheese, shredded
4 tablespoons unsalted butter
Make the stew: Heat 4 tablespoons of the butter in a large, heavy-bottomed pot or Dutch oven over medium-high heat until melted and just beginning to foam.
Add the onions, shallots, 1 teaspoon of the salt, and 1 teaspoon of the pepper. Cook, stirring occasionally, until the onions are translucent and begin to brown on the edges, 5 to 7 minutes. Reduce the heat to low (or the lowest your stovetop will go) and cook, stirring occasionally and adjusting the heat as needed, until the onions are completely softened and caramel brown in color, about 30 minutes.
Add the garlic, celery, carrots, and mushrooms (add the mushrooms in batches if they do not all not fit into your pot at once, as they will cook down and reduce in volume), and stir to combine. Once you have added all the mushrooms, cover and cook 20 minutes more.
Arrange a rack in the middle of the oven and heat to 375°F. Coat a 9x13-inch baking dish with cooking spray and set aside.
When the vegetables are ready, transfer them with a slotted spoon to a large bowl and set aside. Pour the remaining vegetable cooking liquid into another bowl or a measuring cup with a spout; set aside.
Return the pot to high heat, add the remaining 4 tablespoons of butter, and cook until it is melted and begins to foam. Add the flour, whisk to combine, and cook until it is golden-blonde in color, about 2 minutes. Add the wine and whisk to combine.
Add the reserved vegetable cooking liquid and whisk to combine. Add the sage, thyme, and remaining 3 teaspoons salt and whisk to combine. Add the reserved cooked vegeta