BlueGit

timfa questward

Keep cauldron mats in the bag until bottle succeeds.

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
79aacce64b5f4ce3933d5a39e690744d19ad05c6
Parent
91015956
7 files changed +357 −228
.cursor/rules/station-inventory.mdc added +42 −0
@@ -0,0 +1,42 @@
1 ---
2 description: Crafting station slots never hold items — bag-only until craft/brew succeeds; UI is presentation.
3 alwaysApply: true
4 ---
5
6 # Station slots are never real inventory
7
8 For **all current and future** crafting stations where the player appears to put something “in” the station (furnace, anvil, cauldron, tailor, loom, benches, ovens, …):
9
10 Items **do not leave the bag** into the station. Even when the UI looks like materials sit in station slots, that is **client-side presentation / soft claim only**. The server must not treat a station or tile as an item container for those mats.
11
12 ## Hard rules
13
14 - Station/cauldron/bench “slots” are a **view or reservation over the bag**, not a second inventory.
15 - Materials are **consumed only when the craft/brew successfully completes** (same moment the product is created).
16 - Closing the UI, cancelling, clearing, script stop, logout, or **death mid-craft/brew** must **not** destroy reserved mats.
17 - Station progress/session state is **per player**, never shared on the tile — players cannot take each other’s “station contents.”
18 - On the finishing intent (`craft` complete, `bottle`, `create-dye`, …), the server **validates the bag** and then consumes; it does not trust client slot UI as ownership of items.
19
20 ## Forbidden
21
22 ```text
23 # ❌ BAD — take from bag into station/session on insert or open
24 onInsert(herb) { takeFromBag(herb); session.brew.push(herb); }
25 onClose() { /* mats already gone, no refund */ }
26
27 # ❌ BAD — tile-global station inventory
28 world.tileStations[x][y].slots = [...]
29 ```
30
31 ## Required pattern
32
33 ```text
34 # ✅ GOOD — client shows slots; server soft-tracks steps/claims only
35 onInsert(herb) { assertBagHas(herb); session.pendingClaims.push(herb); /* bag unchanged */ }
36 onBottle() { assertBagHas(claims); takeFromBag(claims + bottles); grantProduct(); }
37 onCloseOrDeath() { clearSession(); /* bag untouched */ }
38 ```
39
40 Recipe-only stations (no insert UI) already match this if they only deduct on successful craft completion.
41
42 When adding a new station with “put items in,” default to **client-side slot UI + server bag check on commit** — never a real station inventory.
@@ -0,0 +1,42 @@
1---
2description: Crafting station slots never hold items — bag-only until craft/brew succeeds; UI is presentation.
3alwaysApply: true
4---
5
6# Station slots are never real inventory
7
8For **all current and future** crafting stations where the player appears to put something “in” the station (furnace, anvil, cauldron, tailor, loom, benches, ovens, …):
9
10Items **do not leave the bag** into the station. Even when the UI looks like materials sit in station slots, that is **client-side presentation / soft claim only**. The server must not treat a station or tile as an item container for those mats.
11
12## Hard rules
13
14- Station/cauldron/bench “slots” are a **view or reservation over the bag**, not a second inventory.
15- Materials are **consumed only when the craft/brew successfully completes** (same moment the product is created).
16- Closing the UI, cancelling, clearing, script stop, logout, or **death mid-craft/brew** must **not** destroy reserved mats.
17- Station progress/session state is **per player**, never shared on the tile — players cannot take each other’s “station contents.”
18- On the finishing intent (`craft` complete, `bottle`, `create-dye`, …), the server **validates the bag** and then consumes; it does not trust client slot UI as ownership of items.
19
20## Forbidden
21
22```text
23# ❌ BAD — take from bag into station/session on insert or open
24onInsert(herb) { takeFromBag(herb); session.brew.push(herb); }
25onClose() { /* mats already gone, no refund */ }
26
27# ❌ BAD — tile-global station inventory
28world.tileStations[x][y].slots = [...]
29```
30
31## Required pattern
32
33```text
34# ✅ GOOD — client shows slots; server soft-tracks steps/claims only
35onInsert(herb) { assertBagHas(herb); session.pendingClaims.push(herb); /* bag unchanged */ }
36onBottle() { assertBagHas(claims); takeFromBag(claims + bottles); grantProduct(); }
37onCloseOrDeath() { clearSession(); /* bag untouched */ }
38```
39
40Recipe-only stations (no insert UI) already match this if they only deduct on successful craft completion.
41
42When adding a new station with “put items in,” default to **client-side slot UI + server bag check on commit** — never a real station inventory.
client/src/play/alchemy.js +78 −25
@@ -47,6 +47,8 @@ export function initAlchemy ({
47 47
48 48 let open = false;
49 49 let state = null;
50 let localSlots = emptyAlchemySlots();
51 let localDyeSlots = emptyDyeSlots();
50 52 let activeTab = "alchemy";
51 53 let pickMode = "alchemy";
52 54 let pickSlotIndex = null;
@@ -54,6 +56,27 @@ export function initAlchemy ({
54 56 let pickInstance = null;
55 57 let pendingDyeConfirm = null;
56 58
59 function emptyAlchemySlots ()
60 {
61 return Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
62 }
63
64 function emptyDyeSlots ()
65 {
66 return Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
67 }
68
69 function flowerPayload ()
70 {
71 return localDyeSlots
72 .filter((slot) => slot?.itemId === ItemId.flower && slot.quantity > 0)
73 .map((slot) => ({
74 itemId: slot.itemId,
75 quantity: slot.quantity | 0,
76 instance: slot.instance ? structuredClone(slot.instance) : null
77 }));
78 }
79
57 80 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
58 81 backdrop?.addEventListener("click", () => close());
59 82 tabAlchemy?.addEventListener("click", () => setTab("alchemy"));
@@ -67,11 +90,25 @@ export function initAlchemy ({
67 90 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
68 91 { socket.send({ type: MessageType.cauldronBottle }); });
69 92 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
70 { socket.send({ type: MessageType.cauldronClear }); });
93 {
94 localSlots = emptyAlchemySlots();
95 socket.send({ type: MessageType.cauldronClear });
96 render();
97 });
71 98 document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>
72 { socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: false }); });
99 {
100 socket.send({
101 type: MessageType.cauldronCreateDye,
102 confirmOverflow: false,
103 flowers: flowerPayload()
104 });
105 });
73 106 document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>
74 { socket.send({ type: MessageType.cauldronClearDye }); });
107 {
108 localDyeSlots = emptyDyeSlots();
109 socket.send({ type: MessageType.cauldronClearDye });
110 render();
111 });
75 112 saveBtn?.addEventListener("click", () =>
76 113 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
77 114 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
@@ -82,7 +119,11 @@ export function initAlchemy ({
82 119 document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>
83 120 {
84 121 closeDyeConfirm();
85 socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: true });
122 socket.send({
123 type: MessageType.cauldronCreateDye,
124 confirmOverflow: true,
125 flowers: flowerPayload()
126 });
86 127 });
87 128
88 129 function setTab (tab)
@@ -158,7 +199,7 @@ export function initAlchemy ({
158 199 insertsEl.replaceChildren();
159 200 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
160 201 {
161 const reserved = state?.slots?.[i] ?? null;
202 const reserved = localSlots[i] ?? null;
162 203 slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));
163 204 const insertBtn = document.createElement("button");
164 205 insertBtn.type = "button";
@@ -167,7 +208,19 @@ export function initAlchemy ({
167 208 insertBtn.disabled = !reserved;
168 209 insertBtn.title = "Insert into cauldron";
169 210 insertBtn.addEventListener("click", () =>
170 { socket.send({ type: MessageType.cauldronInsert, slotIndex: i }); });
211 {
212 const slot = localSlots[i];
213 if (!slot)
214 { return; }
215 socket.send({
216 type: MessageType.cauldronInsert,
217 itemId: slot.itemId,
218 quantity: slot.quantity | 0,
219 instance: slot.instance ?? null
220 });
221 localSlots[i] = null;
222 render();
223 });
171 224 insertsEl.append(insertBtn);
172 225 }
173 226 }
@@ -179,7 +232,7 @@ export function initAlchemy ({
179 232 dyeSlotsEl.replaceChildren();
180 233 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
181 234 {
182 const reserved = state?.dyeSlots?.[i] ?? null;
235 const reserved = localDyeSlots[i] ?? null;
183 236 dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));
184 237 }
185 238 }
@@ -287,27 +340,17 @@ export function initAlchemy ({
287 340 if (pickSlotIndex == null || pickItemId == null)
288 341 { return; }
289 342 const quantity = Math.max(1, pickQty.value | 0);
343 const entry = {
344 itemId: pickItemId,
345 quantity,
346 instance: pickInstance ? structuredClone(pickInstance) : null
347 };
290 348 if (pickMode === "dye")
291 {
292 socket.send({
293 type: MessageType.cauldronSetDyeSlot,
294 slotIndex: pickSlotIndex,
295 itemId: pickItemId,
296 quantity,
297 instance: pickInstance
298 });
299 }
349 { localDyeSlots[pickSlotIndex] = entry; }
300 350 else
301 {
302 socket.send({
303 type: MessageType.cauldronSetSlot,
304 slotIndex: pickSlotIndex,
305 itemId: pickItemId,
306 quantity,
307 instance: pickInstance
308 });
309 }
351 { localSlots[pickSlotIndex] = entry; }
310 352 closePick();
353 render();
311 354 }
312 355
313 356 function openDyeConfirm (confirm)
@@ -331,6 +374,8 @@ export function initAlchemy ({
331 374 {
332 375 open = true;
333 376 state = nextState;
377 localSlots = emptyAlchemySlots();
378 localDyeSlots = emptyDyeSlots();
334 379 backdrop.hidden = false;
335 380 panel.hidden = false;
336 381 if (statusEl)
@@ -348,6 +393,8 @@ export function initAlchemy ({
348 393 open = false;
349 394 backdrop.hidden = true;
350 395 panel.hidden = true;
396 localSlots = emptyAlchemySlots();
397 localDyeSlots = emptyDyeSlots();
351 398 closePick();
352 399 closeDyeConfirm();
353 400 socket.send({ type: MessageType.cauldronClose });
@@ -364,6 +411,8 @@ export function initAlchemy ({
364 411 {
365 412 open = false;
366 413 state = null;
414 localSlots = emptyAlchemySlots();
415 localDyeSlots = emptyDyeSlots();
367 416 if (backdrop)
368 417 { backdrop.hidden = true; }
369 418 if (panel)
@@ -381,6 +430,8 @@ export function initAlchemy ({
381 430 if (panel)
382 431 { panel.hidden = true; }
383 432 state = null;
433 localSlots = emptyAlchemySlots();
434 localDyeSlots = emptyDyeSlots();
384 435 closeDyeConfirm();
385 436 return;
386 437 }
@@ -403,8 +454,10 @@ export function initAlchemy ({
403 454 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
404 455 if (result.potion?.potionKey === "dye")
405 456 {
457 localDyeSlots = emptyDyeSlots();
406 458 if (dyeStatusEl)
407 459 { dyeStatusEl.textContent = line; }
460 render();
408 461 }
409 462 else if (statusEl)
410 463 { statusEl.textContent = line; }
@@ -47,6 +47,8 @@ export function initAlchemy ({
47
47
48 let open = false;
48 let open = false;
49 let state = null;
49 let state = null;
50 let localSlots = emptyAlchemySlots();
51 let localDyeSlots = emptyDyeSlots();
50 let activeTab = "alchemy";
52 let activeTab = "alchemy";
51 let pickMode = "alchemy";
53 let pickMode = "alchemy";
52 let pickSlotIndex = null;
54 let pickSlotIndex = null;
@@ -54,6 +56,27 @@ export function initAlchemy ({
54 let pickInstance = null;
56 let pickInstance = null;
55 let pendingDyeConfirm = null;
57 let pendingDyeConfirm = null;
56
58
59 function emptyAlchemySlots ()
60 {
61 return Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
62 }
63
64 function emptyDyeSlots ()
65 {
66 return Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
67 }
68
69 function flowerPayload ()
70 {
71 return localDyeSlots
72 .filter((slot) => slot?.itemId === ItemId.flower && slot.quantity > 0)
73 .map((slot) => ({
74 itemId: slot.itemId,
75 quantity: slot.quantity | 0,
76 instance: slot.instance ? structuredClone(slot.instance) : null
77 }));
78 }
79
57 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
80 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
58 backdrop?.addEventListener("click", () => close());
81 backdrop?.addEventListener("click", () => close());
59 tabAlchemy?.addEventListener("click", () => setTab("alchemy"));
82 tabAlchemy?.addEventListener("click", () => setTab("alchemy"));
@@ -67,11 +90,25 @@ export function initAlchemy ({
67 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
90 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
68 { socket.send({ type: MessageType.cauldronBottle }); });
91 { socket.send({ type: MessageType.cauldronBottle }); });
69 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
92 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
70 { socket.send({ type: MessageType.cauldronClear }); });
93 {
94 localSlots = emptyAlchemySlots();
95 socket.send({ type: MessageType.cauldronClear });
96 render();
97 });
71 document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>
98 document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>
72 { socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: false }); });
99 {
100 socket.send({
101 type: MessageType.cauldronCreateDye,
102 confirmOverflow: false,
103 flowers: flowerPayload()
104 });
105 });
73 document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>
106 document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>
74 { socket.send({ type: MessageType.cauldronClearDye }); });
107 {
108 localDyeSlots = emptyDyeSlots();
109 socket.send({ type: MessageType.cauldronClearDye });
110 render();
111 });
75 saveBtn?.addEventListener("click", () =>
112 saveBtn?.addEventListener("click", () =>
76 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
113 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
77 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
114 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
@@ -82,7 +119,11 @@ export function initAlchemy ({
82 document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>
119 document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>
83 {
120 {
84 closeDyeConfirm();
121 closeDyeConfirm();
85 socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: true });
122 socket.send({
123 type: MessageType.cauldronCreateDye,
124 confirmOverflow: true,
125 flowers: flowerPayload()
126 });
86 });
127 });
87
128
88 function setTab (tab)
129 function setTab (tab)
@@ -158,7 +199,7 @@ export function initAlchemy ({
158 insertsEl.replaceChildren();
199 insertsEl.replaceChildren();
159 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
200 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
160 {
201 {
161 const reserved = state?.slots?.[i] ?? null;
202 const reserved = localSlots[i] ?? null;
162 slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));
203 slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));
163 const insertBtn = document.createElement("button");
204 const insertBtn = document.createElement("button");
164 insertBtn.type = "button";
205 insertBtn.type = "button";
@@ -167,7 +208,19 @@ export function initAlchemy ({
167 insertBtn.disabled = !reserved;
208 insertBtn.disabled = !reserved;
168 insertBtn.title = "Insert into cauldron";
209 insertBtn.title = "Insert into cauldron";
169 insertBtn.addEventListener("click", () =>
210 insertBtn.addEventListener("click", () =>
170 { socket.send({ type: MessageType.cauldronInsert, slotIndex: i }); });
211 {
212 const slot = localSlots[i];
213 if (!slot)
214 { return; }
215 socket.send({
216 type: MessageType.cauldronInsert,
217 itemId: slot.itemId,
218 quantity: slot.quantity | 0,
219 instance: slot.instance ?? null
220 });
221 localSlots[i] = null;
222 render();
223 });
171 insertsEl.append(insertBtn);
224 insertsEl.append(insertBtn);
172 }
225 }
173 }
226 }
@@ -179,7 +232,7 @@ export function initAlchemy ({
179 dyeSlotsEl.replaceChildren();
232 dyeSlotsEl.replaceChildren();
180 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
233 for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
181 {
234 {
182 const reserved = state?.dyeSlots?.[i] ?? null;
235 const reserved = localDyeSlots[i] ?? null;
183 dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));
236 dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));
184 }
237 }
185 }
238 }
@@ -287,27 +340,17 @@ export function initAlchemy ({
287 if (pickSlotIndex == null || pickItemId == null)
340 if (pickSlotIndex == null || pickItemId == null)
288 { return; }
341 { return; }
289 const quantity = Math.max(1, pickQty.value | 0);
342 const quantity = Math.max(1, pickQty.value | 0);
343 const entry = {
344 itemId: pickItemId,
345 quantity,
346 instance: pickInstance ? structuredClone(pickInstance) : null
347 };
290 if (pickMode === "dye")
348 if (pickMode === "dye")
291 {
349 { localDyeSlots[pickSlotIndex] = entry; }
292 socket.send({
293 type: MessageType.cauldronSetDyeSlot,
294 slotIndex: pickSlotIndex,
295 itemId: pickItemId,
296 quantity,
297 instance: pickInstance
298 });
299 }
300 else
350 else
301 {
351 { localSlots[pickSlotIndex] = entry; }
302 socket.send({
303 type: MessageType.cauldronSetSlot,
304 slotIndex: pickSlotIndex,
305 itemId: pickItemId,
306 quantity,
307 instance: pickInstance
308 });
309 }
310 closePick();
352 closePick();
353 render();
311 }
354 }
312
355
313 function openDyeConfirm (confirm)
356 function openDyeConfirm (confirm)
@@ -331,6 +374,8 @@ export function initAlchemy ({
331 {
374 {
332 open = true;
375 open = true;
333 state = nextState;
376 state = nextState;
377 localSlots = emptyAlchemySlots();
378 localDyeSlots = emptyDyeSlots();
334 backdrop.hidden = false;
379 backdrop.hidden = false;
335 panel.hidden = false;
380 panel.hidden = false;
336 if (statusEl)
381 if (statusEl)
@@ -348,6 +393,8 @@ export function initAlchemy ({
348 open = false;
393 open = false;
349 backdrop.hidden = true;
394 backdrop.hidden = true;
350 panel.hidden = true;
395 panel.hidden = true;
396 localSlots = emptyAlchemySlots();
397 localDyeSlots = emptyDyeSlots();
351 closePick();
398 closePick();
352 closeDyeConfirm();
399 closeDyeConfirm();
353 socket.send({ type: MessageType.cauldronClose });
400 socket.send({ type: MessageType.cauldronClose });
@@ -364,6 +411,8 @@ export function initAlchemy ({
364 {
411 {
365 open = false;
412 open = false;
366 state = null;
413 state = null;
414 localSlots = emptyAlchemySlots();
415 localDyeSlots = emptyDyeSlots();
367 if (backdrop)
416 if (backdrop)
368 { backdrop.hidden = true; }
417 { backdrop.hidden = true; }
369 if (panel)
418 if (panel)
@@ -381,6 +430,8 @@ export function initAlchemy ({
381 if (panel)
430 if (panel)
382 { panel.hidden = true; }
431 { panel.hidden = true; }
383 state = null;
432 state = null;
433 localSlots = emptyAlchemySlots();
434 localDyeSlots = emptyDyeSlots();
384 closeDyeConfirm();
435 closeDyeConfirm();
385 return;
436 return;
386 }
437 }
@@ -403,8 +454,10 @@ export function initAlchemy ({
403 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
454 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
404 if (result.potion?.potionKey === "dye")
455 if (result.potion?.potionKey === "dye")
405 {
456 {
457 localDyeSlots = emptyDyeSlots();
406 if (dyeStatusEl)
458 if (dyeStatusEl)
407 { dyeStatusEl.textContent = line; }
459 { dyeStatusEl.textContent = line; }
460 render();
408 }
461 }
409 else if (statusEl)
462 else if (statusEl)
410 { statusEl.textContent = line; }
463 { statusEl.textContent = line; }
docs/FEATURES.md +1 −1
@@ -259,7 +259,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
259 259 ## Crafting stations
260 260
261 261 **Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
262 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag. Materials are consumed only when the craft/brew **succeeds**. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global.
262 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
263 263 **TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
264 264 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
265 265
@@ -259,7 +259,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
259## Crafting stations
259## Crafting stations
260
260
261**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
261**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
262**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag. Materials are consumed only when the craft/brew **succeeds**. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global.
262**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
263**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
263**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
264**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
264**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
265
265
docs/SCRIPTS.md +2 −2
@@ -209,13 +209,13 @@ Exact gather verb must match what the block supports; wrong verb → error (`cho
209 209
210 210 **Station state hard rule:** cauldron / furnace / anvil / every craft station progress is **per player**, never shared on the tile. Many characters may use the “same” station block at once without interfering. Scripts and the UI obey the same rule — this applies to **all current and future** crafting stations.
211 211
212 **Inventory hard rule (stations — script and player):** an item is **never committed** into a station. Slots in craft/brew UIs are a **view / reservation** over the bag only — materials do not leave the inventory when placed in a station slot. Therefore:
212 **Inventory hard rule (stations — script and player):** an item is **never committed** into a station. Slots in craft/brew UIs are a **view / reservation** over the bag only — materials do not leave the inventory when placed in a station slot. Even when it *looks* like something sits in the cauldron or bench, it is still in the bag. Therefore:
213 213
214 214 - Closing the station UI, cancelling, `cauldron clear`, script stop/error, logout, or **death mid-craft / mid-brew** must leave the bag unchanged for those materials (or immediately show them back — there was nothing to return from the station itself).
215 215 - Item loss due to closed UI or death while using a station is **impossible**.
216 216 - Materials are consumed only when the craft/brew **successfully completes** (same moment the product is created), never earlier.
217 217
218 This is a gameplay rule for humans and scripts alike; the script layer must not invent a different consume-on-insert path.
218 This is a gameplay rule for humans and scripts alike (also `.cursor/rules/station-inventory.mdc`); the script layer must not invent a different consume-on-insert path.
219 219
220 220 #### Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …)
221 221
@@ -209,13 +209,13 @@ Exact gather verb must match what the block supports; wrong verb → error (`cho
209
209
210**Station state hard rule:** cauldron / furnace / anvil / every craft station progress is **per player**, never shared on the tile. Many characters may use the “same” station block at once without interfering. Scripts and the UI obey the same rule — this applies to **all current and future** crafting stations.
210**Station state hard rule:** cauldron / furnace / anvil / every craft station progress is **per player**, never shared on the tile. Many characters may use the “same” station block at once without interfering. Scripts and the UI obey the same rule — this applies to **all current and future** crafting stations.
211
211
212**Inventory hard rule (stations — script and player):** an item is **never committed** into a station. Slots in craft/brew UIs are a **view / reservation** over the bag only — materials do not leave the inventory when placed in a station slot. Therefore:
212**Inventory hard rule (stations — script and player):** an item is **never committed** into a station. Slots in craft/brew UIs are a **view / reservation** over the bag only — materials do not leave the inventory when placed in a station slot. Even when it *looks* like something sits in the cauldron or bench, it is still in the bag. Therefore:
213
213
214- Closing the station UI, cancelling, `cauldron clear`, script stop/error, logout, or **death mid-craft / mid-brew** must leave the bag unchanged for those materials (or immediately show them back — there was nothing to return from the station itself).
214- Closing the station UI, cancelling, `cauldron clear`, script stop/error, logout, or **death mid-craft / mid-brew** must leave the bag unchanged for those materials (or immediately show them back — there was nothing to return from the station itself).
215- Item loss due to closed UI or death while using a station is **impossible**.
215- Item loss due to closed UI or death while using a station is **impossible**.
216- Materials are consumed only when the craft/brew **successfully completes** (same moment the product is created), never earlier.
216- Materials are consumed only when the craft/brew **successfully completes** (same moment the product is created), never earlier.
217
217
218This is a gameplay rule for humans and scripts alike; the script layer must not invent a different consume-on-insert path.
218This is a gameplay rule for humans and scripts alike (also `.cursor/rules/station-inventory.mdc`); the script layer must not invent a different consume-on-insert path.
219
219
220#### Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …)
220#### Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …)
221
221
server/src/alchemy/service.js +164 −185
@@ -33,8 +33,9 @@ import { randomUUID } from "node:crypto";
33 33 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
34 34
35 35 /**
36 * Cauldron sessions live on the worker world (per character while the UI is open).
37 * Clients send intents only; all brew outcomes are evaluated here.
36 * Cauldron UI slot contents live on the client only.
37 * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance)
38 * without removing items from the bag until bottle / create-dye succeeds.
38 39 */
39 40
40 41 function userError (message)
@@ -61,39 +62,21 @@ function ensureSessions (world)
61 62 function emptySession ()
62 63 {
63 64 return {
64 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
65 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
66 brew: [],
65 /** Soft claims for alchemy inserts — still in the bag until bottle. */
66 pendingBrew: [],
67 67 steps: [],
68 68 lastSuccessRecipe: null
69 69 };
70 70 }
71 71
72 function normalizeSession (session)
73 {
74 if (!Array.isArray(session.dyeSlots) || session.dyeSlots.length !== DYE_CAULDRON_SLOT_COUNT)
75 { session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null); }
76 return session;
77 }
78
79 function slotView (slot)
80 {
81 if (!slot)
82 { return null; }
83 return {
84 itemId: slot.itemId,
85 quantity: slot.quantity | 0,
86 instance: slot.instance ? structuredClone(slot.instance) : null
87 };
88 }
89
90 72 function sessionView (session)
91 73 {
92 74 const steps = session.steps ?? [];
93 75 return {
94 slots: (session.slots ?? []).map(slotView),
95 dyeSlots: (session.dyeSlots ?? []).map(slotView),
96 brew: (session.brew ?? []).map((row) => ({
76 // Slots / dye slots are client-only; never authoritative on the server.
77 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
78 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
79 brew: (session.pendingBrew ?? []).map((row) => ({
97 80 itemId: row.itemId,
98 81 quantity: row.quantity | 0,
99 82 instance: row.instance ? structuredClone(row.instance) : null
@@ -139,21 +122,15 @@ function requireSession (world, characterId)
139 122 const session = ensureSessions(world).get(characterId);
140 123 if (!session)
141 124 { throw userError("Open a cauldron first."); }
142 return normalizeSession(session);
125 return session;
143 126 }
144 127
145 128 function clearAlchemy (session)
146 129 {
147 session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
148 session.brew = [];
130 session.pendingBrew = [];
149 131 session.steps = [];
150 132 }
151 133
152 function clearDyeSlots (session)
153 {
154 session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
155 }
156
157 134 function ensureInventory (world, handle)
158 135 {
159 136 let inventory = world.ecs.get(handle, Component.inventory);
@@ -163,6 +140,62 @@ function ensureInventory (world, handle)
163 140 return inventory;
164 141 }
165 142
143 function countMatchingInstance (slots, itemId, instance)
144 {
145 let total = 0;
146 const key = JSON.stringify(instance ?? null);
147 for (const slot of slots ?? [])
148 {
149 if (!slot || slot.itemId !== itemId)
150 { continue; }
151 if (JSON.stringify(slot.instance ?? null) !== key)
152 { continue; }
153 total += stackQuantity(slot.quantity);
154 }
155 return total;
156 }
157
158 function pendingClaimedQuantity (pendingBrew, itemId, instance)
159 {
160 const key = JSON.stringify(instance ?? null);
161 let total = 0;
162 for (const row of pendingBrew ?? [])
163 {
164 if (row.itemId !== itemId)
165 { continue; }
166 if (JSON.stringify(row.instance ?? null) !== key)
167 { continue; }
168 total += row.quantity | 0;
169 }
170 return total;
171 }
172
173 function addPendingBrew (session, brewRow)
174 {
175 const existing = session.pendingBrew.find((row) =>
176 row.itemId === brewRow.itemId
177 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
178 if (existing)
179 { existing.quantity += brewRow.quantity; }
180 else
181 { session.pendingBrew.push(brewRow); }
182 }
183
184 function refundStacks (inventory, rows)
185 {
186 for (const row of rows ?? [])
187 {
188 const def = itemDefinition(row.itemId);
189 const refund = insertStack(inventory.slots, {
190 itemId: row.itemId,
191 quantity: row.quantity,
192 instance: row.instance ? structuredClone(row.instance) : null
193 }, def);
194 if (refund.ok)
195 { inventory.slots = refund.slots; }
196 }
197 }
198
166 199 export function handleAlchemyCommand (world, sessionId, command)
167 200 {
168 201 switch (command.type)
@@ -170,11 +203,11 @@ export function handleAlchemyCommand (world, sessionId, command)
170 203 case "open-cauldron":
171 204 return openCauldron(world, sessionId, command);
172 205 case "cauldron-set-slot":
173 return setSlot(world, sessionId, command);
174 206 case "cauldron-set-dye-slot":
175 return setDyeSlot(world, sessionId, command);
207 // Slot UI is client-only; ignore mutations, echo session for sync.
208 return echoSession(world, sessionId, command);
176 209 case "cauldron-insert":
177 return insertFromSlot(world, sessionId, command);
210 return insertIngredient(world, sessionId, command);
178 211 case "cauldron-action":
179 212 return action(world, sessionId, command);
180 213 case "cauldron-bottle":
@@ -194,6 +227,19 @@ export function handleAlchemyCommand (world, sessionId, command)
194 227 }
195 228 }
196 229
230 function echoSession (world, sessionId, command)
231 {
232 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
233 requireNearCauldron(world, handle);
234 const session = requireSession(world, command.characterId);
235 return {
236 events: [],
237 private: bagView(world.ecs, handle),
238 cauldron: true,
239 cauldronState: sessionView(session)
240 };
241 }
242
197 243 function openCauldron (world, sessionId, command)
198 244 {
199 245 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -203,7 +249,11 @@ function openCauldron (world, sessionId, command)
203 249 { throw userError("I don't have any empty bottles."); }
204 250
205 251 const sessions = ensureSessions(world);
206 const existing = normalizeSession(sessions.get(command.characterId) ?? emptySession());
252 const existing = sessions.get(command.characterId) ?? emptySession();
253 if (!Array.isArray(existing.pendingBrew))
254 { existing.pendingBrew = []; }
255 if (!Array.isArray(existing.steps))
256 { existing.steps = []; }
207 257 sessions.set(command.characterId, existing);
208 258 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
209 259 return {
@@ -217,31 +267,21 @@ function openCauldron (world, sessionId, command)
217 267 function closeCauldron (world, sessionId, command)
218 268 {
219 269 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
270 // Soft claims only — bag never held station items.
220 271 ensureSessions(world).delete(command.characterId);
221 272 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
222 273 }
223 274
224 function setSlot (world, sessionId, command)
275 function insertIngredient (world, sessionId, command)
225 276 {
226 277 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
227 278 requireNearCauldron(world, handle);
228 279 const session = requireSession(world, command.characterId);
229 const slotIndex = command.slotIndex | 0;
230 if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT)
231 { throw userError("Invalid cauldron slot."); }
232 280
233 281 const itemId = command.itemId | 0;
234 282 const quantity = Math.max(0, command.quantity | 0);
235 283 if (!itemId || quantity <= 0)
236 {
237 session.slots[slotIndex] = null;
238 return {
239 events: [],
240 private: bagView(world.ecs, handle),
241 cauldron: true,
242 cauldronState: sessionView(session)
243 };
244 }
284 { throw userError("Nothing to insert."); }
245 285
246 286 const def = itemDefinition(itemId);
247 287 if (!def || def.uniqueInstance || def.equipment
@@ -249,114 +289,17 @@ function setSlot (world, sessionId, command)
249 289 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
250 290 { throw userError("Use the Dyes tab for flowers."); }
251 291
292 const instance = command.instance ? structuredClone(command.instance) : null;
252 293 const inventory = ensureInventory(world, handle);
253 const have = countItemInSlots(inventory.slots, itemId);
254 if (have < quantity)
294 const have = instance
295 ? countMatchingInstance(inventory.slots, itemId, instance)
296 : countItemInSlots(inventory.slots, itemId);
297 const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance);
298 if (have < alreadyClaimed + quantity)
255 299 { throw userError("Not enough of that item in your inventory."); }
256 300
257 session.slots[slotIndex] = { itemId, quantity, instance: null };
258 return {
259 events: [],
260 private: bagView(world.ecs, handle),
261 cauldron: true,
262 cauldronState: sessionView(session)
263 };
264 }
265
266 function setDyeSlot (world, sessionId, command)
267 {
268 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
269 requireNearCauldron(world, handle);
270 const session = requireSession(world, command.characterId);
271 const slotIndex = command.slotIndex | 0;
272 if (slotIndex < 0 || slotIndex >= DYE_CAULDRON_SLOT_COUNT)
273 { throw userError("Invalid dye slot."); }
274
275 const itemId = command.itemId | 0;
276 const quantity = Math.max(0, command.quantity | 0);
277 if (!itemId || quantity <= 0)
278 {
279 session.dyeSlots[slotIndex] = null;
280 return {
281 events: [],
282 private: bagView(world.ecs, handle),
283 cauldron: true,
284 cauldronState: sessionView(session)
285 };
286 }
287
288 if (itemId !== ItemId.flower)
289 { throw userError("Only flowers go in dye slots."); }
290
291 const inventory = ensureInventory(world, handle);
292 const wanted = command.instance ? structuredClone(command.instance) : null;
293 let instance = wanted;
294 if (!instance)
295 {
296 for (const slot of inventory.slots)
297 {
298 if (slot?.itemId === ItemId.flower && slot.instance)
299 {
300 instance = structuredClone(slot.instance);
301 break;
302 }
303 }
304 }
305 if (!instance?.color)
306 { throw userError("That flower has no colour."); }
307
308 const have = countMatchingInstance(inventory.slots, ItemId.flower, instance);
309 if (have < quantity)
310 { throw userError("Not enough of that flower in your inventory."); }
311
312 session.dyeSlots[slotIndex] = { itemId: ItemId.flower, quantity, instance };
313 return {
314 events: [],
315 private: bagView(world.ecs, handle),
316 cauldron: true,
317 cauldronState: sessionView(session)
318 };
319 }
320
321 function insertFromSlot (world, sessionId, command)
322 {
323 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
324 requireNearCauldron(world, handle);
325 const session = requireSession(world, command.characterId);
326 const slotIndex = command.slotIndex | 0;
327 const reserved = session.slots[slotIndex];
328 if (!reserved)
329 { throw userError("That cauldron slot is empty."); }
330
331 const inventory = ensureInventory(world, handle);
332 const pulled = takeMatchingFromSlots(inventory.slots, {
333 itemId: reserved.itemId,
334 quantity: reserved.quantity,
335 instance: reserved.instance ?? null,
336 compact: false
337 });
338 if (!pulled.ok)
339 { throw userError("Not enough of that item in your inventory."); }
340 inventory.slots = pulled.slots;
341 session.slots[slotIndex] = null;
342
343 const brewRow = {
344 itemId: reserved.itemId,
345 quantity: reserved.quantity,
346 instance: reserved.instance
347 ? structuredClone(reserved.instance)
348 : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null)
349 };
350
351 const existing = session.brew.find((row) =>
352 row.itemId === brewRow.itemId
353 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
354 if (existing)
355 { existing.quantity += brewRow.quantity; }
356 else
357 { session.brew.push(brewRow); }
358
359 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
301 addPendingBrew(session, { itemId, quantity, instance });
302 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
360 303 session.lastSuccessRecipe = null;
361 304
362 305 return {
@@ -392,7 +335,7 @@ function bottle (world, sessionId, command)
392 335 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
393 336 requireNearCauldron(world, handle);
394 337 const session = requireSession(world, command.characterId);
395 if (!(session.brew?.length > 0) && !(session.steps?.length > 0))
338 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
396 339 { throw userError("The cauldron is empty."); }
397 340
398 341 const inventory = ensureInventory(world, handle);
@@ -400,7 +343,7 @@ function bottle (world, sessionId, command)
400 343
401 344 const evaluation = evaluateAlchemyBottle({
402 345 skills,
403 brewStacks: session.brew,
346 brewStacks: session.pendingBrew,
404 347 takenSteps: session.steps,
405 348 potions: resolvedAlchemyPotions()
406 349 });
@@ -411,13 +354,39 @@ function bottle (world, sessionId, command)
411 354 if (produced <= 0)
412 355 { throw userError("You need glass bottles to bottle the brew."); }
413 356
357 for (const row of session.pendingBrew ?? [])
358 {
359 const have = row.instance
360 ? countMatchingInstance(inventory.slots, row.itemId, row.instance)
361 : countItemInSlots(inventory.slots, row.itemId);
362 if (have < (row.quantity | 0))
363 { throw userError("Not enough of that item in your inventory."); }
364 }
365
366 // Consume soft-claimed ingredients only now (success path).
367 for (const row of session.pendingBrew ?? [])
368 {
369 const pulled = takeMatchingFromSlots(inventory.slots, {
370 itemId: row.itemId,
371 quantity: row.quantity,
372 instance: row.instance ?? null,
373 compact: false
374 });
375 if (!pulled.ok)
376 { throw userError("Not enough of that item in your inventory."); }
377 inventory.slots = pulled.slots;
378 }
379
414 380 const takeBottles = takeMatchingFromSlots(inventory.slots, {
415 381 itemId: ItemId.glassBottle,
416 382 quantity: produced,
417 383 compact: false
418 384 });
419 385 if (!takeBottles.ok)
420 { throw userError("You need glass bottles to bottle the brew."); }
386 {
387 refundStacks(inventory, session.pendingBrew);
388 throw userError("You need glass bottles to bottle the brew.");
389 }
421 390 inventory.slots = takeBottles.slots;
422 391
423 392 const instance = potionItemInstance(evaluation.result);
@@ -431,11 +400,12 @@ function bottle (world, sessionId, command)
431 400 }), potionDef);
432 401 if (!inserted.ok)
433 402 {
434 const refund = insertStack(inventory.slots, {
403 refundStacks(inventory, session.pendingBrew);
404 const refundBottles = insertStack(inventory.slots, {
435 405 itemId: ItemId.glassBottle,
436 406 quantity: produced
437 407 }, itemDefinition(ItemId.glassBottle));
438 inventory.slots = refund.ok ? refund.slots : inventory.slots;
408 inventory.slots = refundBottles.ok ? refundBottles.slots : inventory.slots;
439 409 throw userError("Not enough inventory space for potions.");
440 410 }
441 411 inventory.slots = inserted.slots;
@@ -469,8 +439,9 @@ function createDye (world, sessionId, command)
469 439 {
470 440 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
471 441 requireNearCauldron(world, handle);
472 const session = requireSession(world, command.characterId);
473 const rows = (session.dyeSlots ?? []).filter((slot) => slot?.itemId === ItemId.flower);
442 requireSession(world, command.characterId);
443
444 const rows = normalizeFlowerRows(command.flowers);
474 445 if (!rows.length)
475 446 { throw userError("Add flowers to make dye."); }
476 447
@@ -487,7 +458,7 @@ function createDye (world, sessionId, command)
487 458 events: [],
488 459 private: bagView(world.ecs, handle),
489 460 cauldron: true,
490 cauldronState: sessionView(session),
461 cauldronState: sessionView(requireSession(world, command.characterId)),
491 462 dyeConfirm: {
492 463 wanted,
493 464 bottles,
@@ -500,6 +471,13 @@ function createDye (world, sessionId, command)
500 471 if (produced <= 0)
501 472 { throw userError("You need glass bottles to bottle the dye."); }
502 473
474 for (const row of rows)
475 {
476 const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance);
477 if (have < row.quantity)
478 { throw userError("Not enough of those flowers in your inventory."); }
479 }
480
503 481 for (const row of rows)
504 482 {
505 483 const pulled = takeMatchingFromSlots(inventory.slots, {
@@ -531,17 +509,14 @@ function createDye (world, sessionId, command)
531 509 origins: [{ origin, quantity: produced }]
532 510 }), dyeDef);
533 511 if (!inserted.ok)
534 {
535 throw userError("Not enough inventory space for dye.");
536 }
512 { throw userError("Not enough inventory space for dye."); }
537 513 inventory.slots = inserted.slots;
538 clearDyeSlots(session);
539 514
540 515 return {
541 516 events: [],
542 517 private: bagView(world.ecs, handle),
543 518 cauldron: true,
544 cauldronState: sessionView(session),
519 cauldronState: sessionView(requireSession(world, command.characterId)),
545 520 alchemyResult: {
546 521 success: true,
547 522 reason: null,
@@ -559,6 +534,25 @@ function createDye (world, sessionId, command)
559 534 };
560 535 }
561 536
537 function normalizeFlowerRows (flowers)
538 {
539 if (!Array.isArray(flowers))
540 { return []; }
541 const rows = [];
542 for (const entry of flowers)
543 {
544 const itemId = entry?.itemId | 0;
545 const quantity = Math.max(0, entry?.quantity | 0);
546 if (itemId !== ItemId.flower || quantity <= 0)
547 { continue; }
548 const instance = entry.instance ? structuredClone(entry.instance) : null;
549 if (!instance?.color)
550 { continue; }
551 rows.push({ itemId: ItemId.flower, quantity, instance });
552 }
553 return rows;
554 }
555
562 556 function clear (world, sessionId, command)
563 557 {
564 558 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -579,7 +573,7 @@ function clearDye (world, sessionId, command)
579 573 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
580 574 requireNearCauldron(world, handle);
581 575 const session = requireSession(world, command.characterId);
582 clearDyeSlots(session);
576 // Dye slots are client-only; nothing to clear server-side.
583 577 return {
584 578 events: [],
585 579 private: bagView(world.ecs, handle),
@@ -637,18 +631,3 @@ function saveRecipe (world, sessionId, command)
637 631 cauldronState: sessionView(session)
638 632 };
639 633 }
640
641 function countMatchingInstance (slots, itemId, instance)
642 {
643 let total = 0;
644 const key = JSON.stringify(instance ?? null);
645 for (const slot of slots ?? [])
646 {
647 if (!slot || slot.itemId !== itemId)
648 { continue; }
649 if (JSON.stringify(slot.instance ?? null) !== key)
650 { continue; }
651 total += stackQuantity(slot.quantity);
652 }
653 return total;
654 }
@@ -33,8 +33,9 @@ import { randomUUID } from "node:crypto";
33import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
34
34
35/**
35/**
36 * Cauldron sessions live on the worker world (per character while the UI is open).
36 * Cauldron UI slot contents live on the client only.
37 * Clients send intents only; all brew outcomes are evaluated here.
37 * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance)
38 * without removing items from the bag until bottle / create-dye succeeds.
38 */
39 */
39
40
40function userError (message)
41function userError (message)
@@ -61,39 +62,21 @@ function ensureSessions (world)
61function emptySession ()
62function emptySession ()
62{
63{
63 return {
64 return {
64 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
65 /** Soft claims for alchemy inserts — still in the bag until bottle. */
65 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
66 pendingBrew: [],
66 brew: [],
67 steps: [],
67 steps: [],
68 lastSuccessRecipe: null
68 lastSuccessRecipe: null
69 };
69 };
70}
70}
71
71
72function normalizeSession (session)
73{
74 if (!Array.isArray(session.dyeSlots) || session.dyeSlots.length !== DYE_CAULDRON_SLOT_COUNT)
75 { session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null); }
76 return session;
77}
78
79function slotView (slot)
80{
81 if (!slot)
82 { return null; }
83 return {
84 itemId: slot.itemId,
85 quantity: slot.quantity | 0,
86 instance: slot.instance ? structuredClone(slot.instance) : null
87 };
88}
89
90function sessionView (session)
72function sessionView (session)
91{
73{
92 const steps = session.steps ?? [];
74 const steps = session.steps ?? [];
93 return {
75 return {
94 slots: (session.slots ?? []).map(slotView),
76 // Slots / dye slots are client-only; never authoritative on the server.
95 dyeSlots: (session.dyeSlots ?? []).map(slotView),
77 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
96 brew: (session.brew ?? []).map((row) => ({
78 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
79 brew: (session.pendingBrew ?? []).map((row) => ({
97 itemId: row.itemId,
80 itemId: row.itemId,
98 quantity: row.quantity | 0,
81 quantity: row.quantity | 0,
99 instance: row.instance ? structuredClone(row.instance) : null
82 instance: row.instance ? structuredClone(row.instance) : null
@@ -139,21 +122,15 @@ function requireSession (world, characterId)
139 const session = ensureSessions(world).get(characterId);
122 const session = ensureSessions(world).get(characterId);
140 if (!session)
123 if (!session)
141 { throw userError("Open a cauldron first."); }
124 { throw userError("Open a cauldron first."); }
142 return normalizeSession(session);
125 return session;
143}
126}
144
127
145function clearAlchemy (session)
128function clearAlchemy (session)
146{
129{
147 session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
130 session.pendingBrew = [];
148 session.brew = [];
149 session.steps = [];
131 session.steps = [];
150}
132}
151
133
152function clearDyeSlots (session)
153{
154 session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
155}
156
157function ensureInventory (world, handle)
134function ensureInventory (world, handle)
158{
135{
159 let inventory = world.ecs.get(handle, Component.inventory);
136 let inventory = world.ecs.get(handle, Component.inventory);
@@ -163,6 +140,62 @@ function ensureInventory (world, handle)
163 return inventory;
140 return inventory;
164}
141}
165
142
143function countMatchingInstance (slots, itemId, instance)
144{
145 let total = 0;
146 const key = JSON.stringify(instance ?? null);
147 for (const slot of slots ?? [])
148 {
149 if (!slot || slot.itemId !== itemId)
150 { continue; }
151 if (JSON.stringify(slot.instance ?? null) !== key)
152 { continue; }
153 total += stackQuantity(slot.quantity);
154 }
155 return total;
156}
157
158function pendingClaimedQuantity (pendingBrew, itemId, instance)
159{
160 const key = JSON.stringify(instance ?? null);
161 let total = 0;
162 for (const row of pendingBrew ?? [])
163 {
164 if (row.itemId !== itemId)
165 { continue; }
166 if (JSON.stringify(row.instance ?? null) !== key)
167 { continue; }
168 total += row.quantity | 0;
169 }
170 return total;
171}
172
173function addPendingBrew (session, brewRow)
174{
175 const existing = session.pendingBrew.find((row) =>
176 row.itemId === brewRow.itemId
177 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
178 if (existing)
179 { existing.quantity += brewRow.quantity; }
180 else
181 { session.pendingBrew.push(brewRow); }
182}
183
184function refundStacks (inventory, rows)
185{
186 for (const row of rows ?? [])
187 {
188 const def = itemDefinition(row.itemId);
189 const refund = insertStack(inventory.slots, {
190 itemId: row.itemId,
191 quantity: row.quantity,
192 instance: row.instance ? structuredClone(row.instance) : null
193 }, def);
194 if (refund.ok)
195 { inventory.slots = refund.slots; }
196 }
197}
198
166export function handleAlchemyCommand (world, sessionId, command)
199export function handleAlchemyCommand (world, sessionId, command)
167{
200{
168 switch (command.type)
201 switch (command.type)
@@ -170,11 +203,11 @@ export function handleAlchemyCommand (world, sessionId, command)
170 case "open-cauldron":
203 case "open-cauldron":
171 return openCauldron(world, sessionId, command);
204 return openCauldron(world, sessionId, command);
172 case "cauldron-set-slot":
205 case "cauldron-set-slot":
173 return setSlot(world, sessionId, command);
174 case "cauldron-set-dye-slot":
206 case "cauldron-set-dye-slot":
175 return setDyeSlot(world, sessionId, command);
207 // Slot UI is client-only; ignore mutations, echo session for sync.
208 return echoSession(world, sessionId, command);
176 case "cauldron-insert":
209 case "cauldron-insert":
177 return insertFromSlot(world, sessionId, command);
210 return insertIngredient(world, sessionId, command);
178 case "cauldron-action":
211 case "cauldron-action":
179 return action(world, sessionId, command);
212 return action(world, sessionId, command);
180 case "cauldron-bottle":
213 case "cauldron-bottle":
@@ -194,6 +227,19 @@ export function handleAlchemyCommand (world, sessionId, command)
194 }
227 }
195}
228}
196
229
230function echoSession (world, sessionId, command)
231{
232 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
233 requireNearCauldron(world, handle);
234 const session = requireSession(world, command.characterId);
235 return {
236 events: [],
237 private: bagView(world.ecs, handle),
238 cauldron: true,
239 cauldronState: sessionView(session)
240 };
241}
242
197function openCauldron (world, sessionId, command)
243function openCauldron (world, sessionId, command)
198{
244{
199 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
245 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -203,7 +249,11 @@ function openCauldron (world, sessionId, command)
203 { throw userError("I don't have any empty bottles."); }
249 { throw userError("I don't have any empty bottles."); }
204
250
205 const sessions = ensureSessions(world);
251 const sessions = ensureSessions(world);
206 const existing = normalizeSession(sessions.get(command.characterId) ?? emptySession());
252 const existing = sessions.get(command.characterId) ?? emptySession();
253 if (!Array.isArray(existing.pendingBrew))
254 { existing.pendingBrew = []; }
255 if (!Array.isArray(existing.steps))
256 { existing.steps = []; }
207 sessions.set(command.characterId, existing);
257 sessions.set(command.characterId, existing);
208 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
258 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
209 return {
259 return {
@@ -217,31 +267,21 @@ function openCauldron (world, sessionId, command)
217function closeCauldron (world, sessionId, command)
267function closeCauldron (world, sessionId, command)
218{
268{
219 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
269 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
270 // Soft claims only — bag never held station items.
220 ensureSessions(world).delete(command.characterId);
271 ensureSessions(world).delete(command.characterId);
221 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
272 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
222}
273}
223
274
224function setSlot (world, sessionId, command)
275function insertIngredient (world, sessionId, command)
225{
276{
226 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
277 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
227 requireNearCauldron(world, handle);
278 requireNearCauldron(world, handle);
228 const session = requireSession(world, command.characterId);
279 const session = requireSession(world, command.characterId);
229 const slotIndex = command.slotIndex | 0;
230 if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT)
231 { throw userError("Invalid cauldron slot."); }
232
280
233 const itemId = command.itemId | 0;
281 const itemId = command.itemId | 0;
234 const quantity = Math.max(0, command.quantity | 0);
282 const quantity = Math.max(0, command.quantity | 0);
235 if (!itemId || quantity <= 0)
283 if (!itemId || quantity <= 0)
236 {
284 { throw userError("Nothing to insert."); }
237 session.slots[slotIndex] = null;
238 return {
239 events: [],
240 private: bagView(world.ecs, handle),
241 cauldron: true,
242 cauldronState: sessionView(session)
243 };
244 }
245
285
246 const def = itemDefinition(itemId);
286 const def = itemDefinition(itemId);
247 if (!def || def.uniqueInstance || def.equipment
287 if (!def || def.uniqueInstance || def.equipment
@@ -249,114 +289,17 @@ function setSlot (world, sessionId, command)
249 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
289 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
250 { throw userError("Use the Dyes tab for flowers."); }
290 { throw userError("Use the Dyes tab for flowers."); }
251
291
292 const instance = command.instance ? structuredClone(command.instance) : null;
252 const inventory = ensureInventory(world, handle);
293 const inventory = ensureInventory(world, handle);
253 const have = countItemInSlots(inventory.slots, itemId);
294 const have = instance
254 if (have < quantity)
295 ? countMatchingInstance(inventory.slots, itemId, instance)
296 : countItemInSlots(inventory.slots, itemId);
297 const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance);
298 if (have < alreadyClaimed + quantity)
255 { throw userError("Not enough of that item in your inventory."); }
299 { throw userError("Not enough of that item in your inventory."); }
256
300
257 session.slots[slotIndex] = { itemId, quantity, instance: null };
301 addPendingBrew(session, { itemId, quantity, instance });
258 return {
302 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
259 events: [],
260 private: bagView(world.ecs, handle),
261 cauldron: true,
262 cauldronState: sessionView(session)
263 };
264}
265
266function setDyeSlot (world, sessionId, command)
267{
268 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
269 requireNearCauldron(world, handle);
270 const session = requireSession(world, command.characterId);
271 const slotIndex = command.slotIndex | 0;
272 if (slotIndex < 0 || slotIndex >= DYE_CAULDRON_SLOT_COUNT)
273 { throw userError("Invalid dye slot."); }
274
275 const itemId = command.itemId | 0;
276 const quantity = Math.max(0, command.quantity | 0);
277 if (!itemId || quantity <= 0)
278 {
279 session.dyeSlots[slotIndex] = null;
280 return {
281 events: [],
282 private: bagView(world.ecs, handle),
283 cauldron: true,
284 cauldronState: sessionView(session)
285 };
286 }
287
288 if (itemId !== ItemId.flower)
289 { throw userError("Only flowers go in dye slots."); }
290
291 const inventory = ensureInventory(world, handle);
292 const wanted = command.instance ? structuredClone(command.instance) : null;
293 let instance = wanted;
294 if (!instance)
295 {
296 for (const slot of inventory.slots)
297 {
298 if (slot?.itemId === ItemId.flower && slot.instance)
299 {
300 instance = structuredClone(slot.instance);
301 break;
302 }
303 }
304 }
305 if (!instance?.color)
306 { throw userError("That flower has no colour."); }
307
308 const have = countMatchingInstance(inventory.slots, ItemId.flower, instance);
309 if (have < quantity)
310 { throw userError("Not enough of that flower in your inventory."); }
311
312 session.dyeSlots[slotIndex] = { itemId: ItemId.flower, quantity, instance };
313 return {
314 events: [],
315 private: bagView(world.ecs, handle),
316 cauldron: true,
317 cauldronState: sessionView(session)
318 };
319}
320
321function insertFromSlot (world, sessionId, command)
322{
323 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
324 requireNearCauldron(world, handle);
325 const session = requireSession(world, command.characterId);
326 const slotIndex = command.slotIndex | 0;
327 const reserved = session.slots[slotIndex];
328 if (!reserved)
329 { throw userError("That cauldron slot is empty."); }
330
331 const inventory = ensureInventory(world, handle);
332 const pulled = takeMatchingFromSlots(inventory.slots, {
333 itemId: reserved.itemId,
334 quantity: reserved.quantity,
335 instance: reserved.instance ?? null,
336 compact: false
337 });
338 if (!pulled.ok)
339 { throw userError("Not enough of that item in your inventory."); }
340 inventory.slots = pulled.slots;
341 session.slots[slotIndex] = null;
342
343 const brewRow = {
344 itemId: reserved.itemId,
345 quantity: reserved.quantity,
346 instance: reserved.instance
347 ? structuredClone(reserved.instance)
348 : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null)
349 };
350
351 const existing = session.brew.find((row) =>
352 row.itemId === brewRow.itemId
353 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
354 if (existing)
355 { existing.quantity += brewRow.quantity; }
356 else
357 { session.brew.push(brewRow); }
358
359 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
360 session.lastSuccessRecipe = null;
303 session.lastSuccessRecipe = null;
361
304
362 return {
305 return {
@@ -392,7 +335,7 @@ function bottle (world, sessionId, command)
392 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
335 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
393 requireNearCauldron(world, handle);
336 requireNearCauldron(world, handle);
394 const session = requireSession(world, command.characterId);
337 const session = requireSession(world, command.characterId);
395 if (!(session.brew?.length > 0) && !(session.steps?.length > 0))
338 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
396 { throw userError("The cauldron is empty."); }
339 { throw userError("The cauldron is empty."); }
397
340
398 const inventory = ensureInventory(world, handle);
341 const inventory = ensureInventory(world, handle);
@@ -400,7 +343,7 @@ function bottle (world, sessionId, command)
400
343
401 const evaluation = evaluateAlchemyBottle({
344 const evaluation = evaluateAlchemyBottle({
402 skills,
345 skills,
403 brewStacks: session.brew,
346 brewStacks: session.pendingBrew,
404 takenSteps: session.steps,
347 takenSteps: session.steps,
405 potions: resolvedAlchemyPotions()
348 potions: resolvedAlchemyPotions()
406 });
349 });
@@ -411,13 +354,39 @@ function bottle (world, sessionId, command)
411 if (produced <= 0)
354 if (produced <= 0)
412 { throw userError("You need glass bottles to bottle the brew."); }
355 { throw userError("You need glass bottles to bottle the brew."); }
413
356
357 for (const row of session.pendingBrew ?? [])
358 {
359 const have = row.instance
360 ? countMatchingInstance(inventory.slots, row.itemId, row.instance)
361 : countItemInSlots(inventory.slots, row.itemId);
362 if (have < (row.quantity | 0))
363 { throw userError("Not enough of that item in your inventory."); }
364 }
365
366 // Consume soft-claimed ingredients only now (success path).
367 for (const row of session.pendingBrew ?? [])
368 {
369 const pulled = takeMatchingFromSlots(inventory.slots, {
370 itemId: row.itemId,
371 quantity: row.quantity,
372 instance: row.instance ?? null,
373 compact: false
374 });
375 if (!pulled.ok)
376 { throw userError("Not enough of that item in your inventory."); }
377 inventory.slots = pulled.slots;
378 }
379
414 const takeBottles = takeMatchingFromSlots(inventory.slots, {
380 const takeBottles = takeMatchingFromSlots(inventory.slots, {
415 itemId: ItemId.glassBottle,
381 itemId: ItemId.glassBottle,
416 quantity: produced,
382 quantity: produced,
417 compact: false
383 compact: false
418 });
384 });
419 if (!takeBottles.ok)
385 if (!takeBottles.ok)
420 { throw userError("You need glass bottles to bottle the brew."); }
386 {
387 refundStacks(inventory, session.pendingBrew);
388 throw userError("You need glass bottles to bottle the brew.");
389 }
421 inventory.slots = takeBottles.slots;
390 inventory.slots = takeBottles.slots;
422
391
423 const instance = potionItemInstance(evaluation.result);
392 const instance = potionItemInstance(evaluation.result);
@@ -431,11 +400,12 @@ function bottle (world, sessionId, command)
431 }), potionDef);
400 }), potionDef);
432 if (!inserted.ok)
401 if (!inserted.ok)
433 {
402 {
434 const refund = insertStack(inventory.slots, {
403 refundStacks(inventory, session.pendingBrew);
404 const refundBottles = insertStack(inventory.slots, {
435 itemId: ItemId.glassBottle,
405 itemId: ItemId.glassBottle,
436 quantity: produced
406 quantity: produced
437 }, itemDefinition(ItemId.glassBottle));
407 }, itemDefinition(ItemId.glassBottle));
438 inventory.slots = refund.ok ? refund.slots : inventory.slots;
408 inventory.slots = refundBottles.ok ? refundBottles.slots : inventory.slots;
439 throw userError("Not enough inventory space for potions.");
409 throw userError("Not enough inventory space for potions.");
440 }
410 }
441 inventory.slots = inserted.slots;
411 inventory.slots = inserted.slots;
@@ -469,8 +439,9 @@ function createDye (world, sessionId, command)
469{
439{
470 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
440 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
471 requireNearCauldron(world, handle);
441 requireNearCauldron(world, handle);
472 const session = requireSession(world, command.characterId);
442 requireSession(world, command.characterId);
473 const rows = (session.dyeSlots ?? []).filter((slot) => slot?.itemId === ItemId.flower);
443
444 const rows = normalizeFlowerRows(command.flowers);
474 if (!rows.length)
445 if (!rows.length)
475 { throw userError("Add flowers to make dye."); }
446 { throw userError("Add flowers to make dye."); }
476
447
@@ -487,7 +458,7 @@ function createDye (world, sessionId, command)
487 events: [],
458 events: [],
488 private: bagView(world.ecs, handle),
459 private: bagView(world.ecs, handle),
489 cauldron: true,
460 cauldron: true,
490 cauldronState: sessionView(session),
461 cauldronState: sessionView(requireSession(world, command.characterId)),
491 dyeConfirm: {
462 dyeConfirm: {
492 wanted,
463 wanted,
493 bottles,
464 bottles,
@@ -500,6 +471,13 @@ function createDye (world, sessionId, command)
500 if (produced <= 0)
471 if (produced <= 0)
501 { throw userError("You need glass bottles to bottle the dye."); }
472 { throw userError("You need glass bottles to bottle the dye."); }
502
473
474 for (const row of rows)
475 {
476 const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance);
477 if (have < row.quantity)
478 { throw userError("Not enough of those flowers in your inventory."); }
479 }
480
503 for (const row of rows)
481 for (const row of rows)
504 {
482 {
505 const pulled = takeMatchingFromSlots(inventory.slots, {
483 const pulled = takeMatchingFromSlots(inventory.slots, {
@@ -531,17 +509,14 @@ function createDye (world, sessionId, command)
531 origins: [{ origin, quantity: produced }]
509 origins: [{ origin, quantity: produced }]
532 }), dyeDef);
510 }), dyeDef);
533 if (!inserted.ok)
511 if (!inserted.ok)
534 {
512 { throw userError("Not enough inventory space for dye."); }
535 throw userError("Not enough inventory space for dye.");
536 }
537 inventory.slots = inserted.slots;
513 inventory.slots = inserted.slots;
538 clearDyeSlots(session);
539
514
540 return {
515 return {
541 events: [],
516 events: [],
542 private: bagView(world.ecs, handle),
517 private: bagView(world.ecs, handle),
543 cauldron: true,
518 cauldron: true,
544 cauldronState: sessionView(session),
519 cauldronState: sessionView(requireSession(world, command.characterId)),
545 alchemyResult: {
520 alchemyResult: {
546 success: true,
521 success: true,
547 reason: null,
522 reason: null,
@@ -559,6 +534,25 @@ function createDye (world, sessionId, command)
559 };
534 };
560}
535}
561
536
537function normalizeFlowerRows (flowers)
538{
539 if (!Array.isArray(flowers))
540 { return []; }
541 const rows = [];
542 for (const entry of flowers)
543 {
544 const itemId = entry?.itemId | 0;
545 const quantity = Math.max(0, entry?.quantity | 0);
546 if (itemId !== ItemId.flower || quantity <= 0)
547 { continue; }
548 const instance = entry.instance ? structuredClone(entry.instance) : null;
549 if (!instance?.color)
550 { continue; }
551 rows.push({ itemId: ItemId.flower, quantity, instance });
552 }
553 return rows;
554}
555
562function clear (world, sessionId, command)
556function clear (world, sessionId, command)
563{
557{
564 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
558 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -579,7 +573,7 @@ function clearDye (world, sessionId, command)
579 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
573 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
580 requireNearCauldron(world, handle);
574 requireNearCauldron(world, handle);
581 const session = requireSession(world, command.characterId);
575 const session = requireSession(world, command.characterId);
582 clearDyeSlots(session);
576 // Dye slots are client-only; nothing to clear server-side.
583 return {
577 return {
584 events: [],
578 events: [],
585 private: bagView(world.ecs, handle),
579 private: bagView(world.ecs, handle),
@@ -637,18 +631,3 @@ function saveRecipe (world, sessionId, command)
637 cauldronState: sessionView(session)
631 cauldronState: sessionView(session)
638 };
632 };
639}
633}
640
641function countMatchingInstance (slots, itemId, instance)
642{
643 let total = 0;
644 const key = JSON.stringify(instance ?? null);
645 for (const slot of slots ?? [])
646 {
647 if (!slot || slot.itemId !== itemId)
648 { continue; }
649 if (JSON.stringify(slot.instance ?? null) !== key)
650 { continue; }
651 total += stackQuantity(slot.quantity);
652 }
653 return total;
654}
server/src/gateway/websocket.js +5 −2
@@ -383,7 +383,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
383 383 simulation.enqueue(session.id, {
384 384 type: "cauldron-insert",
385 385 characterId: session.characterId,
386 slotIndex: message.slotIndex | 0
386 itemId: message.itemId | 0,
387 quantity: message.quantity | 0,
388 instance: message.instance ?? null
387 389 });
388 390 break;
389 391 case MessageType.cauldronAction:
@@ -406,7 +408,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
406 408 simulation.enqueue(session.id, {
407 409 type: "cauldron-create-dye",
408 410 characterId: session.characterId,
409 confirmOverflow: !!message.confirmOverflow
411 confirmOverflow: !!message.confirmOverflow,
412 flowers: Array.isArray(message.flowers) ? message.flowers : []
410 413 });
411 414 break;
412 415 case MessageType.cauldronClear:
@@ -383,7 +383,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
383 simulation.enqueue(session.id, {
383 simulation.enqueue(session.id, {
384 type: "cauldron-insert",
384 type: "cauldron-insert",
385 characterId: session.characterId,
385 characterId: session.characterId,
386 slotIndex: message.slotIndex | 0
386 itemId: message.itemId | 0,
387 quantity: message.quantity | 0,
388 instance: message.instance ?? null
387 });
389 });
388 break;
390 break;
389 case MessageType.cauldronAction:
391 case MessageType.cauldronAction:
@@ -406,7 +408,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
406 simulation.enqueue(session.id, {
408 simulation.enqueue(session.id, {
407 type: "cauldron-create-dye",
409 type: "cauldron-create-dye",
408 characterId: session.characterId,
410 characterId: session.characterId,
409 confirmOverflow: !!message.confirmOverflow
411 confirmOverflow: !!message.confirmOverflow,
412 flowers: Array.isArray(message.flowers) ? message.flowers : []
410 });
413 });
411 break;
414 break;
412 case MessageType.cauldronClear:
415 case MessageType.cauldronClear:
server/tests/alchemy.test.js +65 −13
@@ -107,37 +107,39 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
107 107 harness.simulation.step();
108 108
109 109 harness.simulation.enqueue(1, {
110 type: "cauldron-set-slot",
110 type: "cauldron-insert",
111 111 characterId: cid,
112 slotIndex: 0,
113 112 itemId: ItemId.thyme,
114 113 quantity: 2
115 114 });
116 115 harness.simulation.enqueue(1, {
117 type: "cauldron-set-slot",
116 type: "cauldron-action",
118 117 characterId: cid,
119 slotIndex: 1,
120 itemId: ItemId.mint,
121 quantity: 2
118 action: AlchemyStepKind.heat
122 119 });
123 harness.simulation.step();
124
125 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
126 120 harness.simulation.enqueue(1, {
127 type: "cauldron-action",
121 type: "cauldron-insert",
128 122 characterId: cid,
129 action: AlchemyStepKind.heat
123 itemId: ItemId.mint,
124 quantity: 2
130 125 });
131 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
132 126 harness.simulation.enqueue(1, {
133 127 type: "cauldron-action",
134 128 characterId: cid,
135 129 action: AlchemyStepKind.stir
136 130 });
131 harness.simulation.step();
132
133 // Soft claims only — ingredients stay in the bag until bottle.
134 let bag = harness.simulation.bagOf(entityId);
135 assert.equal(countItem(bag.inventory, ItemId.thyme), 2);
136 assert.equal(countItem(bag.inventory, ItemId.mint), 2);
137 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 2);
138
137 139 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
138 140 harness.simulation.step();
139 141
140 const bag = harness.simulation.bagOf(entityId);
142 bag = harness.simulation.bagOf(entityId);
141 143 assert.equal(countItem(bag.inventory, ItemId.thyme), 0);
142 144 assert.equal(countItem(bag.inventory, ItemId.mint), 0);
143 145 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
@@ -161,6 +163,56 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
161 163 { harness.close(); }
162 164 });
163 165
166 test("cauldron clear / close after insert does not consume ingredients", () =>
167 {
168 const harness = makeSimulation({ workerCount: 1 });
169 try
170 {
171 placeCauldron(harness.worldDb, 8, 8);
172 harness.simulation.reloadWorld();
173 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
174 const inventory = emptySlots();
175 inventory[0] = { itemId: ItemId.thyme, quantity: 2 };
176 inventory[1] = { itemId: ItemId.glassBottle, quantity: 1 };
177 harness.stateDb.saveBag(character.character_id, {
178 inventory,
179 equipment: emptyEquipment(),
180 vault: [],
181 vaultReserved: []
182 });
183 const entityId = harness.simulation.spawnCharacter(1, character);
184 const cid = character.character_id;
185
186 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
187 harness.simulation.step();
188 harness.simulation.enqueue(1, {
189 type: "cauldron-insert",
190 characterId: cid,
191 itemId: ItemId.thyme,
192 quantity: 2
193 });
194 harness.simulation.step();
195 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.thyme), 2);
196
197 harness.simulation.enqueue(1, { type: "cauldron-clear", characterId: cid });
198 harness.simulation.step();
199 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.thyme), 2);
200
201 harness.simulation.enqueue(1, {
202 type: "cauldron-insert",
203 characterId: cid,
204 itemId: ItemId.thyme,
205 quantity: 2
206 });
207 harness.simulation.step();
208 harness.simulation.enqueue(1, { type: "cauldron-close", characterId: cid });
209 harness.simulation.step();
210 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.thyme), 2);
211 }
212 finally
213 { harness.close(); }
214 });
215
164 216 test("drinking a lesser health tonic applies health regen", () =>
165 217 {
166 218 const harness = makeSimulation({ workerCount: 1 });
@@ -107,37 +107,39 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
107 harness.simulation.step();
107 harness.simulation.step();
108
108
109 harness.simulation.enqueue(1, {
109 harness.simulation.enqueue(1, {
110 type: "cauldron-set-slot",
110 type: "cauldron-insert",
111 characterId: cid,
111 characterId: cid,
112 slotIndex: 0,
113 itemId: ItemId.thyme,
112 itemId: ItemId.thyme,
114 quantity: 2
113 quantity: 2
115 });
114 });
116 harness.simulation.enqueue(1, {
115 harness.simulation.enqueue(1, {
117 type: "cauldron-set-slot",
116 type: "cauldron-action",
118 characterId: cid,
117 characterId: cid,
119 slotIndex: 1,
118 action: AlchemyStepKind.heat
120 itemId: ItemId.mint,
121 quantity: 2
122 });
119 });
123 harness.simulation.step();
124
125 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
126 harness.simulation.enqueue(1, {
120 harness.simulation.enqueue(1, {
127 type: "cauldron-action",
121 type: "cauldron-insert",
128 characterId: cid,
122 characterId: cid,
129 action: AlchemyStepKind.heat
123 itemId: ItemId.mint,
124 quantity: 2
130 });
125 });
131 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
132 harness.simulation.enqueue(1, {
126 harness.simulation.enqueue(1, {
133 type: "cauldron-action",
127 type: "cauldron-action",
134 characterId: cid,
128 characterId: cid,
135 action: AlchemyStepKind.stir
129 action: AlchemyStepKind.stir
136 });
130 });
131 harness.simulation.step();
132
133 // Soft claims only — ingredients stay in the bag until bottle.
134 let bag = harness.simulation.bagOf(entityId);
135 assert.equal(countItem(bag.inventory, ItemId.thyme), 2);
136 assert.equal(countItem(bag.inventory, ItemId.mint), 2);
137 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 2);
138
137 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
139 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
138 harness.simulation.step();
140 harness.simulation.step();
139
141
140 const bag = harness.simulation.bagOf(entityId);
142 bag = harness.simulation.bagOf(entityId);
141 assert.equal(countItem(bag.inventory, ItemId.thyme), 0);
143 assert.equal(countItem(bag.inventory, ItemId.thyme), 0);
142 assert.equal(countItem(bag.inventory, ItemId.mint), 0);
144 assert.equal(countItem(bag.inventory, ItemId.mint), 0);
143 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
145 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
@@ -161,6 +163,56 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
161 { harness.close(); }
163 { harness.close(); }
162});
164});
163
165
166test("cauldron clear / close after insert does not consume ingredients", () =>
167{
168 const harness = makeSimulation({ workerCount: 1 });
169 try
170 {
171 placeCauldron(harness.worldDb, 8, 8);
172 harness.simulation.reloadWorld();
173 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
174 const inventory = emptySlots();
175 inventory[0] = { itemId: ItemId.thyme, quantity: 2 };
176 inventory[1] = { itemId: ItemId.glassBottle, quantity: 1 };
177 harness.stateDb.saveBag(character.character_id, {
178 inventory,
179 equipment: emptyEquipment(),
180 vault: [],
181 vaultReserved: []
182 });
183 const entityId = harness.simulation.spawnCharacter(1, character);
184 const cid = character.character_id;
185
186 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
187 harness.simulation.step();
188 harness.simulation.enqueue(1, {
189 type: "cauldron-insert",
190 characterId: cid,
191 itemId: ItemId.thyme,
192 quantity: 2
193 });
194 harness.simulation.step();
195 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.thyme), 2);
196
197 harness.simulation.enqueue(1, { type: "cauldron-clear", characterId: cid });
198 harness.simulation.step();
199 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.thyme), 2);
200
201 harness.simulation.enqueue(1, {
202 type: "cauldron-insert",
203 characterId: cid,
204 itemId: ItemId.thyme,
205 quantity: 2
206 });
207 harness.simulation.step();
208 harness.simulation.enqueue(1, { type: "cauldron-close", characterId: cid });
209 harness.simulation.step();
210 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.thyme), 2);
211 }
212 finally
213 { harness.close(); }
214});
215
164test("drinking a lesser health tonic applies health regen", () =>
216test("drinking a lesser health tonic applies health regen", () =>
165{
217{
166 const harness = makeSimulation({ workerCount: 1 });
218 const harness = makeSimulation({ workerCount: 1 });