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 b2c92c7..73cc66b 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
@@ -551,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'}
@@ -570,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}
@@ -601,6 +618,7 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
aria-label={water?.label ?? 'Beaker'}
disabled={busy}
onClick={onWater}
+ data-spit-cue={spitTargetId === WATER_ID ? 'burst' : 'none'}
>
{waterHeld ? (
@@ -611,6 +629,7 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
amountMl={waterAmountMl(scene)}
hasAqueous={hasAqueous}
dissolveCue={dissolveCue}
+ spitCue={spitTargetId === WATER_ID}
/>
)}
{water?.label ?? 'Beaker'}
@@ -785,6 +804,7 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
amountMl={waterAmountMl(scene)}
hasAqueous={hasAqueous}
dissolveCue={dissolveCue}
+ spitCue={spitTargetId === WATER_ID}
floating
/>
) : heldVesselId === H2O_ID && scene ? (
@@ -800,9 +820,17 @@ export function LabBench({ onModeChange }: { onModeChange?: (mode: string) => vo
floating
/>
) : heldVesselId === DISH_ID && scene ? (
-
+
) : heldVesselId === FILTRATE_ID && scene ? (
-
+
) : heldVesselId === PAPER_ID && scene ? (
) : (
@@ -828,7 +856,7 @@ 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..8280989 100644
--- a/apps/web/src/components/LabBenchIcons.tsx
+++ b/apps/web/src/components/LabBenchIcons.tsx
@@ -10,6 +10,55 @@ import {
export type StockSolid = 'nacl' | 'cacl2' | 'sand' | 'naoh' | 'na2so4'
+/** Shared spray burst for chemical spit (water / dish / filtrate). */
+function SpitSprayOverlay({
+ originY,
+}: {
+ /** Vertical origin of the droplet cluster in the SVG viewBox. */
+ originY: number
+}) {
+ return (
+
+
+
+
+
+
+
+
+ )
+}
+
/** Fill fraction 0..1 from server amount_ml relative to initial water volume. */
export function waterFillRatio(amountMl: number | null | undefined): number {
if (amountMl == null || amountMl <= 0) return 0
@@ -22,6 +71,7 @@ export function WaterBeakerSvg({
amountMl,
hasAqueous,
dissolveCue,
+ spitCue,
floating,
}: {
leftoverSolid: StockSolid | null
@@ -31,6 +81,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 +107,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 +158,7 @@ export function WaterBeakerSvg({
) : null}
+ {spitCue ? : null}
)
@@ -403,7 +457,16 @@ export function TongsSvg({ floating }: { floating?: boolean }) {
)
}
-export function EvaporationDishSvg({ amountMl, floating }: { amountMl?: number | null; floating?: boolean }) {
+export function EvaporationDishSvg({
+ amountMl,
+ floating,
+ spitCue,
+}: {
+ amountMl?: number | null
+ floating?: boolean
+ /** Silent chemical spit burst from server `last_events`. */
+ spitCue?: boolean
+}) {
const fill = dishFillRatio(amountMl)
const floorY = 42
const height = 16 * fill
@@ -414,6 +477,7 @@ export function EvaporationDishSvg({ amountMl, floating }: { amountMl?: number |
className={floating ? 'h-10 w-20' : 'h-14 w-28'}
aria-hidden
data-dish-fill={fill.toFixed(2)}
+ data-spit-cue={spitCue ? 'burst' : 'none'}
>
) : null}
+ {spitCue ? : null}
)
}
@@ -456,7 +521,16 @@ export function filtrateFillRatio(amountMl: number | null | undefined): number {
return Math.min(1, amountMl / FILTRATE_CAPACITY_ML)
}
-export function FiltrateBeakerSvg({ amountMl, floating }: { amountMl?: number | null; floating?: boolean }) {
+export function FiltrateBeakerSvg({
+ amountMl,
+ floating,
+ spitCue,
+}: {
+ amountMl?: number | null
+ floating?: boolean
+ /** Silent chemical spit burst from server `last_events`. */
+ spitCue?: boolean
+}) {
const fill = filtrateFillRatio(amountMl)
const floorY = 148
const fullHeight = 62
@@ -469,6 +543,7 @@ export function FiltrateBeakerSvg({ amountMl, floating }: { amountMl?: number |
className={floating ? 'h-24 w-16' : 'h-32 w-20'}
aria-hidden
data-filtrate-fill={fill.toFixed(2)}
+ data-spit-cue={spitCue ? 'burst' : 'none'}
>
) : 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..587b1f7 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 (visual-only; no teaching row). */
+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..2049faf 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -282,6 +282,42 @@ body::before {
filter: saturate(1.15);
}
+.lab-spit-drop {
+ opacity: 0;
+ animation: spit-burst 0.85s ease-out 1 forwards;
+}
+
+.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 +334,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 +357,11 @@ body::before {
.lab-water-dissolved-cue {
animation: none;
}
+
+ .lab-spit-drop {
+ animation: none;
+ opacity: 0;
+ }
}
@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..b4d4cc3 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,16 @@ 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.
+///
+/// `allow_spit_mass` is ignored when `apply_heat` is false; on heat, it gates
+/// spray discard (false on clock ticks).
+pub fn speciate_aqueous_acid_base(
+ item: &mut SceneItem,
+ apply_heat: bool,
+ allow_spit_mass: 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 +141,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 +171,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, allow_spit_mass);
}
}
+ false
}
/// Net charge (mol e⁻) of aqueous ions — should be ~0 after speciation.
@@ -190,7 +192,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 {
@@ -235,7 +237,7 @@ mod tests {
#[test]
fn pure_water_speciates_near_ph_7() {
let mut item = vessel(vec![water(100.0)]);
- speciate_aqueous_acid_base(&mut item, false);
+ speciate_aqueous_acid_base(&mut item, false, false);
let ph = ph_of_entries(&item.properties.composition).expect("pH");
assert!((ph - 7.0).abs() < 0.05, "got pH {ph}");
assert!(aqueous_charge_mol(&item).abs() < 1e-12);
@@ -246,7 +248,7 @@ mod tests {
// 0.1 M H₂SO₄ in 1 L → c = 0.1; school [H+] ≈ 0.11 not 0.2.
let c = 0.1;
let mut item = vessel(vec![water(1000.0), aq("h+", c), aq("hso4-", c)]);
- speciate_aqueous_acid_base(&mut item, false);
+ speciate_aqueous_acid_base(&mut item, false, false);
let v_l = solution_volume_ml(&item) / 1000.0;
let c_h = aqueous_mol(&item, "h+") / v_l;
assert!(
@@ -262,12 +264,12 @@ mod tests {
#[test]
fn strong_hcl_and_naoh_extremes() {
let mut acid = vessel(vec![water(100.0), aq("h+", 0.01), aq("cl-", 0.01)]);
- speciate_aqueous_acid_base(&mut acid, false);
+ speciate_aqueous_acid_base(&mut acid, false, false);
let ph_a = ph_of_entries(&acid.properties.composition).unwrap();
assert!((ph_a - 1.0).abs() < 0.05, "0.1 M HCl → pH~1, got {ph_a}");
let mut base = vessel(vec![water(100.0), aq("na+", 0.01), aq("oh-", 0.01)]);
- speciate_aqueous_acid_base(&mut base, false);
+ speciate_aqueous_acid_base(&mut base, false, false);
let ph_b = ph_of_entries(&base.properties.composition).unwrap();
assert!(ph_b > 11.0 && ph_b < 13.0, "got {ph_b}");
}
@@ -283,7 +285,7 @@ mod tests {
aq("oh-", n),
]);
let t0 = item.properties.temperature_c.unwrap();
- speciate_aqueous_acid_base(&mut item, true);
+ speciate_aqueous_acid_base(&mut item, true, true);
let t1 = item.properties.temperature_c.unwrap();
assert!(t1 > t0 + 0.5, "expected neutralization heat {t0} → {t1}");
let ph = ph_of_entries(&item.properties.composition).unwrap();
@@ -304,7 +306,7 @@ mod tests {
]);
let t0 = item.properties.temperature_c.unwrap();
let c0 = effective_heat_capacity(&item);
- speciate_aqueous_acid_base(&mut item, true);
+ speciate_aqueous_acid_base(&mut item, true, true);
let t1 = item.properties.temperature_c.unwrap();
let dt = t1 - t0;
let dt_expected = -n * H_OH_NEUTRALIZATION_J_PER_MOL / c0;
@@ -329,7 +331,7 @@ mod tests {
]);
let t0 = item.properties.temperature_c.unwrap();
let c0 = effective_heat_capacity(&item);
- speciate_aqueous_acid_base(&mut item, true);
+ speciate_aqueous_acid_base(&mut item, true, true);
let t1 = item.properties.temperature_c.unwrap();
let dt = t1 - t0;
let dt_expected = -2.0 * n * H_OH_NEUTRALIZATION_J_PER_MOL / c0;
diff --git a/crates/chemlab-core/src/aqueous_pipeline.rs b/crates/chemlab-core/src/aqueous_pipeline.rs
index 799e1d6..79dc149 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,35 @@ impl FinalizeStage {
FinalizeStage::SyncFillMl,
];
- fn apply(self, item: &mut SceneItem, dissolve_tau_s: f64) {
+ fn apply(self, item: &mut SceneItem, dissolve_tau_s: f64, allow_spit_mass: bool) -> 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);
- }
+ FinalizeStage::KineticDissolve => crate::dissolve_kinetics::apply_kinetic_dissolve(
+ item,
+ dissolve_tau_s,
+ allow_spit_mass,
+ ),
FinalizeStage::SpeciateWithHeat => {
- crate::acid_base::speciate_aqueous_acid_base(item, true);
+ crate::acid_base::speciate_aqueous_acid_base(item, true, allow_spit_mass)
}
FinalizeStage::EnforceSaturation => {
crate::solubility::enforce_saturation(item);
+ false
}
FinalizeStage::SpeciateNoHeatAfterSi | FinalizeStage::SpeciateNoHeatAfterReform => {
- crate::acid_base::speciate_aqueous_acid_base(item, false);
+ let _ = crate::acid_base::speciate_aqueous_acid_base(item, false, false);
+ false
}
FinalizeStage::ReformH2so4 => {
crate::h2so4::reform_aqueous_h2so4_to_liquid(item);
+ false
}
FinalizeStage::SyncFillMl => {
crate::solubility::sync_fill_ml(item);
+ false
}
}
}
@@ -129,22 +136,36 @@ 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).
+///
+/// `allow_spit_mass`: action paths pass `true` (clamp + spray discard); clock
+/// `apply_elapsed` passes `false` (clamp only — spit is action-scoped).
+pub(crate) fn finalize_aqueous_vessel(
+ item: &mut SceneItem,
+ dissolve_tau_s: f64,
+ allow_spit_mass: bool,
+) -> bool {
+ let mut spit = false;
for stage in FinalizeStage::ALL {
- stage.apply(item, dissolve_tau_s);
+ spit |= stage.apply(item, dissolve_tau_s, allow_spit_mass);
}
+ 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,
+ allow_spit_mass: bool,
+) -> bool {
let water_ml = target
.properties
.composition
@@ -153,15 +174,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, allow_spit_mass)
}
#[cfg(test)]
diff --git a/crates/chemlab-core/src/dissolve_kinetics.rs b/crates/chemlab-core/src/dissolve_kinetics.rs
index 61824c7..aa381a0 100644
--- a/crates/chemlab-core/src/dissolve_kinetics.rs
+++ b/crates/chemlab-core/src/dissolve_kinetics.rs
@@ -101,25 +101,33 @@ 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,
+ allow_spit_mass: bool,
+) -> 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, allow_spit_mass);
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, allow_spit_mass: bool) -> 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 +151,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, allow_spit_mass);
}
}
+ 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 +185,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 +203,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 {
@@ -320,7 +330,7 @@ mod tests {
..ItemProperties::default()
},
};
- apply_kinetic_dissolve(&mut beaker, 2.0);
+ apply_kinetic_dissolve(&mut beaker, 2.0, true);
assert!(
(solid_amount_g(
beaker
@@ -365,7 +375,7 @@ mod tests {
};
// Long contact approaches the SI capacity; further time adds negligibly.
for _ in 0..6 {
- apply_kinetic_dissolve(&mut dish, 2.0);
+ apply_kinetic_dissolve(&mut dish, 2.0, true);
}
let na = aqueous_mol(&dish, "na+");
let cap_mol =
@@ -428,7 +438,7 @@ mod tests {
..ItemProperties::default()
},
};
- apply_kinetic_dissolve_step(&mut beaker, POUR_CONTACT_TAU_S);
+ apply_kinetic_dissolve_step(&mut beaker, POUR_CONTACT_TAU_S, true);
let t = beaker.properties.temperature_c.unwrap();
let ca = aqueous_mol(&beaker, "ca2+");
let na = aqueous_mol(&beaker, "na+");
diff --git a/crates/chemlab-core/src/lib.rs b/crates/chemlab-core/src/lib.rs
index 9593110..cb845f7 100644
--- a/crates/chemlab-core/src/lib.rs
+++ b/crates/chemlab-core/src/lib.rs
@@ -34,10 +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,
+ 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,
diff --git a/crates/chemlab-core/src/scene.rs b/crates/chemlab-core/src/scene.rs
index 0273fd8..aa582bd 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,12 @@ 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,
+ true,
);
+ note_chemical_spit(scene, spit);
return Ok(());
}
@@ -1127,10 +1134,12 @@ fn apply_pour(
});
}
- finalize_aqueous_vessel(
+ let spit = finalize_aqueous_vessel(
&mut scene.items[target_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
+ true,
);
+ note_chemical_spit(scene, spit);
Ok(())
}
@@ -1293,8 +1302,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 +1345,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, true);
+ note_chemical_spit(scene, spit);
let pipette = &mut scene.items[tool_idx];
pipette.location = "hand".into();
@@ -1423,11 +1433,13 @@ 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,
+ true,
);
+ note_chemical_spit(scene, spit_mix || spit_fin);
let pipette = &mut scene.items[tool_idx];
pipette.properties.holding.clear();
@@ -1642,17 +1654,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, true);
// 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, true);
+ let spit_dest = finalize_aqueous_vessel(&mut scene.items[dest_idx], 0.0, true);
+ 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 +1805,14 @@ 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, true);
+ let spit_dest = finalize_aqueous_vessel(
&mut scene.items[dest_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
+ true,
);
+ 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 +1830,14 @@ 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, true);
+ let spit_dest = finalize_aqueous_vessel(
&mut scene.items[dest_idx],
crate::dissolve_kinetics::POUR_CONTACT_TAU_S,
+ true,
);
+ 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 +1997,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 +2011,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 +2031,90 @@ 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, true)
}
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, true)
}
-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. When `allow_spit_mass` is true (action paths), also discard
+/// [`CHEMICAL_SPIT_FRAC`] of composition and return `true` so the caller can emit
+/// at most one silent `spit` event per action. Clock ticks pass `false` — clamp
+/// only, no spray mass / event (spit is action-scoped). Burner continuous boil
+/// stays on the thermal path.
+pub(crate) fn apply_chemical_heat(target: &mut SceneItem, q_j: f64, allow_spit_mass: bool) -> 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);
+ if !allow_spit_mass {
+ return false;
+ }
+ 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/evaporation.rs b/crates/chemlab-core/src/scene_tests/evaporation.rs
index d797062..85549d3 100644
--- a/crates/chemlab-core/src/scene_tests/evaporation.rs
+++ b/crates/chemlab-core/src/scene_tests/evaporation.rs
@@ -387,7 +387,7 @@ fn heat_redissolve_approaches_new_capacity_over_multiple_ticks() {
{
let dish = scene.items.iter_mut().find(|i| i.id == "dish-1").unwrap();
- crate::dissolve_kinetics::apply_kinetic_dissolve(dish, 0.3);
+ crate::dissolve_kinetics::apply_kinetic_dissolve(dish, 0.3, true);
}
let na_one = aqueous_mol(item(&scene, "dish-1"), "na+");
let frac_one = (na_one - na_cold) / opened;
@@ -399,7 +399,7 @@ fn heat_redissolve_approaches_new_capacity_over_multiple_ticks() {
for _ in 0..8 {
let dish = scene.items.iter_mut().find(|i| i.id == "dish-1").unwrap();
dish.properties.temperature_c = Some(60.0);
- crate::dissolve_kinetics::apply_kinetic_dissolve(dish, 0.5);
+ crate::dissolve_kinetics::apply_kinetic_dissolve(dish, 0.5, true);
}
let na_many = aqueous_mol(item(&scene, "dish-1"), "na+");
assert!(
diff --git a/crates/chemlab-core/src/scene_tests/h2so4.rs b/crates/chemlab-core/src/scene_tests/h2so4.rs
index f7c07fa..88f0e91 100644
--- a/crates/chemlab-core/src/scene_tests/h2so4.rs
+++ b/crates/chemlab-core/src/scene_tests/h2so4.rs
@@ -529,3 +529,160 @@ 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}");
+}
+
+#[test]
+fn chemical_heat_clock_mode_clamps_without_spit_mass() {
+ // allow_spit_mass=false (clock): clamp at boil, no spray discard, no spit flag.
+ let mut item = item(&initial_bench_scene("lab-test"), "beaker-water").clone();
+ item.properties.temperature_c = Some(95.0);
+ item.properties.fill_ml = Some(10.0);
+ item.properties.composition = vec![CompositionEntry {
+ substance_id: "water".into(),
+ phase: "liquid".into(),
+ amount_ml: Some(10.0),
+ amount_scoop: None,
+ amount_g: None,
+ amount_mol: None,
+ }];
+ crate::solubility::sync_fill_ml(&mut item);
+ let v0 = crate::hcl::solution_volume_ml(&item);
+ let c = effective_heat_capacity(&item);
+ let q = -c * 20.0; // proposed T = 115 °C → overshoot
+ let spit = apply_chemical_heat(&mut item, q, false);
+ assert!(!spit);
+ let t_boil = vessel_boil_temperature_c(&item);
+ assert!(
+ (item.properties.temperature_c.unwrap() - t_boil).abs() < 0.05,
+ "expected clamp at boil"
+ );
+ assert!(
+ (crate::hcl::solution_volume_ml(&item) - v0).abs() < 1e-9,
+ "clock mode must not discard spit fraction"
+ );
+
+ let mut item2 = item.clone();
+ item2.properties.temperature_c = Some(95.0);
+ crate::solubility::sync_fill_ml(&mut item2);
+ let spit_action = apply_chemical_heat(&mut item2, q, true);
+ assert!(spit_action);
+ assert!(crate::hcl::solution_volume_ml(&item2) < v0 * (1.0 - CHEMICAL_SPIT_FRAC * 0.5));
+}
diff --git a/crates/chemlab-core/src/thermal.rs b/crates/chemlab-core/src/thermal.rs
index ba3eeea..9f5a8bb 100644
--- a/crates/chemlab-core/src/thermal.rs
+++ b/crates/chemlab-core/src/thermal.rs
@@ -43,7 +43,7 @@ pub fn apply_elapsed(scene: &mut Scene, dt_s: f64) {
&& crate::solubility::dish_has_liquid(&scene.items[dish_idx])
{
apply_dish_evaporation(&mut scene.items[dish_idx], dt, heating_dish);
- finalize_aqueous_vessel(&mut scene.items[dish_idx], dt);
+ finalize_aqueous_vessel(&mut scene.items[dish_idx], dt, false);
finalized_dish = true;
if let Some(burner_idx) = burner_idx {
if scene.items[burner_idx].properties.on == Some(true)
@@ -75,7 +75,7 @@ pub fn apply_elapsed(scene: &mut Scene, dt_s: f64) {
continue;
}
if crate::dissolve_kinetics::vessel_needs_kinetic_dissolve(&scene.items[idx]) {
- finalize_aqueous_vessel(&mut scene.items[idx], dt);
+ finalize_aqueous_vessel(&mut scene.items[idx], dt, false);
}
}
}
@@ -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..13fee66 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. On **action** paths it also 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. Clock `apply_elapsed` kinetic/speciate heat uses the same clamp but **does not** discard spray mass or emit `spit` (spit is action-scoped). 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 (water, dish, or filtrate; `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.