From 132cb273d53ad5cfbfa5983e15fc4cfd938fcce9 Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Mon, 28 Sep 2026 12:15:08 +0000
Subject: [PATCH 1/3] feat: chemical boil spit (spray + mass loss)
Route instant chemical heat through apply_chemical_heat; when T would
cross boil, clamp, discard CHEMICAL_SPIT_FRAC, emit one silent spit
event, and play a CSS spray cue on the action target (no teaching banner).
Co-authored-by: Arnoud
---
apps/web/src/components/LabBench.tsx | 25 +++-
apps/web/src/components/LabBenchIcons.tsx | 14 +++
apps/web/src/components/labBenchScene.test.ts | 16 +++
apps/web/src/components/labBenchScene.ts | 12 ++
apps/web/src/index.css | 60 +++++++++
crates/chemlab-core/src/acid_base.rs | 23 ++--
crates/chemlab-core/src/aqueous_pipeline.rs | 44 ++++---
crates/chemlab-core/src/dissolve_kinetics.rs | 30 +++--
crates/chemlab-core/src/lib.rs | 10 +-
crates/chemlab-core/src/scene.rs | 117 +++++++++++++-----
crates/chemlab-core/src/scene_tests/h2so4.rs | 115 +++++++++++++++++
crates/chemlab-core/src/thermal.rs | 11 +-
docs/lab-scene-spec.md | 10 +-
13 files changed, 391 insertions(+), 96 deletions(-)
diff --git a/apps/web/src/components/LabBench.tsx b/apps/web/src/components/LabBench.tsx
index b2c92c7..0b97054 100644
--- a/apps/web/src/components/LabBench.tsx
+++ b/apps/web/src/components/LabBench.tsx
@@ -64,6 +64,8 @@ import {
burnerIsOn,
dishAmountMl,
dissolveCueFromEvents,
+ spitCueFromEvents,
+ bannerEventsFromLastEvents,
distilledWaterAmountMl,
hclStockAmountMl,
h2so4StockAmountMl,
@@ -140,6 +142,8 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
const [pointer, setPointer] = useState<{ x: number; y: number } | null>(null)
const [stockCarouselIndex, setStockCarouselIndex] = useState(0)
const [toolCarouselIndex, setToolCarouselIndex] = useState(0)
+ /** Last action vessel id — spit CSS burst target (dissolve-cue pattern). */
+ const [lastActionTargetId, setLastActionTargetId] = useState(null)
const burnerOn = scene ? burnerIsOn(scene) : false
const needsClockPoll = scene ? sceneNeedsClockPoll(scene) : false
@@ -275,6 +279,7 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
tool_item_id: toolItemId,
target_item_id: targetItemId,
})
+ setLastActionTargetId(targetItemId)
setScene(response.scene)
} catch (err) {
setError(err instanceof Error ? err.message : 'Action failed')
@@ -293,6 +298,7 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
source_item_id: sourceItemId,
target_item_id: targetItemId,
})
+ setLastActionTargetId(targetItemId)
setScene(response.scene)
} catch (err) {
setError(err instanceof Error ? err.message : 'Action failed')
@@ -467,6 +473,9 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
const paperHeld = paper?.location === 'held'
const lastEvents = scene ? optionalArray(scene.last_events) : []
const dissolveCue = dissolveCueFromEvents(lastEvents)
+ const hasSpitCue = spitCueFromEvents(lastEvents)
+ const spitTargetId = hasSpitCue ? lastActionTargetId : null
+ const bannerEvents = bannerEventsFromLastEvents(lastEvents)
const hasAqueous = scene ? waterHasAqueous(scene) : false
const inspectItem = scene && inspectItemId ? findItem(scene, inspectItemId) : undefined
const pipetteFilled = scene ? pipetteIsFilled(scene) : false
@@ -597,10 +606,11 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
) : null}
- {lastEvents.length > 0 ? (
+ {bannerEvents.length > 0 ? (
{dissolveCue ? (
vo
{': '}
{dissolveCue === 'dissolved'
- ? lastEvents.find((event) => event.kind === 'dissolved')?.message
- : lastEvents.find((event) => event.kind === 'did_not_dissolve')?.message}
+ ? bannerEvents.find((event) => event.kind === 'dissolved')?.message
+ : bannerEvents.find((event) => event.kind === 'did_not_dissolve')?.message}
) : (
- lastEvents.map((event, index) => {
+ bannerEvents.map((event, index) => {
const outcome = outcomeLabel(event.kind)
return (
{outcome ? (
{outcome}
) : null}
-
{event.message}
+ {event.message ? (
+
{event.message}
+ ) : null}
)
})
diff --git a/apps/web/src/components/LabBenchIcons.tsx b/apps/web/src/components/LabBenchIcons.tsx
index e3c3d2f..ad4798b 100644
--- a/apps/web/src/components/LabBenchIcons.tsx
+++ b/apps/web/src/components/LabBenchIcons.tsx
@@ -22,6 +22,7 @@ export function WaterBeakerSvg({
amountMl,
hasAqueous,
dissolveCue,
+ spitCue,
floating,
}: {
leftoverSolid: StockSolid | null
@@ -31,6 +32,8 @@ export function WaterBeakerSvg({
hasAqueous?: boolean
/** Latest dissolve-related kind from scene `last_events`. */
dissolveCue?: 'dissolved' | 'did_not_dissolve' | null
+ /** Silent chemical spit burst from server `last_events`. */
+ spitCue?: boolean
floating?: boolean
}) {
const fill = waterFillRatio(amountMl)
@@ -55,6 +58,7 @@ export function WaterBeakerSvg({
data-water-fill={fill.toFixed(2)}
data-water-aqueous={hasAqueous ? 'true' : 'false'}
data-dissolve-cue={dissolveCue ?? 'none'}
+ data-spit-cue={spitCue ? 'burst' : 'none'}
>
@@ -105,6 +109,16 @@ export function WaterBeakerSvg({
) : null}
+ {spitCue ? (
+
+
+
+
+
+
+
+
+ ) : null}
)
diff --git a/apps/web/src/components/labBenchScene.test.ts b/apps/web/src/components/labBenchScene.test.ts
index 4d2f982..4d2fd6c 100644
--- a/apps/web/src/components/labBenchScene.test.ts
+++ b/apps/web/src/components/labBenchScene.test.ts
@@ -22,6 +22,8 @@ import {
sceneNeedsDissolvePoll,
sceneNeedsThermalPoll,
solutionVolumeMl,
+ spitCueFromEvents,
+ bannerEventsFromLastEvents,
tongsHeldVesselId,
waterAmountMl,
} from './labBenchScene'
@@ -325,3 +327,17 @@ describe('clock poll gates', () => {
expect(sceneNeedsClockPoll(sandOnly)).toBe(false)
})
})
+
+describe('chemical spit cues', () => {
+ it('detects spit and suppresses it from the banner list', () => {
+ const events = [
+ { kind: 'poured', message: 'Emptied the pipette into the vessel.' },
+ { kind: 'spit', message: '' },
+ ]
+ expect(spitCueFromEvents(events)).toBe(true)
+ expect(bannerEventsFromLastEvents(events)).toEqual([
+ { kind: 'poured', message: 'Emptied the pipette into the vessel.' },
+ ])
+ expect(spitCueFromEvents([{ kind: 'poured', message: 'ok' }])).toBe(false)
+ })
+})
diff --git a/apps/web/src/components/labBenchScene.ts b/apps/web/src/components/labBenchScene.ts
index 756677d..e034b1c 100644
--- a/apps/web/src/components/labBenchScene.ts
+++ b/apps/web/src/components/labBenchScene.ts
@@ -165,6 +165,18 @@ export function dissolveCueFromEvents(
return null
}
+/** True when the last action emitted a silent chemical spit (visual-only). */
+export function spitCueFromEvents(events: { kind: string; message: string }[]): boolean {
+ return events.some((event) => event.kind === 'spit')
+}
+
+/** Banner events — suppress silent spit (empty teaching copy by design). */
+export function bannerEventsFromLastEvents(
+ events: { kind: string; message: string }[],
+): { kind: string; message: string }[] {
+ return events.filter((event) => event.kind !== 'spit')
+}
+
/** Dish liquid height — Φ_V solution volume (matches server `fill_ml`), not water-only ml. */
export function dishAmountMl(scene: LabScene): number | null {
const item = findItem(scene, DISH_ID)
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index b64f3fd..7d14b39 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -282,6 +282,46 @@ body::before {
filter: saturate(1.15);
}
+.lab-item--spit-cue {
+ position: relative;
+}
+
+.lab-spit-drop {
+ opacity: 0;
+ animation: spit-burst 0.85s ease-out 1;
+}
+
+.lab-spit-drop--1 {
+ animation-delay: 0ms;
+ --spit-dx: -10px;
+ --spit-dy: -28px;
+}
+.lab-spit-drop--2 {
+ animation-delay: 40ms;
+ --spit-dx: 4px;
+ --spit-dy: -34px;
+}
+.lab-spit-drop--3 {
+ animation-delay: 70ms;
+ --spit-dx: 16px;
+ --spit-dy: -24px;
+}
+.lab-spit-drop--4 {
+ animation-delay: 20ms;
+ --spit-dx: -18px;
+ --spit-dy: -36px;
+}
+.lab-spit-drop--5 {
+ animation-delay: 90ms;
+ --spit-dx: 22px;
+ --spit-dy: -40px;
+}
+.lab-spit-drop--6 {
+ animation-delay: 55ms;
+ --spit-dx: 0px;
+ --spit-dy: -44px;
+}
+
.lab-bench-status {
letter-spacing: 0.01em;
}
@@ -298,6 +338,21 @@ body::before {
}
}
+@keyframes spit-burst {
+ 0% {
+ opacity: 0.95;
+ transform: translate(0, 0) scale(1);
+ }
+ 70% {
+ opacity: 0.55;
+ transform: translate(var(--spit-dx), var(--spit-dy)) scale(0.7);
+ }
+ 100% {
+ opacity: 0;
+ transform: translate(var(--spit-dx), calc(var(--spit-dy) - 8px)) scale(0.35);
+ }
+}
+
@media (prefers-reduced-motion: reduce) {
.lab-water-busy {
animation: none;
@@ -306,6 +361,11 @@ body::before {
.lab-water-dissolved-cue {
animation: none;
}
+
+ .lab-spit-drop {
+ animation: none;
+ opacity: 0.55;
+ }
}
@media (prefers-reduced-motion: reduce) {
diff --git a/crates/chemlab-core/src/acid_base.rs b/crates/chemlab-core/src/acid_base.rs
index 3970c8f..9376821 100644
--- a/crates/chemlab-core/src/acid_base.rs
+++ b/crates/chemlab-core/src/acid_base.rs
@@ -13,8 +13,7 @@
use crate::composition::{aqueous_mol, liquid_water_ml, set_aqueous_mol};
use crate::scene::{
- effective_heat_capacity, CompositionEntry, SceneItem, AMBIENT_TEMPERATURE_C,
- H_OH_NEUTRALIZATION_J_PER_MOL, WATER_MOLAR_MASS_G_PER_MOL,
+ CompositionEntry, SceneItem, H_OH_NEUTRALIZATION_J_PER_MOL, WATER_MOLAR_MASS_G_PER_MOL,
};
const AMOUNT_EPS: f64 = 1e-12;
@@ -123,7 +122,9 @@ fn add_water_ml(item: &mut SceneItem, ml: f64) {
///
/// Concentrations use **liquid water** ml as the solvent basis (not Φ_V solution
/// volume, which can include non-aqueous liquid H₂SO₄). No-ops when dry.
-pub fn speciate_aqueous_acid_base(item: &mut SceneItem, apply_heat: bool) {
+///
+/// Returns `true` when neutralization heat discarded spit mass.
+pub fn speciate_aqueous_acid_base(item: &mut SceneItem, apply_heat: bool) -> bool {
let water_ml = liquid_water_ml(item);
// Dry or empty: leave ion piles for reform / SI; strip solvent-only Kw ions.
if water_ml <= AMOUNT_EPS {
@@ -133,7 +134,7 @@ pub fn speciate_aqueous_acid_base(item: &mut SceneItem, apply_heat: bool) {
if n_cl <= AMOUNT_EPS && n_s <= AMOUNT_EPS {
set_aqueous_mol(item, "h+", 0.0);
}
- return;
+ return false;
}
let v_l = water_ml / 1000.0;
@@ -163,17 +164,11 @@ pub fn speciate_aqueous_acid_base(item: &mut SceneItem, apply_heat: bool) {
let n_rxn = 0.5 * (acid_base_before - acid_base_after).max(0.0);
if n_rxn > AMOUNT_EPS {
add_water_ml(item, n_rxn * WATER_MOLAR_MASS_G_PER_MOL);
- let c_eff = effective_heat_capacity(item);
- if c_eff > AMOUNT_EPS {
- let t = item
- .properties
- .temperature_c
- .unwrap_or(AMBIENT_TEMPERATURE_C);
- item.properties.temperature_c =
- Some(t - n_rxn * H_OH_NEUTRALIZATION_J_PER_MOL / c_eff);
- }
+ let q = n_rxn * H_OH_NEUTRALIZATION_J_PER_MOL;
+ return crate::scene::apply_chemical_heat(item, q);
}
}
+ false
}
/// Net charge (mol e⁻) of aqueous ions — should be ~0 after speciation.
@@ -190,7 +185,7 @@ pub fn aqueous_charge_mol(item: &SceneItem) -> f64 {
mod tests {
use super::*;
use crate::hcl::{ph_of_entries, solution_volume_ml};
- use crate::scene::{CompositionEntry, ItemProperties};
+ use crate::scene::{effective_heat_capacity, CompositionEntry, ItemProperties};
fn aq(substance_id: &str, amount_mol: f64) -> CompositionEntry {
CompositionEntry {
diff --git a/crates/chemlab-core/src/aqueous_pipeline.rs b/crates/chemlab-core/src/aqueous_pipeline.rs
index 799e1d6..484e078 100644
--- a/crates/chemlab-core/src/aqueous_pipeline.rs
+++ b/crates/chemlab-core/src/aqueous_pipeline.rs
@@ -4,9 +4,9 @@
//! depend on mutator-heavy `scene` helpers for ion writing.
use crate::scene::{
- add_or_increase_mol_in, effective_heat_capacity, CompositionEntry, SceneItem, AMOUNT_EPS,
- CACL2_MOLAR_MASS_G_PER_MOL, CASO4_MOLAR_MASS_G_PER_MOL, NA2SO4_MOLAR_MASS_G_PER_MOL,
- NACL_MOLAR_MASS_G_PER_MOL, NAOH_MOLAR_MASS_G_PER_MOL,
+ add_or_increase_mol_in, CompositionEntry, SceneItem, AMOUNT_EPS, CACL2_MOLAR_MASS_G_PER_MOL,
+ CASO4_MOLAR_MASS_G_PER_MOL, NA2SO4_MOLAR_MASS_G_PER_MOL, NACL_MOLAR_MASS_G_PER_MOL,
+ NAOH_MOLAR_MASS_G_PER_MOL,
};
/// Enthalpy of solution of NaCl at bench conditions (endothermic), J/mol.
@@ -50,28 +50,33 @@ impl FinalizeStage {
FinalizeStage::SyncFillMl,
];
- fn apply(self, item: &mut SceneItem, dissolve_tau_s: f64) {
+ fn apply(self, item: &mut SceneItem, dissolve_tau_s: f64) -> bool {
match self {
FinalizeStage::IonizeH2so4 => {
crate::h2so4::ionize_liquid_h2so4_in_water(item);
+ false
}
FinalizeStage::KineticDissolve => {
- crate::dissolve_kinetics::apply_kinetic_dissolve(item, dissolve_tau_s);
+ crate::dissolve_kinetics::apply_kinetic_dissolve(item, dissolve_tau_s)
}
FinalizeStage::SpeciateWithHeat => {
- crate::acid_base::speciate_aqueous_acid_base(item, true);
+ crate::acid_base::speciate_aqueous_acid_base(item, true)
}
FinalizeStage::EnforceSaturation => {
crate::solubility::enforce_saturation(item);
+ false
}
FinalizeStage::SpeciateNoHeatAfterSi | FinalizeStage::SpeciateNoHeatAfterReform => {
crate::acid_base::speciate_aqueous_acid_base(item, false);
+ false
}
FinalizeStage::ReformH2so4 => {
crate::h2so4::reform_aqueous_h2so4_to_liquid(item);
+ false
}
FinalizeStage::SyncFillMl => {
crate::solubility::sync_fill_ml(item);
+ false
}
}
}
@@ -129,22 +134,28 @@ pub(crate) fn author_dissolved_salt_ions(
/// threshold; [`crate::acid_base::speciate_aqueous_acid_base`] then solves `K_w` +
/// `K_a2`. SI is precipitate-only (under-saturated redissolve is kinetic-owned).
/// Free sulfuric below the reform threshold becomes liquid `h2so4`.
-pub(crate) fn finalize_aqueous_vessel(item: &mut SceneItem, dissolve_tau_s: f64) {
+///
+/// Returns `true` when any chemical-heat step discarded spit mass (caller emits
+/// at most one `spit` event per action).
+pub(crate) fn finalize_aqueous_vessel(item: &mut SceneItem, dissolve_tau_s: f64) -> bool {
+ let mut spit = false;
for stage in FinalizeStage::ALL {
- stage.apply(item, dissolve_tau_s);
+ spit |= stage.apply(item, dissolve_tau_s);
}
+ spit
}
/// Apply dissolution heat to the solvent vessel: ΔT = −(n·ΔH_sol) / C_eff.
///
-/// `C_eff` is [`effective_heat_capacity`] of the target (vessel + water + solids).
-/// Endothermic ΔH cools; exothermic heats.
+/// Routes through [`crate::scene::apply_chemical_heat`] so boil/spit gating is
+/// shared with dilution and neutralization. Returns `true` when spit mass was
+/// discarded on this heat step.
pub(crate) fn apply_dissolution_temperature_change(
target: &mut SceneItem,
moles: f64,
delta_h_j_per_mol: f64,
- current_temperature_c: f64,
-) {
+ _current_temperature_c: f64,
+) -> bool {
let water_ml = target
.properties
.composition
@@ -153,15 +164,10 @@ pub(crate) fn apply_dissolution_temperature_change(
.and_then(|c| c.amount_ml)
.unwrap_or(0.0);
if water_ml <= 0.0 || moles <= 0.0 {
- return;
- }
- let c_eff = effective_heat_capacity(target);
- if c_eff <= AMOUNT_EPS {
- return;
+ return false;
}
let heat_j = moles * delta_h_j_per_mol;
- let delta_t = -heat_j / c_eff;
- target.properties.temperature_c = Some(current_temperature_c + delta_t);
+ crate::scene::apply_chemical_heat(target, heat_j)
}
#[cfg(test)]
diff --git a/crates/chemlab-core/src/dissolve_kinetics.rs b/crates/chemlab-core/src/dissolve_kinetics.rs
index 61824c7..23e8aa1 100644
--- a/crates/chemlab-core/src/dissolve_kinetics.rs
+++ b/crates/chemlab-core/src/dissolve_kinetics.rs
@@ -101,25 +101,29 @@ fn dissolve_mass_for_contact(avail: f64, cap: f64, k: f64, tau_s: f64, is_naoh:
///
/// Authors ions + ΔH only for the mass that dissolves this call; remainder stays
/// solid. No-op without liquid water or when `τ ≤ 0`.
-pub(crate) fn apply_kinetic_dissolve(item: &mut SceneItem, tau_s: f64) {
+/// Returns `true` when any dissolve heat step discarded spit mass.
+pub(crate) fn apply_kinetic_dissolve(item: &mut SceneItem, tau_s: f64) -> bool {
let mut remaining = if tau_s.is_finite() {
tau_s.clamp(0.0, MAX_TAU_S)
} else {
0.0
};
+ let mut spit = false;
while remaining > AMOUNT_EPS {
let step = remaining.min(SUBSTEP_TAU_S);
- apply_kinetic_dissolve_step(item, step);
+ spit |= apply_kinetic_dissolve_step(item, step);
remaining -= step;
}
+ spit
}
-fn apply_kinetic_dissolve_step(item: &mut SceneItem, tau_s: f64) {
+fn apply_kinetic_dissolve_step(item: &mut SceneItem, tau_s: f64) -> bool {
let water_ml = solvent_water_ml_for_si(item);
if water_ml <= AMOUNT_EPS || tau_s <= AMOUNT_EPS {
- return;
+ return false;
}
+ let mut spit = false;
for salt_id in KINETIC_SALTS {
// Refresh T each salt so earlier dissolve ΔH is not wiped by a frozen snapshot.
let t = item
@@ -143,22 +147,25 @@ fn apply_kinetic_dissolve_step(item: &mut SceneItem, tau_s: f64) {
if let Some((moles, delta_h)) =
author_dissolved_salt_ions(&mut item.properties.composition, salt_id, m_diss)
{
- apply_dissolution_temperature_change(item, moles, delta_h, t);
+ spit |= apply_dissolution_temperature_change(item, moles, delta_h, t);
}
}
+ spit
}
/// Wash soluble solids from filter paper into a fluid parcel (same rate law).
///
-/// Updates `fluid` ions and `fluid_t` with dissolve ΔH. Sand is never touched.
+/// Updates `fluid` ions. Dissolve ΔH is returned as heat (J) for the caller to
+/// apply via [`crate::scene::apply_chemical_heat`] on the destination vessel after
+/// mix (shared boil/spit gate). Sand is never touched.
pub(crate) fn wash_paper_solids_into_fluid(
paper: &mut SceneItem,
fluid: &mut Vec,
fluid_t: &mut f64,
-) {
+) -> f64 {
let v_fluid = crate::composition::solvent_water_ml_for_si_entries(fluid);
if v_fluid <= AMOUNT_EPS {
- return;
+ return 0.0;
}
let c_fluid = heat_capacity_of_entries(fluid);
@@ -174,6 +181,7 @@ pub(crate) fn wash_paper_solids_into_fluid(
};
let tau = FILTER_WASH_TAU_S_PER_ML * v_fluid;
+ let mut heat_j = 0.0;
for salt_id in KINETIC_SALTS {
let avail = paper
@@ -191,12 +199,10 @@ pub(crate) fn wash_paper_solids_into_fluid(
}
remove_solid_mass(paper, salt_id, m_diss);
if let Some((moles, delta_h)) = author_dissolved_salt_ions(fluid, salt_id, m_diss) {
- let c_eff = heat_capacity_of_entries(fluid);
- if c_eff > AMOUNT_EPS {
- *fluid_t -= moles * delta_h / c_eff;
- }
+ heat_j += moles * delta_h;
}
}
+ heat_j
}
fn vessel_unsaturated_cap_g(item: &SceneItem, salt_id: &str, water_ml: f64, t: f64) -> f64 {
diff --git a/crates/chemlab-core/src/lib.rs b/crates/chemlab-core/src/lib.rs
index 9593110..d54dcaf 100644
--- a/crates/chemlab-core/src/lib.rs
+++ b/crates/chemlab-core/src/lib.rs
@@ -34,11 +34,11 @@ pub use hcl::{
};
pub use scene::{
apply_action, apply_elapsed, boiling_temperature_c, effective_heat_capacity,
- ensure_default_bench_items, initial_bench_scene, initial_scene_for_mode, water_mole_fraction,
- water_vapor_pressure_bar, Action, CompositionEntry, ItemProperties, Scene, SceneError,
- SceneEvent, SceneItem, AMBIENT_TEMPERATURE_C, ATM_PRESSURE_BAR, BOILING_TEMPERATURE_C,
- BURNER_POWER_W, CP_CACL2, CP_H2SO4_LIQUID, CP_NACL, CP_NAOH, CP_SAND, C_BEAKER, C_DISH,
- DISH_CAPACITY_ML, DISH_EVAP_AREA_M2, DISH_MASS_TRANSFER_COEFF_ML_PER_S_M2,
+ ensure_default_bench_items, initial_bench_scene, initial_scene_for_mode, vessel_boil_temperature_c,
+ water_mole_fraction, water_vapor_pressure_bar, Action, CompositionEntry, ItemProperties, Scene,
+ SceneError, SceneEvent, SceneItem, AMBIENT_TEMPERATURE_C, ATM_PRESSURE_BAR, BOILING_TEMPERATURE_C,
+ BURNER_POWER_W, CHEMICAL_SPIT_FRAC, CP_CACL2, CP_H2SO4_LIQUID, CP_NACL, CP_NAOH, CP_SAND, C_BEAKER,
+ C_DISH, DISH_CAPACITY_ML, DISH_EVAP_AREA_M2, DISH_MASS_TRANSFER_COEFF_ML_PER_S_M2,
DISTILLED_WATER_CAPACITY_ML, DISTILLED_WATER_ID, FILTRATE_CAPACITY_ML,
H_OH_NEUTRALIZATION_J_PER_MOL, MAIN_BEAKER_ID, PIPETTE_MIN_SOURCE_ML, PIPETTE_VOLUME_ML,
RELATIVE_HUMIDITY, SPOON_SCOOP_MASS_G, UA_BEAKER, UA_DISH, WATER_ANTOINE_A, WATER_ANTOINE_B,
diff --git a/crates/chemlab-core/src/scene.rs b/crates/chemlab-core/src/scene.rs
index 0273fd8..0f30942 100644
--- a/crates/chemlab-core/src/scene.rs
+++ b/crates/chemlab-core/src/scene.rs
@@ -124,6 +124,11 @@ pub(crate) use crate::aqueous_pipeline::finalize_aqueous_vessel;
/// Enthalpy of neutralization H⁺ + OH⁻ → H₂O (exothermic), J/mol.
pub const H_OH_NEUTRALIZATION_J_PER_MOL: f64 = -55800.0;
+/// School fraction of vessel composition discarded when chemical heat would boil.
+///
+/// Lost as spray (not continuous evaporation). Mid-range of the 2–5% school band.
+pub const CHEMICAL_SPIT_FRAC: f64 = 0.03;
+
/// Specific heat capacity of liquid water, J/(g·K). Mass of water ≈ volume in ml.
pub const WATER_SPECIFIC_HEAT_J_PER_G_K: f64 = 4.184;
@@ -1093,10 +1098,11 @@ fn apply_pour(
mass_g,
);
}
- finalize_aqueous_vessel(
+ let spit = finalize_aqueous_vessel(
&mut scene.items[target_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
);
+ note_chemical_spit(scene, spit);
return Ok(());
}
@@ -1127,10 +1133,11 @@ fn apply_pour(
});
}
- finalize_aqueous_vessel(
+ let spit = finalize_aqueous_vessel(
&mut scene.items[target_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
);
+ note_chemical_spit(scene, spit);
Ok(())
}
@@ -1293,8 +1300,8 @@ fn apply_toggle_burner(scene: &mut Scene, burner_item_id: &str) -> Result<(), Sc
mod thermal;
pub use thermal::{
- apply_elapsed, boiling_temperature_c, effective_heat_capacity, water_mole_fraction,
- water_vapor_pressure_bar,
+ apply_elapsed, boiling_temperature_c, effective_heat_capacity, vessel_boil_temperature_c,
+ water_mole_fraction, water_vapor_pressure_bar,
};
use thermal::blend_temperature_capacity;
@@ -1336,7 +1343,8 @@ fn apply_pipette_fill(
.unwrap_or(scene.temperature_c);
let aliquot = take_liquid_aliquot(&mut scene.items[target_idx], PIPETTE_VOLUME_ML)?;
// Concentration may precipitate; no dissolve contact on the source draw.
- finalize_aqueous_vessel(&mut scene.items[target_idx], 0.0);
+ let spit = finalize_aqueous_vessel(&mut scene.items[target_idx], 0.0);
+ note_chemical_spit(scene, spit);
let pipette = &mut scene.items[tool_idx];
pipette.location = "hand".into();
@@ -1423,11 +1431,12 @@ fn apply_pipette_empty(
.properties
.temperature_c
.unwrap_or(scene.temperature_c);
- mix_aliquot_into(&mut scene.items[target_idx], &aliquot, aliquot_t);
- finalize_aqueous_vessel(
+ let spit_mix = mix_aliquot_into(&mut scene.items[target_idx], &aliquot, aliquot_t);
+ let spit_fin = finalize_aqueous_vessel(
&mut scene.items[target_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
);
+ note_chemical_spit(scene, spit_mix || spit_fin);
let pipette = &mut scene.items[tool_idx];
pipette.properties.holding.clear();
@@ -1642,17 +1651,19 @@ fn apply_filter_pour(scene: &mut Scene, tool_idx: usize) -> Result<(), SceneErro
}
// Deposit source solids onto paper first so this pour's soluble fraction is
// eligible for wash with the fluid still about to enter the filtrate.
- mix_transfer_into(&mut scene.items[paper_idx], &solids, None);
+ let _ = mix_transfer_into(&mut scene.items[paper_idx], &solids, None);
let mut fluid_t = source_t;
- crate::dissolve_kinetics::wash_paper_solids_into_fluid(
+ let wash_q = crate::dissolve_kinetics::wash_paper_solids_into_fluid(
&mut scene.items[paper_idx],
&mut fluid,
&mut fluid_t,
);
- mix_transfer_into(&mut scene.items[dest_idx], &fluid, Some(fluid_t));
+ let spit_mix = mix_transfer_into(&mut scene.items[dest_idx], &fluid, Some(fluid_t));
+ let spit_wash = apply_chemical_heat(&mut scene.items[dest_idx], wash_q);
// Wash already applied contact-time kinetics; finalize is SI/speciate only.
- finalize_aqueous_vessel(&mut scene.items[source_idx], 0.0);
- finalize_aqueous_vessel(&mut scene.items[dest_idx], 0.0);
+ let spit_src = finalize_aqueous_vessel(&mut scene.items[source_idx], 0.0);
+ let spit_dest = finalize_aqueous_vessel(&mut scene.items[dest_idx], 0.0);
+ note_chemical_spit(scene, spit_mix || spit_wash || spit_src || spit_dest);
scene.last_events.push(SceneEvent {
kind: "poured".into(),
message: "Filtered into the filtrate beaker.".into(),
@@ -1791,12 +1802,13 @@ fn apply_tongs_pour(scene: &mut Scene, tool_idx: usize, dest_idx: usize) -> Resu
}
let (taken, source_t) = transfer_liquid_fraction(scene, source_idx, dest_idx, dest_cap)?;
- mix_transfer_into(&mut scene.items[dest_idx], &taken, Some(source_t));
- finalize_aqueous_vessel(&mut scene.items[source_idx], 0.0);
- finalize_aqueous_vessel(
+ let spit_mix = mix_transfer_into(&mut scene.items[dest_idx], &taken, Some(source_t));
+ let spit_src = finalize_aqueous_vessel(&mut scene.items[source_idx], 0.0);
+ let spit_dest = finalize_aqueous_vessel(
&mut scene.items[dest_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
);
+ note_chemical_spit(scene, spit_mix || spit_src || spit_dest);
scene.last_events.push(SceneEvent {
kind: "poured".into(),
message: "Poured from the held vessel.".into(),
@@ -1814,12 +1826,13 @@ fn dump_all_solids(
.temperature_c
.unwrap_or(scene.temperature_c);
let taken = take_all_solids(&mut scene.items[source_idx]);
- mix_transfer_into(&mut scene.items[dest_idx], &taken, Some(source_t));
- finalize_aqueous_vessel(&mut scene.items[source_idx], 0.0);
- finalize_aqueous_vessel(
+ let spit_mix = mix_transfer_into(&mut scene.items[dest_idx], &taken, Some(source_t));
+ let spit_src = finalize_aqueous_vessel(&mut scene.items[source_idx], 0.0);
+ let spit_dest = finalize_aqueous_vessel(
&mut scene.items[dest_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
);
+ note_chemical_spit(scene, spit_mix || spit_src || spit_dest);
scene.last_events.push(SceneEvent {
kind: "poured".into(),
message: "Poured solids into the vessel.".into(),
@@ -1979,7 +1992,7 @@ fn mix_transfer_into(
target: &mut SceneItem,
transferred: &[CompositionEntry],
source_t: Option,
-) {
+) -> bool {
let dest_hcl_before = crate::hcl::HclInventory::from_item(target);
let added_hcl = crate::hcl::HclInventory::from_entries(transferred);
let dest_h2so4_before = crate::h2so4::H2so4Inventory::from_item(target);
@@ -1993,11 +2006,12 @@ fn mix_transfer_into(
merge_composition_into(target, transferred, true);
crate::h2so4::ionize_liquid_h2so4_in_water(target);
crate::solubility::sync_fill_ml(target);
- apply_hcl_dilution_temperature(target, dest_hcl_before, added_hcl);
- apply_h2so4_dilution_temperature(target, dest_h2so4_before, added_h2so4);
+ let spit_hcl = apply_hcl_dilution_temperature(target, dest_hcl_before, added_hcl);
+ let spit_h2so4 = apply_h2so4_dilution_temperature(target, dest_h2so4_before, added_h2so4);
+ spit_hcl || spit_h2so4
}
-fn mix_aliquot_into(target: &mut SceneItem, aliquot: &[CompositionEntry], aliquot_t: f64) {
+fn mix_aliquot_into(target: &mut SceneItem, aliquot: &[CompositionEntry], aliquot_t: f64) -> bool {
let dest_hcl_before = crate::hcl::HclInventory::from_item(target);
let added_hcl = crate::hcl::HclInventory::from_entries(aliquot);
let dest_h2so4_before = crate::h2so4::H2so4Inventory::from_item(target);
@@ -2012,50 +2026,85 @@ fn mix_aliquot_into(target: &mut SceneItem, aliquot: &[CompositionEntry], aliquo
merge_composition_into(target, aliquot, false);
crate::h2so4::ionize_liquid_h2so4_in_water(target);
crate::solubility::sync_fill_ml(target);
- apply_hcl_dilution_temperature(target, dest_hcl_before, added_hcl);
- apply_h2so4_dilution_temperature(target, dest_h2so4_before, added_h2so4);
+ let spit_hcl = apply_hcl_dilution_temperature(target, dest_hcl_before, added_hcl);
+ let spit_h2so4 = apply_h2so4_dilution_temperature(target, dest_h2so4_before, added_h2so4);
+ spit_hcl || spit_h2so4
}
fn apply_hcl_dilution_temperature(
target: &mut SceneItem,
dest_before: crate::hcl::HclInventory,
added: crate::hcl::HclInventory,
-) {
+) -> bool {
// Gated on HCl inventory (`min(max(n_h − n_oh, 0), n_cl)`), not bare protons.
if dest_before.n_h <= AMOUNT_EPS && added.n_h <= AMOUNT_EPS {
- return;
+ return false;
}
let after = crate::hcl::HclInventory::from_item(target);
let q = crate::hcl::hcl_dilution_heat_j(dest_before, added, after);
- apply_chemical_heat(target, q);
+ apply_chemical_heat(target, q)
}
fn apply_h2so4_dilution_temperature(
target: &mut SceneItem,
dest_before: crate::h2so4::H2so4Inventory,
added: crate::h2so4::H2so4Inventory,
-) {
+) -> bool {
if dest_before.n_h2so4 <= AMOUNT_EPS && added.n_h2so4 <= AMOUNT_EPS {
- return;
+ return false;
}
let after = crate::h2so4::H2so4Inventory::from_item(target);
let q = crate::h2so4::h2so4_dilution_heat_j(dest_before, added, after);
- apply_chemical_heat(target, q);
+ apply_chemical_heat(target, q)
}
-fn apply_chemical_heat(target: &mut SceneItem, q_j: f64) {
+/// Apply instant chemical heat `q_j` (negative ⇒ exothermic): `ΔT = −Q / C_eff`.
+///
+/// When the proposed temperature would reach or exceed [`vessel_boil_temperature_c`],
+/// clamp at boil, discard [`CHEMICAL_SPIT_FRAC`] of composition (spray mass), and
+/// return `true` so the caller can emit at most one silent `spit` event per action.
+/// Burner continuous boil stays on the thermal path — this gate is chemical-only.
+pub(crate) fn apply_chemical_heat(target: &mut SceneItem, q_j: f64) -> bool {
if q_j.abs() <= AMOUNT_EPS {
- return;
+ return false;
}
let c_eff = effective_heat_capacity(target);
if c_eff <= AMOUNT_EPS {
- return;
+ return false;
}
let t = target
.properties
.temperature_c
.unwrap_or(AMBIENT_TEMPERATURE_C);
- target.properties.temperature_c = Some(t - q_j / c_eff);
+ let t_proposed = t - q_j / c_eff;
+ let t_boil = vessel_boil_temperature_c(target);
+ // Already plateaued at boil from a prior chemical-heat step this action:
+ // clamp only — do not spit mass again.
+ if t + 1e-3 >= t_boil {
+ target.properties.temperature_c = Some(t_boil);
+ return false;
+ }
+ if t_proposed + 1e-6 < t_boil {
+ target.properties.temperature_c = Some(t_proposed);
+ return false;
+ }
+ target.properties.temperature_c = Some(t_boil);
+ let _discarded = take_composition_fraction(target, CHEMICAL_SPIT_FRAC);
+ true
+}
+
+/// Push a silent spit event at most once per action (empty message; FE is visual-only).
+fn note_chemical_spit(scene: &mut Scene, spit: bool) {
+ if !spit {
+ return;
+ }
+ if scene.last_events.iter().any(|e| e.kind == "spit") {
+ return;
+ }
+ scene.last_events.push(SceneEvent {
+ kind: "spit".into(),
+ message: String::new(),
+ });
}
fn add_or_increase_water(item: &mut SceneItem, ml: f64) {
diff --git a/crates/chemlab-core/src/scene_tests/h2so4.rs b/crates/chemlab-core/src/scene_tests/h2so4.rs
index f7c07fa..b1663ce 100644
--- a/crates/chemlab-core/src/scene_tests/h2so4.rs
+++ b/crates/chemlab-core/src/scene_tests/h2so4.rs
@@ -529,3 +529,118 @@ fn reformed_liquid_redilutes_and_ionizes() {
let t = dish.properties.temperature_c.unwrap_or(20.0);
assert!(t > 20.5, "re-dilution should warm, got {t}");
}
+
+fn spit_count(scene: &Scene) -> usize {
+ scene.last_events.iter().filter(|e| e.kind == "spit").count()
+}
+
+fn solution_ml(id: &str, scene: &Scene) -> f64 {
+ crate::hcl::solution_volume_ml(item(scene, id))
+}
+
+#[test]
+fn chemical_heat_overshoot_spits_and_drops_mass_at_boil() {
+ let mut scene = initial_bench_scene("lab-test");
+ fill_main_beaker(&mut scene, 10.0);
+ {
+ let water = scene
+ .items
+ .iter_mut()
+ .find(|i| i.id == "beaker-water")
+ .unwrap();
+ water.properties.temperature_c = Some(95.0);
+ }
+ fill_pipette_from(&mut scene, "beaker-h2so4");
+ apply_action(
+ &mut scene,
+ Action::UseTool {
+ tool_item_id: "pipette-1".into(),
+ target_item_id: "beaker-water".into(),
+ },
+ )
+ .unwrap();
+
+ assert_eq!(spit_count(&scene), 1);
+ let spit = scene
+ .last_events
+ .iter()
+ .find(|e| e.kind == "spit")
+ .expect("spit event");
+ assert_eq!(spit.message, "");
+
+ let water = item(&scene, "beaker-water");
+ let t = water.properties.temperature_c.unwrap();
+ let t_boil = boiling_temperature_c(water_mole_fraction(water));
+ assert!(
+ (t - t_boil).abs() < 0.05,
+ "T should clamp at boil: T={t} T_boil={t_boil}"
+ );
+ let v = solution_ml("beaker-water", &scene);
+ assert!(
+ v < 10.0 + PIPETTE_VOLUME_ML - 0.15,
+ "spit should drop sprayable volume, got {v}"
+ );
+ assert_fill_ml_matches_phi_v(&scene);
+}
+
+#[test]
+fn mild_dilution_does_not_spit() {
+ let mut scene = initial_bench_scene("lab-test");
+ fill_main_beaker(&mut scene, 20.0);
+ fill_pipette_from(&mut scene, "beaker-h2so4");
+ apply_action(
+ &mut scene,
+ Action::UseTool {
+ tool_item_id: "pipette-1".into(),
+ target_item_id: "beaker-water".into(),
+ },
+ )
+ .unwrap();
+ assert_eq!(spit_count(&scene), 0);
+ let t = item(&scene, "beaker-water")
+ .properties
+ .temperature_c
+ .unwrap_or(20.0);
+ assert!(t > 20.5 && t < 80.0, "mild warming only, got {t}");
+}
+
+#[test]
+fn stacked_chemical_heats_emit_at_most_one_spit() {
+ let mut scene = initial_bench_scene("lab-test");
+ fill_main_beaker(&mut scene, 10.0);
+ {
+ let water = scene
+ .items
+ .iter_mut()
+ .find(|i| i.id == "beaker-water")
+ .unwrap();
+ water.properties.temperature_c = Some(95.0);
+ water.properties.composition.push(CompositionEntry {
+ substance_id: "naoh".into(),
+ phase: "solid".into(),
+ amount_ml: None,
+ amount_scoop: Some(5),
+ amount_g: Some(1.0),
+ amount_mol: None,
+ });
+ }
+ fill_pipette_from(&mut scene, "beaker-h2so4");
+ apply_action(
+ &mut scene,
+ Action::UseTool {
+ tool_item_id: "pipette-1".into(),
+ target_item_id: "beaker-water".into(),
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ spit_count(&scene),
+ 1,
+ "dilution + kinetic + neutralization must share one spit: {:?}",
+ scene.last_events
+ );
+ let water = item(&scene, "beaker-water");
+ let t = water.properties.temperature_c.unwrap();
+ let t_boil = boiling_temperature_c(water_mole_fraction(water));
+ assert!((t - t_boil).abs() < 0.05, "T={t} T_boil={t_boil}");
+}
diff --git a/crates/chemlab-core/src/thermal.rs b/crates/chemlab-core/src/thermal.rs
index ba3eeea..ac5c474 100644
--- a/crates/chemlab-core/src/thermal.rs
+++ b/crates/chemlab-core/src/thermal.rs
@@ -156,15 +156,16 @@ fn remove_evaporated_mass(dish: &mut SceneItem, loss_mass_g: f64) {
}
}
-/// Dish boil temperature.
+/// Vessel boil temperature (beaker or dish).
///
/// With HCl inventory: tabulated `T_hcl(w)`. When non-HCl solutes are also
/// present (salt metals / salt Cl⁻ / sulfate concentrates), take
/// `max(T_hcl(w), T_raoult(x_w))` so elevation is not ignored (no more acid-wins).
/// Concentrated HCl alone stays on the acid table — Raoult on the acid-depleted
/// `x_w` would falsely soar. Without HCl inventory: Raoult + Antoine from water
-/// mole fraction (sulfuric-only / water path).
-fn dish_boil_temperature_c(item: &SceneItem) -> f64 {
+/// mole fraction (sulfuric-only / water path). Shared by burner dish boil and
+/// instant chemical-heat spit gating.
+pub fn vessel_boil_temperature_c(item: &SceneItem) -> f64 {
let inv = crate::hcl::HclInventory::from_item(item);
let t_water = boiling_temperature_c(water_mole_fraction(item));
if inv.n_h > AMOUNT_EPS {
@@ -177,6 +178,10 @@ fn dish_boil_temperature_c(item: &SceneItem) -> f64 {
t_water
}
+fn dish_boil_temperature_c(item: &SceneItem) -> f64 {
+ vessel_boil_temperature_c(item)
+}
+
/// True when aqueous non-HCl solutes depress `x_w` beyond gated HCl alone:
/// salt Na⁺/Ca²⁺, salt Cl⁻, or sulfate / bisulfate concentrates.
fn dish_has_non_hcl_solute(item: &SceneItem) -> bool {
diff --git a/docs/lab-scene-spec.md b/docs/lab-scene-spec.md
index de89473..44649e2 100644
--- a/docs/lab-scene-spec.md
+++ b/docs/lab-scene-spec.md
@@ -99,12 +99,16 @@ Pour into water is a separate action, e.g. `{ "type": "pour", "source_item_id":
- `ItemProperties` — optional volume/fill/flags/temperature (°C as `f64`); `composition` and `holding` lists; optional burner `on`; optional pipette `source_item_id`
- `Item` — `id`, `kind` (`beaker` \| `spoon` \| `pipette` \| `evaporation_dish` \| `burner`), `label`, `location`, `properties`
- `LabScene` — `lab_id`, `version`, ambient `temperature_c` (default `20.0`), `items`, optional `last_events`, optional `last_applied_unix_ms`
-- `LabEvent` — `kind` (e.g. `scooped`, `returned`, `poured`, `pipetted`, `toggled`, `dissolved`, `did_not_dissolve`), `message`
+- `LabEvent` — `kind` (e.g. `scooped`, `returned`, `poured`, `pipetted`, `toggled`, `dissolved`, `did_not_dissolve`, `spit`), `message`
- `LabAction` — tagged `type`: `use_tool` \| `pour` \| `put_away` \| `reset` \| `toggle_burner`
- `LabActionResponse` — `{ "scene": LabScene }`
When NaCl dissolves into water, the scene engine applies **endothermic** cooling to the water beaker's `properties.temperature_c` (ΔH_sol ≈ 3.88 kJ/mol; ΔT = −n·ΔH / C_eff). When CaCl₂ dissolves, it applies **exothermic** heating (ΔH_sol ≈ −81.3 kJ/mol) with the same C_eff model. Ambient `LabScene.temperature_c` is unchanged. Sand that does not dissolve still energy-weights its solid heat capacity into the target. The frontend formats inspect mass (g) and volume (ml) to **two decimal places**, aqueous molarity (M) to **three significant digits**, and beaker/scene temperature to two decimal places.
+### Instant chemical heat and boil spit
+
+All instant chemical ΔT (H₂SO₄ / HCl Φ_L dilution, neutralization, kinetic dissolve ΔH) routes through `apply_chemical_heat` (`ΔT = −Q / C_eff`). When the proposed temperature would reach or exceed the vessel boil temperature (same rule as dish boil: HCl table ± Raoult), the engine **clamps** `T` at boil, discards a school spray fraction **`CHEMICAL_SPIT_FRAC = 0.03`** of the vessel composition via `take_composition_fraction` (not continuous evaporation), syncs `fill_ml`, and emits at most one silent `LabEvent` `{ kind: "spit", message: "" }` per action. Mild dilutions that stay below boil do not spit. Stacked heats in one action (dilution then kinetic then neutralization) share that single spit. The frontend suppresses spit from the teaching banner and plays a short CSS/SVG spray burst on the last action target (`prefers-reduced-motion` respected). Burner continuous boil / dish heat-limited evaporation stays on the thermal path and is separate. Beakers still never evaporate on the clock.
+
### Heat capacity and temperature blending
`effective_heat_capacity(item) = C_vessel(kind) + Σ contents m·c_p` (tools / burner / filter paper skipped; pipette = liquid holding only):
@@ -126,7 +130,7 @@ Transfers (pipette empty, tongs liquid/solid pour, filter fluid → filtrate, sp
where `C_dest` is the destination's effective heat capacity **before** the add. A **spoon** holding solids carries `temperature_c` from the source vessel and clears it on empty / put-away.
-**Filter pour wash:** after the phase split (solids → paper, liquid+aqueous → fluid parcel) and before mixing into the filtrate, fine soluble solids on the paper (`nacl`, `cacl2`, `naoh`, and sulfate solids when present) partially dissolve into the fluid with the **same** school first-order helper as vessels: contact time `τ ∝ V_fluid` at the energy-weighted blend T of fluid + paper solids, per-salt `k(T)`, `m_diss = min(avail, unsaturated_cap) · (1 − exp(−k·τ))` (NaOH uncapped). Sand never dissolves. Dissolve ΔH adjusts the fluid parcel temperature before the filtrate blend.
+**Filter pour wash:** after the phase split (solids → paper, liquid+aqueous → fluid parcel) and before mixing into the filtrate, fine soluble solids on the paper (`nacl`, `cacl2`, `naoh`, and sulfate solids when present) partially dissolve into the fluid with the **same** school first-order helper as vessels: contact time `τ ∝ V_fluid` at the energy-weighted blend T of fluid + paper solids, per-salt `k(T)`, `m_diss = min(avail, unsaturated_cap) · (1 − exp(−k·τ))` (NaOH uncapped). Sand never dissolves. Dissolve ΔH is applied on the filtrate via `apply_chemical_heat` after the mix (shared boil/spit gate).
### Free-mode hydrochloric acid stock
@@ -160,7 +164,7 @@ While the **burner** is on and heating the dish, dish temperature rises with `dT
**Burner off (sub-boil):** mass-transfer loss `m_dot = k · A · max(0, p_w − p_air) / P_atm` with `p_w = x_w · P_sat(T)`, `p_air = RH · P_sat(T_amb)`; `A = DISH_EVAP_AREA_M2`, `k` chosen so pure water at 20 °C / 50% RH loses ≈ **2 ml/h**. Evaporated mass cools the dish by `ΔT = −m · H_vap / C_eff`. With HCl inventory, `H_vap = (1 − y)·2257 + y·HCL_LATENT` (school `HCL_LATENT ≈ 440` J/g); water-only uses `WATER_LATENT_HEAT_J_PER_G = 2257`. Sub-boil mass transfer is skipped while the burner is heating so Antoine-scaled driving force cannot dry/concentrate the dish before boil.
-**At boil** (burner on): clamp `T` to the boil rule above; heat-limited rate `m_dot = BURNER_POWER_W / H_vap` (same weighted `H_vap` when HCl leaves). With HCl inventory, mass loss removes **both water and HCl** with a documented school `y(w)` vapor table consistent with the boil-T knots (~**20.2% w/w** azeotrope): lean liquid → vapor leaner in HCl; rich liquid → vapor richer in HCl; `|y − w_l|` shrinks as `w_l → w_az`, removing proportional `h+`/`cl-` with evaporated HCl. Without HCl inventory, boil removes water only and leaves salt / sulfate ions (and non-volatile H₂SO₄) behind. While heating, Newton cool is skipped for the dish (same as before), so boil `Q_net` is burner power only. Burner off at/above boil does not heat-limit evaporate (`Q_net ≤ 0`); ambient cool lowers `T`. Beakers never evaporate. Mixed NaCl/CaCl₂/Na₂SO₄/CaSO₄ SI is **precipitate-only** on aqueous vessels; under-saturated solid → aq goes through kinetic dissolve on clock `dt`. The burner turns off when the dish has no liquid water (leftover liquid H₂SO₄ after dry-out does not keep it on).
+**At boil** (burner on): clamp `T` to the boil rule above; heat-limited rate `m_dot = BURNER_POWER_W / H_vap` (same weighted `H_vap` when HCl leaves). With HCl inventory, mass loss removes **both water and HCl** with a documented school `y(w)` vapor table consistent with the boil-T knots (~**20.2% w/w** azeotrope): lean liquid → vapor leaner in HCl; rich liquid → vapor richer in HCl; `|y − w_l|` shrinks as `w_l → w_az`, removing proportional `h+`/`cl-` with evaporated HCl. Without HCl inventory, boil removes water only and leaves salt / sulfate ions (and non-volatile H₂SO₄) behind. While heating, Newton cool is skipped for the dish (same as before), so boil `Q_net` is burner power only. Burner off at/above boil does not heat-limit evaporate (`Q_net ≤ 0`); ambient cool lowers `T`. Beakers never evaporate continuously on the clock (chemical spit can still discard a spray fraction — see Instant chemical heat and boil spit). Mixed NaCl/CaCl₂/Na₂SO₄/CaSO₄ SI is **precipitate-only** on aqueous vessels; under-saturated solid → aq goes through kinetic dissolve on clock `dt`. The burner turns off when the dish has no liquid water (leftover liquid H₂SO₄ after dry-out does not keep it on).
Every `apply_elapsed` tick also applies **Newton cooling** toward ambient 20.00 °C for thermal vessels (and a filled pipette): `dT = −(UA / C_eff) · (T − T_amb) · dt`, clamped so T does not cross ambient; snap when `|T − 20| < 0.005`. `UA_DISH = 4.0` W/K, `UA_BEAKER = 3.0` W/K. While the burner is actively heating the dish, that dish skips ambient cool for the tick; other vessels still cool. Elapsed heat/cool/evap is `chemlab-core::apply_elapsed`; the HTTP layer owns the clock. The web client polls the lab scene (~300 ms) while the burner is on, **or** any thermal item has `|T − 20| ≥ 0.5`, **or** a wet beaker/dish still holds a kinetically soluble solid (NaCl / CaCl₂ / NaOH / Na₂SO₄ / gypsum) — NaCl dissolve ΔT is often ≪ 0.5 °C, so thermal poll alone would leave inspect amounts stale.
From 35e1aaafb7b25065bcae4ea854819b51e088789b Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Mon, 28 Sep 2026 12:16:59 +0000
Subject: [PATCH 2/3] style: cargo fmt for chemical spit changes
Co-authored-by: Arnoud
---
crates/chemlab-core/src/lib.rs | 11 ++++++-----
crates/chemlab-core/src/scene_tests/h2so4.rs | 6 +++++-
2 files changed, 11 insertions(+), 6 deletions(-)
diff --git a/crates/chemlab-core/src/lib.rs b/crates/chemlab-core/src/lib.rs
index d54dcaf..cb845f7 100644
--- a/crates/chemlab-core/src/lib.rs
+++ b/crates/chemlab-core/src/lib.rs
@@ -34,11 +34,12 @@ pub use hcl::{
};
pub use scene::{
apply_action, apply_elapsed, boiling_temperature_c, effective_heat_capacity,
- ensure_default_bench_items, initial_bench_scene, initial_scene_for_mode, vessel_boil_temperature_c,
- water_mole_fraction, water_vapor_pressure_bar, Action, CompositionEntry, ItemProperties, Scene,
- SceneError, SceneEvent, SceneItem, AMBIENT_TEMPERATURE_C, ATM_PRESSURE_BAR, BOILING_TEMPERATURE_C,
- BURNER_POWER_W, CHEMICAL_SPIT_FRAC, CP_CACL2, CP_H2SO4_LIQUID, CP_NACL, CP_NAOH, CP_SAND, C_BEAKER,
- C_DISH, DISH_CAPACITY_ML, DISH_EVAP_AREA_M2, DISH_MASS_TRANSFER_COEFF_ML_PER_S_M2,
+ ensure_default_bench_items, initial_bench_scene, initial_scene_for_mode,
+ vessel_boil_temperature_c, water_mole_fraction, water_vapor_pressure_bar, Action,
+ CompositionEntry, ItemProperties, Scene, SceneError, SceneEvent, SceneItem,
+ AMBIENT_TEMPERATURE_C, ATM_PRESSURE_BAR, BOILING_TEMPERATURE_C, BURNER_POWER_W,
+ CHEMICAL_SPIT_FRAC, CP_CACL2, CP_H2SO4_LIQUID, CP_NACL, CP_NAOH, CP_SAND, C_BEAKER, C_DISH,
+ DISH_CAPACITY_ML, DISH_EVAP_AREA_M2, DISH_MASS_TRANSFER_COEFF_ML_PER_S_M2,
DISTILLED_WATER_CAPACITY_ML, DISTILLED_WATER_ID, FILTRATE_CAPACITY_ML,
H_OH_NEUTRALIZATION_J_PER_MOL, MAIN_BEAKER_ID, PIPETTE_MIN_SOURCE_ML, PIPETTE_VOLUME_ML,
RELATIVE_HUMIDITY, SPOON_SCOOP_MASS_G, UA_BEAKER, UA_DISH, WATER_ANTOINE_A, WATER_ANTOINE_B,
diff --git a/crates/chemlab-core/src/scene_tests/h2so4.rs b/crates/chemlab-core/src/scene_tests/h2so4.rs
index b1663ce..fc4523f 100644
--- a/crates/chemlab-core/src/scene_tests/h2so4.rs
+++ b/crates/chemlab-core/src/scene_tests/h2so4.rs
@@ -531,7 +531,11 @@ fn reformed_liquid_redilutes_and_ionizes() {
}
fn spit_count(scene: &Scene) -> usize {
- scene.last_events.iter().filter(|e| e.kind == "spit").count()
+ scene
+ .last_events
+ .iter()
+ .filter(|e| e.kind == "spit")
+ .count()
}
fn solution_ml(id: &str, scene: &Scene) -> f64 {
From 000bb957fcb8a2af5ea088a60eb1d5b444e494a3 Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Mon, 28 Sep 2026 12:28:23 +0000
Subject: [PATCH 3/3] fix: spit cue on last target; clock clamp-only
Wire CSS/SVG spit spray to dish and filtrate as well as water.
Pass allow_spit_mass=false from apply_elapsed so clock kinetic heat
clamps at boil without discarding spray mass or emitting spit.
Co-authored-by: Arnoud
---
.../LabBench.pipette-burner.test.tsx | 42 +++++++++
apps/web/src/components/LabBench.tsx | 27 ++++--
apps/web/src/components/LabBenchIcons.tsx | 86 ++++++++++++++++---
apps/web/src/components/labBenchScene.ts | 2 +-
apps/web/src/index.css | 8 +-
crates/chemlab-core/src/acid_base.rs | 25 ++++--
crates/chemlab-core/src/aqueous_pipeline.rs | 28 ++++--
crates/chemlab-core/src/dissolve_kinetics.rs | 18 ++--
crates/chemlab-core/src/scene.rs | 34 +++++---
.../src/scene_tests/evaporation.rs | 4 +-
crates/chemlab-core/src/scene_tests/h2so4.rs | 38 ++++++++
crates/chemlab-core/src/thermal.rs | 4 +-
docs/lab-scene-spec.md | 2 +-
13 files changed, 252 insertions(+), 66 deletions(-)
diff --git a/apps/web/src/components/LabBench.pipette-burner.test.tsx b/apps/web/src/components/LabBench.pipette-burner.test.tsx
index 9a7faf5..8f897d5 100644
--- a/apps/web/src/components/LabBench.pipette-burner.test.tsx
+++ b/apps/web/src/components/LabBench.pipette-burner.test.tsx
@@ -12,6 +12,8 @@ import {
stubLabFetch,
lastActionInit,
expectCsrfLabAction,
+ applyPipetteUse,
+ cloneScene,
} from './labBenchTestHelpers'
describe('LabBench pipette / burner', () => {
@@ -370,4 +372,44 @@ describe('LabBench pipette / burner', () => {
})
})
+ it('shows spit cue on dish last-action target, not water, and hides spit from banner', async () => {
+ const fetchMock = stubLabFetch({
+ actionHandler: (action, scene) => {
+ if (action.type === 'use_tool' && action.tool_item_id === 'pipette-1') {
+ const result = applyPipetteUse(scene, action.target_item_id)
+ if ('error' in result) return result
+ if (
+ action.target_item_id === 'dish-1' &&
+ result.last_events?.some((event) => event.kind === 'poured')
+ ) {
+ const next = cloneScene(result)
+ next.last_events = [
+ { kind: 'spit', message: '' },
+ ...(next.last_events ?? []),
+ ]
+ return next
+ }
+ return result
+ }
+ return scene
+ },
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ render()
+ await screen.findByRole('button', { name: 'Pipette' })
+ fireEvent.click(screen.getByRole('button', { name: 'Pipette' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Beaker' }))
+ await waitFor(() => {
+ expect(document.querySelector('[data-pipette-filled="true"]')).not.toBeNull()
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Evaporation dish' }))
+ await waitFor(() => {
+ expect(document.querySelector('[data-dish-fill]')).toHaveAttribute('data-spit-cue', 'burst')
+ })
+ expect(document.querySelector('[data-water-fill]')).toHaveAttribute('data-spit-cue', 'none')
+ expect(document.querySelector('[data-event-kind="spit"]')).toBeNull()
+ expect(screen.getByRole('status')).toHaveTextContent('Emptied the pipette into the vessel.')
+ })
+
})
diff --git a/apps/web/src/components/LabBench.tsx b/apps/web/src/components/LabBench.tsx
index 0b97054..73cc66b 100644
--- a/apps/web/src/components/LabBench.tsx
+++ b/apps/web/src/components/LabBench.tsx
@@ -560,11 +560,15 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
aria-label="Filtrate beaker"
disabled={busy}
onClick={onFiltrate}
+ data-spit-cue={spitTargetId === FILTRATE_ID ? 'burst' : 'none'}
>
{filtrateHeld ? (
) : (
-
+
)}
{filtrate?.label ?? 'Filtrate'}
@@ -579,11 +583,15 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
aria-label="Evaporation dish"
disabled={busy}
onClick={onDish}
+ data-spit-cue={spitTargetId === DISH_ID ? 'burst' : 'none'}
>
{dishHeld ? (
) : (
-
+
)}
{dish.label}
@@ -606,7 +614,7 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo