Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src-tauri/src/app_services.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,7 @@ impl CompanionService {
let db = FilamentDatabase::open(&self.db_path)?;
let rows = db.with_read_transaction(|snapshot| {
let rows = snapshot.list_printer_overview()?;
let mut integrations = snapshot.list_bambu_live_integrations()?;
crate::bambu_live_sync::refresh_inventory_match_status(snapshot, &mut integrations)?;
let integrations = crate::bambu_live_sync::printer_display_integrations(snapshot)?;
let mut rows = enrich_printer_overview_with_live_slots(rows, &integrations);
for printer in &mut rows {
for slot in &mut printer.slots {
Expand Down
5 changes: 2 additions & 3 deletions src-tauri/src/app_services_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1736,9 +1736,8 @@ fn printer_reads_reconcile_saved_rfid_without_a_new_mqtt_observation_or_writes()
);

// Both desktop and Companion settings use this same read-only reconciliation.
let mut entries = db.list_bambu_live_integrations().expect("entries");
crate::bambu_live_sync::refresh_inventory_match_status(&db, &mut entries)
.expect("settings match");
let entries =
crate::bambu_live_sync::printer_display_integrations(&db).expect("settings match");
let tray = &entries[0].config.observed_state.as_ref().unwrap().trays[0];
assert_eq!(tray.match_status.as_deref(), Some("clear_match"));
assert_eq!(
Expand Down
40 changes: 40 additions & 0 deletions src-tauri/src/bambu_live_observation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,46 @@ pub(crate) fn merge_idle_observation(
next
}

/// Filter the display copy only. The MQTT baseline and diagnostics retain the original report.
pub(crate) fn hide_finished_job_fields(
observed: &mut BambuLiveObservedStateRow,
finished_at: &str,
) {
let Some(end) = parse_flexible_timestamp(Some(finished_at)) else {
return;
};
let fields = observed
.raw_payload_json
.as_ref()
.and_then(|raw| raw.get("_bfm_observed_fields"));
let belongs_to_finished_job = |key: &str| {
// For legacy snapshots without a field clock, only discard what the snapshot itself dates.
let at = fields
.and_then(|fields| fields.get(key))
.and_then(Value::as_str)
.or(observed.last_seen_at.as_deref());
parse_flexible_timestamp(at).is_some_and(|seen| seen <= end)
};
// A late 100% report must not turn a previously explicit stop into an active job.
let terminal = matches!(
normalized_gcode_state(observed.gcode_state.as_deref()).as_deref(),
Some("FINISH" | "FINISHED" | "IDLE" | "FAILED" | "STOP" | "STOPPED" | "CANCELLED")
);
if !terminal && belongs_to_finished_job("gcode_state_at") {
observed.gcode_state = None;
}
if belongs_to_finished_job("progress_percent_at") {
observed.progress_percent = None;
}
if belongs_to_finished_job("remaining_minutes_at") {
observed.remaining_minutes = None;
}
if belongs_to_finished_job("job_identity_at") {
observed.subtask_id = None;
observed.subtask_name = None;
}
}

fn should_drop_carried_job_identity(
previous: &BambuLiveObservedStateRow,
next: &BambuLiveObservedStateRow,
Expand Down
161 changes: 161 additions & 0 deletions src-tauri/src/bambu_live_observation_delta_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,167 @@ fn receive(
));
}

#[test]
fn closed_job_fields_stay_hidden_on_refresh_and_restart_despite_new_mqtt_reports() {
use crate::backend::database_printer_usage_sessions::LiveUsageSessionInput;
use crate::backend::filament_database::{BambuLiveIntegrationRow, FilamentDatabase};
use crate::bambu_live_sync::printer_display_integrations;

let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("printer.db");
let db = FilamentDatabase::open(&path).unwrap();
db.apply_schema().unwrap();
db.upsert_printer_with_ams("p1s", "Bambu Lab P1S", "Test printer", 1, 4)
.unwrap();
let session = LiveUsageSessionInput {
printer_id: "p1s",
session_key: "subtask:1",
job_name: Some("Completed plate"),
print_type: Some("cloud"),
observed_at: Some("2026-12-02T13:04:24+01:00"),
};
db.touch_live_usage_session(session).unwrap();
let mut job = poll();
receive(
&mut job,
None,
"2026-12-02T13:04:24+01:00",
json!({"gcode_state":"PREPARE","print_type":"cloud"}),
);
receive(
&mut job,
None,
"2026-12-02T14:03:27+01:00",
json!({"mc_percent":92}),
);
receive(
&mut job,
None,
"2026-12-02T14:05:22+01:00",
json!({"mc_remaining_time":2}),
);
db.finish_live_usage_session("p1s", "subtask:1", Some("2026-12-02T14:10:26+01:00"), true)
.unwrap();
let mut delta = poll();
receive(
&mut delta,
Some(&job),
"2026-12-02T22:42:47+01:00",
json!({"command":"push_status","nozzle_temper":25.84}),
);
let merged = merge_idle_observation(Some(&job), delta);
assert_eq!(merged.gcode_state.as_deref(), Some("PREPARE"));
let mut config: BambuLiveIntegrationRow =
serde_json::from_value(json!({"enabled":true})).unwrap();
config.observed_state = Some(merged.clone());
db.save_bambu_live_integration("p1s", &config).unwrap();
let display = |db: &FilamentDatabase| {
db.with_read_transaction(printer_display_integrations)
.unwrap()
.remove(0)
.config
.observed_state
.unwrap()
};
let assert_closed = |db: &FilamentDatabase| {
let observed = display(db);
assert_eq!(
(
observed.gcode_state,
observed.progress_percent,
observed.remaining_minutes
),
(None, None, None)
);
assert!(observed.online && observed.mqtt_connected);
assert_eq!(observed.nozzle_temp_c, Some(25.84));
assert_eq!(observed.last_seen_at, merged.last_seen_at);
};
assert_closed(&db);
drop(db);
let db = FilamentDatabase::open(&path).unwrap();
assert_closed(&db);
assert_eq!(
db.list_bambu_live_integrations().unwrap()[0]
.config
.observed_state
.as_ref(),
Some(&merged)
);

// A new job can report just its phase first, before it creates a usage session.
let mut previous = merged;
for (phase, at) in [
("RUNNING", "2026-12-02T23:00:00+01:00"),
("PAUSE", "2026-12-02T23:01:00+01:00"),
] {
let mut delta = poll();
receive(
&mut delta,
Some(&previous),
at,
json!({"gcode_state":phase}),
);
previous = merge_idle_observation(Some(&previous), delta);
config.observed_state = Some(previous.clone());
db.save_bambu_live_integration("p1s", &config).unwrap();
let observed = display(&db);
assert_eq!(observed.gcode_state.as_deref(), Some(phase));
assert_eq!(
(observed.progress_percent, observed.remaining_minutes),
(None, None)
);
}

// Rolling over a session can close the previous job and open its successor at the same instant.
db.touch_live_usage_session(LiveUsageSessionInput {
printer_id: "p1s",
session_key: "subtask:2",
job_name: None,
print_type: None,
observed_at: Some("2026-12-02T23:01:00+01:00"),
})
.unwrap();
assert_eq!(db.last_closed_print_at_if_idle("p1s").unwrap(), None);
assert_eq!(display(&db).gcode_state.as_deref(), Some("PAUSE"));
}

#[test]
fn running_and_paused_job_evidence_survives_unrelated_deltas_between_updates() {
for phase in ["RUNNING", "PAUSE"] {
let mut job = poll();
receive(
&mut job,
None,
FIRST,
json!({"gcode_state":phase,"mc_percent":42,"mc_remaining_time":17}),
);
let mut delta = poll();
receive(
&mut delta,
Some(&job),
"2026-11-30T15:20:00Z",
json!({"hms":[]}),
);
let mut shown = merge_idle_observation(Some(&job), delta);
hide_finished_job_fields(&mut shown, "2026-11-30T14:00:00Z");
assert_eq!(shown.gcode_state.as_deref(), Some(phase));
assert_eq!(
(shown.progress_percent, shown.remaining_minutes),
(Some(42), Some(17))
);
}
}

#[test]
fn a_late_progress_report_cannot_revive_a_terminal_job() {
let mut job = poll();
receive(&mut job, None, FIRST, json!({"gcode_state":"FINISH"}));
receive(&mut job, None, LATER, json!({"mc_percent":100}));
hide_finished_job_fields(&mut job, EMPTY);
assert_eq!(job.gcode_state.as_deref(), Some("FINISH"));
}

fn initial_trays() -> BambuLiveObservedStateRow {
let mut state = poll();
receive(
Expand Down
17 changes: 9 additions & 8 deletions src-tauri/src/bambu_live_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,24 @@ use crate::backend::filament_database::{
use crate::bambu_live_matching::match_observed_trays;
use crate::bambu_live_usage::sync_observed_usage;

/// Reconcile derived matches with the current inventory on reads. Saving RFID or
/// creating a catalog roll does not change the printer's observation timestamp.
/// This deliberately excludes usage synchronization and automatic slot writes.
pub(crate) fn refresh_inventory_match_status(
/// Build the read-only telemetry shared by desktop and paired clients from one DB snapshot.
pub(crate) fn printer_display_integrations(
db: &FilamentDatabase,
integrations: &mut [BambuLiveIntegrationEntryRow],
) -> Result<(), InventoryError> {
for entry in integrations {
) -> Result<Vec<BambuLiveIntegrationEntryRow>, InventoryError> {
let mut integrations = db.list_bambu_live_integrations()?;
for entry in &mut integrations {
let Some(observed) = entry.config.observed_state.as_mut() else {
continue;
};
let Some(overview) = db.get_printer_overview(&entry.printer_id)? else {
continue;
};
match_observed_trays(db, &overview, &mut observed.trays)?;
if let Some(finished_at) = db.last_closed_print_at_if_idle(&entry.printer_id)? {
crate::bambu_live_observation::hide_finished_job_fields(observed, &finished_at);
}
}
Ok(())
Ok(integrations)
}

pub(crate) fn enrich_with_match_status(
Expand Down
7 changes: 2 additions & 5 deletions src-tauri/src/companion_library_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,11 +377,8 @@ pub(super) async fn handle_library_printer_settings(
let db = FilamentDatabase::open(&state.db_path).map_err(CompanionApiError::from)?;
let (bambu_live_integrations, printers) = db
.with_read_transaction(|snapshot| {
let mut integrations = snapshot.list_bambu_live_integrations()?;
crate::bambu_live_sync::refresh_inventory_match_status(
snapshot,
&mut integrations,
)?;
let integrations =
crate::bambu_live_sync::printer_display_integrations(snapshot)?;
Ok((integrations, snapshot.list_printers()?))
})
.map_err(CompanionApiError::from)?;
Expand Down
9 changes: 1 addition & 8 deletions src-tauri/src/printer_settings_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,7 @@ pub(crate) fn get_printer_settings(
) -> Result<PrinterSettingsSnapshot, String> {
let bambu_live_integrations = sanitized_bambu_live_integrations(
with_db(&state, |db| {
db.with_read_transaction(|snapshot| {
let mut integrations = snapshot.list_bambu_live_integrations()?;
crate::bambu_live_sync::refresh_inventory_match_status(
snapshot,
&mut integrations,
)?;
Ok(integrations)
})
db.with_read_transaction(crate::bambu_live_sync::printer_display_integrations)
})?,
&state.credentials,
false,
Expand Down
9 changes: 8 additions & 1 deletion src/backend/database_printer_facade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::database_printer_queries::{
use super::database_printer_slot_assignment::assign_spool_to_ams_slot as assign_spool_to_ams_slot_row;
use super::database_printer_usage_sessions::{
correct_live_usage_for_observed_weight_increase as correct_live_usage_for_observed_weight_increase_row,
finish_live_usage_session as finish_live_usage_session_row,
finish_live_usage_session as finish_live_usage_session_row, last_closed_print_at_if_idle,
live_usage_session_has_spool_usage as live_usage_session_has_spool_usage_row,
live_usage_session_is_active as live_usage_session_is_active_row,
live_usage_session_recently_completed_successfully as live_usage_session_recently_completed_successfully_row,
Expand Down Expand Up @@ -224,6 +224,13 @@ impl FilamentDatabase {
)
}

pub fn last_closed_print_at_if_idle(
&self,
printer_id: &str,
) -> InventoryResult<Option<String>> {
last_closed_print_at_if_idle(self.connection(), printer_id)
}

pub fn live_usage_session_is_active(
&self,
printer_id: &str,
Expand Down
13 changes: 13 additions & 0 deletions src/backend/database_printer_usage_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,19 @@ pub(crate) fn finish_live_usage_session(
Ok(())
}

/// An open session can share its first observation with the end of the previous job.
pub(crate) fn last_closed_print_at_if_idle(
conn: &Connection,
printer_id: &str,
) -> InventoryResult<Option<String>> {
Ok(conn.query_row(
"SELECT CASE WHEN COUNT(*) = COUNT(finished_at) THEN MAX(strftime('%Y-%m-%dT%H:%M:%fZ', finished_at)) END
FROM printer_live_usage_sessions WHERE printer_id = ?1",
[printer_id],
|row| row.get(0),
)?)
}

pub(crate) fn live_usage_session_is_active(
conn: &Connection,
printer_id: &str,
Expand Down
27 changes: 27 additions & 0 deletions ui/src/components/dashboard_printer_overview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ registerHooks({
},
});
const { DashboardPrinterOverview } = await import("./dashboard_printer_overview");
const { PrinterOverviewCardHeader } = await import("./printer_overview_card_header");
(globalThis as typeof globalThis & { React: typeof React }).React = React;
const i18n: I18nContextValue = {
locale: "en",
Expand Down Expand Up @@ -64,6 +65,32 @@ test("compact dashboard printer cards show accessible real print progress and re
assert.match(html, /<button type="button"[^>]*>Open printers/);
});

test("printer and dashboard cards use the projected job fields after reopening", () => {
const restored: BambuLiveIntegrationSettings = {
...config,
observed_state: {
online: true, mqtt_connected: true, last_seen_at: new Date().toISOString(), trays: [],
nozzle_temp_c: 25.84, print_type: "cloud", gcode_state: null,
progress_percent: null, remaining_minutes: null, subtask_name: null,
raw_payload_json: { _bfm_job: { gcode_state: "PREPARE", progress_percent: 92, remaining_minutes: 2 } },
},
};
for (const [phase, label] of [[null, "Idle"], ["RUNNING", "Printing"], ["PAUSE", "Paused"]] as const) {
const liveConfig = { ...restored, observed_state: { ...restored.observed_state!, gcode_state: phase } };
const header = renderToStaticMarkup(
<I18nContext.Provider value={i18n}>
<PrinterOverviewCardHeader printer={printer} liveConfig={liveConfig} hasMultiMaterial
liveConnectionIndicator={null} resolvedTheme="light" />
</I18nContext.Provider>,
);
for (const html of [header, render({ bambuLiveIntegrations: { bambu: liveConfig } })]) {
assert.ok(html.includes(`>${label}<`));
assert.match(html, /26°C/);
assert.doesNotMatch(html, /Preparing|92%|2 min|role="progressbar"/);
}
}
});

test("manual Prusa and disconnected host cards never show fabricated current print progress", () => {
const prusa = { ...printer, printer: { ...printer.printer, model: "Prusa MK4S" } };
const manual = render({ printers: [prusa] });
Expand Down
Loading