amsHelpers.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /**
  2. * AMS (Automatic Material System) helper utilities for Bambu Lab printers.
  3. * These functions handle color normalization, slot labeling, and tray ID calculations
  4. * for AMS, AMS-HT, and external spool configurations.
  5. */
  6. import { parseUTCDate } from './date';
  7. /**
  8. * Normalize color format from various sources for CSS rendering.
  9. * API returns "RRGGBBAA" (8-char), 3MF uses "#RRGGBB" (7-char with hash).
  10. * Result is "#RRGGBB" for opaque colors and "#RRGGBBAA" when alpha < FF —
  11. * CSS accepts both forms on `fill` / `backgroundColor`, and preserving alpha
  12. * lets transparent filaments render translucent instead of collapsing to
  13. * solid black (#1545). Comparison helpers use normalizeColorForCompare which
  14. * still strips alpha, so type/colour matching is unaffected.
  15. */
  16. export function normalizeColor(color: string | null | undefined): string {
  17. if (!color) return '#808080';
  18. const clean = color.replace('#', '');
  19. if (clean.length >= 8 && clean.substring(6, 8).toLowerCase() !== 'ff') {
  20. return `#${clean.substring(0, 8)}`;
  21. }
  22. return `#${clean.substring(0, 6)}`;
  23. }
  24. /**
  25. * Normalize color for comparison (case-insensitive, strip hash and alpha).
  26. */
  27. export function normalizeColorForCompare(color: string | undefined): string {
  28. if (!color) return '';
  29. return color.replace('#', '').toLowerCase().substring(0, 6);
  30. }
  31. /**
  32. * AMS unit label using the codebase convention: "AMS-A / AMS-B / ..." for
  33. * regular AMS, "HT-A / HT-B / ..." for AMS-HT (single-tray modules with
  34. * IDs starting at 128). `trayCount` is required because the type can't be
  35. * inferred from the id alone — regular AMS IDs 0-3 can collide with the
  36. * normalized HT range otherwise.
  37. */
  38. export function getAmsLabel(amsId: number | string, trayCount: number): string {
  39. const id = typeof amsId === 'string' ? parseInt(amsId, 10) : amsId;
  40. const safeId = isNaN(id) ? 0 : id;
  41. if (safeId === 255) return 'External';
  42. // A2L "AMS Lite": the backend normalises its physical unit id 16 to 6 at
  43. // ingest (see a2l-am-unit-16). No regular AMS uses id 6, so this is a safe,
  44. // self-scoping label for the Lite's 4-slot unit.
  45. if (safeId === 6) return 'AMS Lite';
  46. const isHt = trayCount === 1;
  47. const normalizedId = safeId >= 128 ? safeId - 128 : safeId;
  48. const letter = String.fromCharCode(65 + normalizedId);
  49. return isHt ? `HT-${letter}` : `AMS-${letter}`;
  50. }
  51. /**
  52. * Filament type equivalence groups.
  53. * Types within the same group are interchangeable on the printer side
  54. * (e.g., Bambu Lab firmware treats PA-CF and PA12-CF as compatible).
  55. */
  56. const FILAMENT_TYPE_GROUPS: string[][] = [
  57. ['PA-CF', 'PA12-CF', 'PAHT-CF'],
  58. ];
  59. const _equivalenceMap: Record<string, string> = {};
  60. for (const group of FILAMENT_TYPE_GROUPS) {
  61. const canonical = group[0];
  62. for (const t of group) {
  63. _equivalenceMap[t.toUpperCase()] = canonical.toUpperCase();
  64. }
  65. }
  66. /**
  67. * Get the canonical filament type for equivalence matching.
  68. * Types in the same group (e.g., PA-CF / PA12-CF / PAHT-CF) return the same canonical type.
  69. */
  70. export function canonicalFilamentType(type: string | undefined): string {
  71. if (!type) return '';
  72. const upper = type.toUpperCase();
  73. return _equivalenceMap[upper] ?? upper;
  74. }
  75. /**
  76. * Check if two filament types are compatible (same type or same equivalence group).
  77. */
  78. export function filamentTypesCompatible(a: string | undefined, b: string | undefined): boolean {
  79. return canonicalFilamentType(a) === canonicalFilamentType(b);
  80. }
  81. /**
  82. * Check if two colors are visually similar within a threshold.
  83. * Uses RGB component comparison with configurable tolerance.
  84. * @param color1 - First hex color
  85. * @param color2 - Second hex color
  86. * @param threshold - Maximum difference per RGB component (default: 40)
  87. */
  88. export function colorsAreSimilar(
  89. color1: string | undefined,
  90. color2: string | undefined,
  91. threshold = 40
  92. ): boolean {
  93. const hex1 = normalizeColorForCompare(color1);
  94. const hex2 = normalizeColorForCompare(color2);
  95. if (!hex1 || !hex2 || hex1.length < 6 || hex2.length < 6) return false;
  96. const r1 = parseInt(hex1.substring(0, 2), 16);
  97. const g1 = parseInt(hex1.substring(2, 4), 16);
  98. const b1 = parseInt(hex1.substring(4, 6), 16);
  99. const r2 = parseInt(hex2.substring(0, 2), 16);
  100. const g2 = parseInt(hex2.substring(2, 4), 16);
  101. const b2 = parseInt(hex2.substring(4, 6), 16);
  102. return (
  103. Math.abs(r1 - r2) <= threshold &&
  104. Math.abs(g1 - g2) <= threshold &&
  105. Math.abs(b1 - b2) <= threshold
  106. );
  107. }
  108. /**
  109. * Format slot label for display in the UI.
  110. * @param amsId - AMS unit ID (0-3 for regular AMS, 128+ for AMS-HT)
  111. * @param trayId - Tray/slot ID within the AMS unit (0-3)
  112. * @param isHt - Whether this is an AMS-HT unit (single tray)
  113. * @param isExternal - Whether this is the external spool holder
  114. */
  115. export function formatSlotLabel(
  116. amsId: number,
  117. trayId: number,
  118. isHt: boolean,
  119. isExternal: boolean
  120. ): string {
  121. if (isExternal) return 'Ext';
  122. // Convert AMS ID to letter (A, B, C, D)
  123. // AMS-HT uses IDs starting at 128
  124. const letter = String.fromCharCode(65 + (amsId >= 128 ? amsId - 128 : amsId));
  125. if (isHt) return `HT-${letter}`;
  126. return `${letter}${trayId + 1}`;
  127. }
  128. /**
  129. * Calculate global tray ID for MQTT command.
  130. * Used in the ams_mapping array sent to the printer.
  131. * @param amsId - AMS unit ID (0-3 for regular AMS, 128+ for AMS-HT)
  132. * @param trayId - Tray/slot ID within the AMS unit
  133. * @param isExternal - Whether this is the external spool holder
  134. * @returns Global tray ID (0-15 for AMS, 128+ for AMS-HT, 254 for external)
  135. */
  136. export function getGlobalTrayId(
  137. amsId: number,
  138. trayId: number,
  139. isExternal: boolean
  140. ): number {
  141. if (isExternal) return 254 + trayId;
  142. // AMS-HT units have IDs starting at 128 with a single tray — use ID directly
  143. if (amsId >= 128) return amsId;
  144. return amsId * 4 + trayId;
  145. }
  146. /**
  147. * Get fill bar color based on spool fill level.
  148. * Matches PrintersPage thresholds and Bambu Lab brand green.
  149. */
  150. export function getFillBarColor(fillLevel: number): string {
  151. if (fillLevel > 50) return '#00ae42'; // Green - good
  152. if (fillLevel >= 15) return '#f59e0b'; // Amber - warning (<= 50%)
  153. return '#ef4444'; // Red - critical (< 15%)
  154. }
  155. /**
  156. * Calculate fill level from Spoolman weight data.
  157. * Used as the first source in the Spoolman → Inventory → AMS fill chain.
  158. */
  159. export function getSpoolmanFillLevel(
  160. linkedSpool: { remaining_weight: number | null; filament_weight: number | null } | undefined
  161. ): number | null {
  162. if (!linkedSpool?.remaining_weight || !linkedSpool?.filament_weight
  163. || linkedSpool.filament_weight <= 0) return null;
  164. return Math.min(100, Math.round(
  165. (linkedSpool.remaining_weight / linkedSpool.filament_weight) * 100
  166. ));
  167. }
  168. function toFixedHex(value: number, width: number): string {
  169. const safe = Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
  170. return safe.toString(16).toUpperCase().padStart(width, '0').slice(-width);
  171. }
  172. // 32-bit FNV-1a hash -> 8-char hex (stable for alphanumeric serials)
  173. function hashSerialToHex32(serial: string): string {
  174. const input = (serial || '').trim().toUpperCase();
  175. let hash = 0x811c9dc5;
  176. for (let i = 0; i < input.length; i++) {
  177. hash ^= input.charCodeAt(i);
  178. hash = Math.imul(hash, 0x01000193);
  179. }
  180. return (hash >>> 0).toString(16).toUpperCase().padStart(8, '0');
  181. }
  182. /**
  183. * Generate a stable fallback spool tag for slots without RFID identifiers.
  184. * Returns a 16-char hex string derived from the printer serial + slot position.
  185. */
  186. export function getFallbackSpoolTag(printerSerial: string, amsId: number, trayId: number): string {
  187. return `${hashSerialToHex32(printerSerial)}${toFixedHex(amsId, 4)}${toFixedHex(trayId, 4)}`;
  188. }
  189. /**
  190. * Get minimum datetime for scheduling (now + 1 minute).
  191. * Returns ISO string format for datetime-local input.
  192. */
  193. export function getMinDateTime(): string {
  194. const now = new Date();
  195. now.setMinutes(now.getMinutes() + 1);
  196. return now.toISOString().slice(0, 16);
  197. }
  198. /**
  199. * Check if a scheduled time is a placeholder far-future date.
  200. * Placeholder dates (more than 6 months out) are treated as ASAP.
  201. */
  202. export function isPlaceholderDate(scheduledTime: string | null | undefined): boolean {
  203. if (!scheduledTime) return false;
  204. const sixMonthsFromNow = Date.now() + 180 * 24 * 60 * 60 * 1000;
  205. return (parseUTCDate(scheduledTime)?.getTime() ?? 0) > sixMonthsFromNow;
  206. }
  207. /**
  208. * Banding tie-break for `preferLowestSortKey`, mirroring backend
  209. * `PrintScheduler._slot_priority` so regular AMS < AMS-HT < external on ties
  210. * regardless of the raw `ams_id`. In particular, `ams_id = -1` (VT / external
  211. * in `buildLoadedFilaments`) MUST NOT sort to a negative number or it would
  212. * beat AMS slot 0 — backend clamps to 10_000.
  213. */
  214. function slotPriority(amsId: number | undefined, trayId: number | undefined): number {
  215. if (amsId == null || amsId < 0) return 10_000;
  216. if (amsId >= 128) return 1_000 + (amsId - 128) * 4 + (trayId ?? 0);
  217. return amsId * 4 + (trayId ?? 0);
  218. }
  219. /**
  220. * Two-tier sort key for the "Prefer Lowest Remaining Filament" preference (#1766).
  221. *
  222. * Mirrors backend `_prefer_lowest_sort_key` in `print_scheduler.py:1161` so the
  223. * client-side sort that PrintModal pre-computes lines up with the dispatch-time
  224. * sort. Inventory-bound spools sort before MQTT-only ones (tier 0 vs tier 1) so
  225. * the user's tracked grams beat the printer's per-cent estimate; within each
  226. * tier the lowest value wins, with the slot-position tie-break above so the
  227. * order is deterministic across identical spools.
  228. *
  229. * `inventoryByTrayId` is the `globalTrayId -> grams_remaining` map derived from
  230. * the user's spool assignments. Pass `undefined` to fall back to remain%-only
  231. * sorting (preserves pre-#1766 behaviour for callers that don't yet wire it in).
  232. */
  233. export function preferLowestSortKey(
  234. f: { globalTrayId: number; amsId?: number; trayId?: number; remain?: number },
  235. inventoryByTrayId: Map<number, number> | undefined,
  236. ): [number, number, number] {
  237. const slot = slotPriority(f.amsId, f.trayId);
  238. if (inventoryByTrayId && inventoryByTrayId.has(f.globalTrayId)) {
  239. return [0, inventoryByTrayId.get(f.globalTrayId) ?? 0, slot];
  240. }
  241. const remain = f.remain ?? -1;
  242. return [1, remain >= 0 ? remain : 101, slot];
  243. }
  244. /** Tuple compare for `preferLowestSortKey` outputs. */
  245. export function compareSortKeys(
  246. a: [number, number, number],
  247. b: [number, number, number],
  248. ): number {
  249. return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
  250. }
  251. /**
  252. * Effective "Prefer lowest remaining filament" preference for a given printer,
  253. * gated on its AMS Filament Backup state (#1766).
  254. *
  255. * Without backup, the printer can't switch to a second spool when the picked
  256. * one runs out — so even with the user setting on, sorting toward the lowest
  257. * leaves the print at risk. Mirrors the backend gate in
  258. * `print_scheduler.py::_compute_ams_mapping_for_printer`. `null`/`undefined`
  259. * (unknown state, e.g. A1 family) preserves today's behaviour intentionally.
  260. */
  261. export function effectivePreferLowest(
  262. setting: boolean | undefined,
  263. amsFilamentBackup: boolean | null | undefined,
  264. ): boolean {
  265. if (!setting) return false;
  266. return amsFilamentBackup !== false;
  267. }
  268. /**
  269. * Auto-match a filament requirement to a loaded filament, respecting nozzle constraints.
  270. * Used by both single-printer (FilamentMapping) and multi-printer (InlineMappingEditor) paths.
  271. */
  272. export function autoMatchFilament(
  273. req: { type?: string; color?: string; nozzle_id?: number | null },
  274. loadedFilaments: { globalTrayId: number; amsId?: number; trayId?: number; type?: string; color?: string; extruderId?: number; remain?: number }[],
  275. usedTrayIds: Set<number>,
  276. preferLowest?: boolean,
  277. inventoryByTrayId?: Map<number, number>,
  278. ): typeof loadedFilaments[number] | undefined {
  279. let nozzleFilaments = filterFilamentsByNozzle(loadedFilaments, req.nozzle_id);
  280. if (preferLowest) {
  281. nozzleFilaments = [...nozzleFilaments].sort((a, b) =>
  282. compareSortKeys(
  283. preferLowestSortKey(a, inventoryByTrayId),
  284. preferLowestSortKey(b, inventoryByTrayId),
  285. ),
  286. );
  287. }
  288. const exactMatch = nozzleFilaments.find(
  289. (f) =>
  290. !usedTrayIds.has(f.globalTrayId) &&
  291. filamentTypesCompatible(f.type, req.type) &&
  292. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  293. );
  294. const similarMatch = exactMatch
  295. ? undefined
  296. : nozzleFilaments.find(
  297. (f) =>
  298. !usedTrayIds.has(f.globalTrayId) &&
  299. filamentTypesCompatible(f.type, req.type) &&
  300. colorsAreSimilar(f.color, req.color)
  301. );
  302. const typeOnlyMatch =
  303. exactMatch || similarMatch
  304. ? undefined
  305. : nozzleFilaments.find(
  306. (f) => !usedTrayIds.has(f.globalTrayId) && filamentTypesCompatible(f.type, req.type)
  307. );
  308. return exactMatch ?? similarMatch ?? typeOnlyMatch;
  309. }
  310. /**
  311. * Filter loaded filaments to those valid for a given nozzle requirement.
  312. * For single-nozzle printers (nozzle_id is null/undefined), returns all filaments.
  313. */
  314. export function filterFilamentsByNozzle<T extends { extruderId?: number }>(
  315. loadedFilaments: T[],
  316. nozzleId: number | undefined | null,
  317. ): T[] {
  318. return loadedFilaments.filter(
  319. (f) => nozzleId == null || f.extruderId === nozzleId
  320. );
  321. }
  322. /**
  323. * List the distinct nozzle diameters the printer actually reports (#2618).
  324. * Mirrors the backend `_installed_nozzle_diameters`: reads each
  325. * `status.nozzles[].nozzle_diameter`, skips the empty-string / non-positive
  326. * defaults that populate a NozzleInfo before MQTT fills it in, and dedupes.
  327. *
  328. * Returns e.g. `['0.4']` (single-nozzle) or `['0.4', '0.6']` (dual-nozzle). An
  329. * empty array means "the printer hasn't told us its nozzle hardware" — callers
  330. * that need to fetch per-nozzle should fall back to their own default rather
  331. * than treating it as "no nozzles". Preserves the bare decimal string form the
  332. * status carries so it can be passed straight to `getKProfiles`.
  333. */
  334. export function installedNozzleDiameters(
  335. status: { nozzles?: { nozzle_diameter?: string }[] } | null | undefined,
  336. ): string[] {
  337. const seen = new Set<string>();
  338. const result: string[] = [];
  339. for (const nozzle of status?.nozzles ?? []) {
  340. const raw = (nozzle?.nozzle_diameter ?? '').trim();
  341. if (!raw || !(parseFloat(raw) > 0) || seen.has(raw)) continue;
  342. seen.add(raw);
  343. result.push(raw);
  344. }
  345. return result;
  346. }
  347. /**
  348. * Resolve the installed nozzle diameter feeding a given AMS unit, so the
  349. * Configure-AMS-Slot picker filters filament presets by the nozzle actually on
  350. * the machine instead of assuming 0.4mm (#1899).
  351. *
  352. * On dual-nozzle printers (H2D) each AMS is bound to one extruder via
  353. * `ams_extruder_map` (amsId → extruder index, 0=left/primary, 1=right), so we
  354. * read that nozzle's diameter. Single-nozzle printers have no map entry and
  355. * fall back to the primary nozzle (index 0). Returns undefined when the printer
  356. * hasn't reported nozzle hardware yet, letting the caller keep its own default.
  357. * Diameter is the bare decimal string the status carries, e.g. "0.4" / "0.6".
  358. */
  359. export function resolveSlotNozzleDiameter(
  360. status: {
  361. nozzles?: { nozzle_diameter?: string }[];
  362. ams_extruder_map?: Record<string, number>;
  363. } | null | undefined,
  364. amsId: number,
  365. ): string | undefined {
  366. const nozzles = status?.nozzles;
  367. if (!nozzles || nozzles.length === 0) return undefined;
  368. const extruderIdx = status?.ams_extruder_map?.[String(amsId)] ?? 0;
  369. const diameter = nozzles[extruderIdx]?.nozzle_diameter || nozzles[0]?.nozzle_diameter;
  370. return diameter || undefined;
  371. }
  372. /**
  373. * Detect Bambu Lab RFID-tagged spool by tray_uuid (32 hex) or tag_uid (16 hex).
  374. *
  375. * Permissive zero-string check: any non-zero non-empty value returns true. The
  376. * function exists to suppress assign/unassign actions on RFID-managed slots
  377. * whose state is owned by the printer firmware — manual changes there would be
  378. * overwritten on the next RFID re-read (eye → pen icon in BambuStudio).
  379. */
  380. export function isBambuLabSpool(tray: {
  381. tray_uuid?: string | null;
  382. tag_uid?: string | null;
  383. } | null | undefined): boolean {
  384. if (!tray) return false;
  385. if (tray.tray_uuid && tray.tray_uuid !== '00000000000000000000000000000000') return true;
  386. if (tray.tag_uid && tray.tag_uid !== '0000000000000000') return true;
  387. return false;
  388. }
  389. export interface AmsTrayLike {
  390. id: number;
  391. tray_type: string | null | undefined;
  392. tray_sub_brands: string | null | undefined;
  393. tray_color: string | null | undefined;
  394. tray_info_idx: string | null | undefined;
  395. }
  396. export interface AmsUnitLike {
  397. id: number;
  398. tray: AmsTrayLike[];
  399. }
  400. /**
  401. * One row in the AMS Backup modal: a group of slots that back each other up
  402. * (length >= 2), or a single non-empty slot with no peer (length === 1).
  403. */
  404. export interface BackupGroup {
  405. /** Stable key — same across renders for the same material+extruder. */
  406. key: string;
  407. /** Bambu preset ID (tray_info_idx) when matched on preset; null otherwise. */
  408. presetId: string | null;
  409. /** 0 = right / single, 1 = left. Scoping field for dual-nozzle. */
  410. extruder: number;
  411. /** Display name from the first slot's tray_sub_brands (or tray_type). */
  412. displayName: string;
  413. /** Tray colour from the first slot, for the swatch in the modal. */
  414. trayColor: string | null;
  415. /** Member slots, in (ams_id, slot_idx) order. */
  416. members: Array<{ amsId: number; slotIdx: number; globalTrayId: number }>;
  417. }
  418. /**
  419. * Canonicalise a hex colour for identity comparison. Mirrors the backend
  420. * `_normalize_color_for_id`. Strips the leading `#`, uppercases, and drops
  421. * the alpha channel when 8 chars long so `1A1A1AFF` matches `1A1A1A`.
  422. */
  423. function normalizeColorForId(raw: string | null | undefined): string {
  424. let s = (raw || '').trim().replace(/^#/, '').toUpperCase();
  425. if (s.length === 8) s = s.slice(0, 6);
  426. return s;
  427. }
  428. /**
  429. * Compute backup pairs for the AMS Backup modal (#1762).
  430. *
  431. * Strict identity rule (mirrors backend `_material_identity_internal` /
  432. * `_material_identity_spoolman`): slots pair ONLY when they share the same
  433. * Bambu preset ID (`tray_info_idx`, e.g. "GFA00") AND the same colour. The
  434. * preset identifies the filament profile (PETG HF, PLA Basic, etc.); the
  435. * colour pins the variant — three PETG HF spools in different colours
  436. * absolutely don't back each other up. User-tagged spools without a preset
  437. * never pair — Bambu's firmware backup logic relies on the preset, and
  438. * pairing on cosmetic name/colour match alone would let two visually-
  439. * identical but materially-different spools be treated as backups.
  440. *
  441. * Empty slots are skipped entirely. Every non-empty slot is returned — slots
  442. * without a peer come back as 1-member entries so the modal can list them as
  443. * "Slots without a backup peer".
  444. *
  445. * On dual-extruder printers (H2D / H2C / X2D), pairs are scoped per extruder
  446. * side — the firmware can't cross extruders even with the global backup bit
  447. * set.
  448. */
  449. export function computeBackupGroups(
  450. amsUnits: AmsUnitLike[] | undefined,
  451. amsExtruderMap: Record<string, number> | undefined,
  452. isDualNozzle: boolean,
  453. ): BackupGroup[] {
  454. if (!amsUnits || amsUnits.length === 0) return [];
  455. // Defensive dedup: ``status.ams`` is expected to be unique by `ams.id`, but
  456. // observed in the wild to occasionally contain duplicate entries (e.g. on
  457. // VP-aggregated switch printers or during MQTT partial-update merges). A
  458. // duplicate would surface as "AMS-A slot 1" rendered twice with different
  459. // materials, which is impossible physically and visually broken. First
  460. // occurrence per `ams.id` wins.
  461. const seenIds = new Set<number>();
  462. const uniqueAms: AmsUnitLike[] = [];
  463. for (const ams of amsUnits) {
  464. if (seenIds.has(ams.id)) continue;
  465. seenIds.add(ams.id);
  466. uniqueAms.push(ams);
  467. }
  468. const byKey = new Map<string, BackupGroup>();
  469. for (const ams of uniqueAms) {
  470. const extruder = isDualNozzle ? Number(amsExtruderMap?.[String(ams.id)] ?? 0) : 0;
  471. ams.tray.forEach((tray, slotIdx) => {
  472. if (!tray?.tray_type) return; // empty slot
  473. const preset = (tray.tray_info_idx || '').trim();
  474. const globalTrayId = getGlobalTrayId(ams.id, slotIdx, false);
  475. const member = { amsId: ams.id, slotIdx, globalTrayId };
  476. let key: string;
  477. let presetId: string | null;
  478. if (preset) {
  479. // Same Bambu profile is necessary but NOT sufficient — different colours
  480. // of the same PETG HF profile can't back each other up. Bake the colour
  481. // into the identity key, normalised to strip alpha and case.
  482. const color = normalizeColorForId(tray.tray_color);
  483. key = `preset:${preset}|color:${color}#${extruder}`;
  484. presetId = preset;
  485. } else {
  486. // No preset → never group with anything else. Unique-per-slot key.
  487. key = `unmatched:${ams.id}:${slotIdx}#${extruder}`;
  488. presetId = null;
  489. }
  490. const existing = byKey.get(key);
  491. if (existing) {
  492. existing.members.push(member);
  493. } else {
  494. byKey.set(key, {
  495. key,
  496. presetId,
  497. extruder,
  498. displayName: tray.tray_sub_brands || tray.tray_type || '',
  499. trayColor: tray.tray_color ?? null,
  500. members: [member],
  501. });
  502. }
  503. });
  504. }
  505. // Stable sort: extruder first (so the modal can section per side on
  506. // dual-nozzle), then pairs before lone slots, then by name, then by first
  507. // member's global tray id for deterministic rendering.
  508. return Array.from(byKey.values()).sort((a, b) => {
  509. if (a.extruder !== b.extruder) return a.extruder - b.extruder;
  510. const aLone = a.members.length === 1 ? 1 : 0;
  511. const bLone = b.members.length === 1 ? 1 : 0;
  512. if (aLone !== bLone) return aLone - bLone;
  513. if (a.displayName !== b.displayName) return a.displayName.localeCompare(b.displayName);
  514. return a.members[0].globalTrayId - b.members[0].globalTrayId;
  515. });
  516. }